var kf=Object.defineProperty;var Sf=(nr,Xr,ri)=>Xr in nr?kf(nr,Xr,{enumerable:!0,configurable:!0,writable:!0,value:ri}):nr[Xr]=ri;var ge=(nr,Xr,ri)=>Sf(nr,typeof Xr!="symbol"?Xr+"":Xr,ri);(function(){"use strict";var nr={},Xr={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(De,A,r)=>{De.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(De,A,r)=>{r.r(A),r.d(A,{Environment:()=>Ze,Interpreter:()=>at,Template:()=>ht,parse:()=>te,tokenize:()=>M});var f=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"}),L=Object.freeze({set:f.Set,for:f.For,in:f.In,is:f.Is,if:f.If,else:f.Else,endif:f.EndIf,elif:f.ElseIf,endfor:f.EndFor,and:f.And,or:f.Or,not:f.Not,"not in":f.NotIn,macro:f.Macro,endmacro:f.EndMacro,true:f.BooleanLiteral,false:f.BooleanLiteral,none:f.NullLiteral,True:f.BooleanLiteral,False:f.BooleanLiteral,None:f.NullLiteral}),j=class{constructor(I,ne){this.value=I,this.type=ne}};function J(I){return/\w/.test(I)}function W(I){return/[0-9]/.test(I)}var w=[["{%",f.OpenStatement],["%}",f.CloseStatement],["{{",f.OpenExpression],["}}",f.CloseExpression],["(",f.OpenParen],[")",f.CloseParen],["{",f.OpenCurlyBracket],["}",f.CloseCurlyBracket],["[",f.OpenSquareBracket],["]",f.CloseSquareBracket],[",",f.Comma],[".",f.Dot],[":",f.Colon],["|",f.Pipe],["<=",f.ComparisonBinaryOperator],[">=",f.ComparisonBinaryOperator],["==",f.ComparisonBinaryOperator],["!=",f.ComparisonBinaryOperator],["<",f.ComparisonBinaryOperator],[">",f.ComparisonBinaryOperator],["+",f.AdditiveBinaryOperator],["-",f.AdditiveBinaryOperator],["*",f.MultiplicativeBinaryOperator],["/",f.MultiplicativeBinaryOperator],["%",f.MultiplicativeBinaryOperator],["=",f.Equals]],v=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function y(I,ne={}){return I.endsWith(` `)&&(I=I.slice(0,-1)),I=I.replace(/{#.*?#}/gs,"{##}"),ne.lstrip_blocks&&(I=I.replace(/^[ \t]*({[#%])/gm,"$1")),ne.trim_blocks&&(I=I.replace(/([#%]})\n/g,"$1")),I.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function M(I,ne={}){var rt,pt,It;const K=[],ce=y(I,ne);let Ie=0;const Qe=St=>{let Ft="";for(;St(ce[Ie]);){if(ce[Ie]==="\\"){if(++Ie,Ie>=ce.length)throw new SyntaxError("Unexpected end of input");const At=ce[Ie++],ns=v.get(At);if(ns===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);Ft+=ns;continue}if(Ft+=ce[Ie++],Ie>=ce.length)throw new SyntaxError("Unexpected end of input")}return Ft};e:for(;Ie0){K.push(new j(At,f.Text));continue}}Qe(At=>/\s/.test(At));const Ft=ce[Ie];if(Ft==="-"||Ft==="+"){const At=(pt=K.at(-1))==null?void 0:pt.type;if(At===f.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${Ft}`);switch(At){case f.Identifier:case f.NumericLiteral:case f.BooleanLiteral:case f.NullLiteral:case f.StringLiteral:case f.CloseParen:case f.CloseSquareBracket:break;default:{++Ie;const ns=Qe(W);K.push(new j(`${Ft}${ns}`,ns.length>0?f.NumericLiteral:f.UnaryOperator));continue}}}for(const[At,ns]of w)if(ce.slice(Ie,Ie+At.length)===At){K.push(new j(At,ns)),Ie+=At.length;continue e}if(Ft==="'"||Ft==='"'){++Ie;const At=Qe(ns=>ns!==Ft);K.push(new j(At,f.StringLiteral)),++Ie;continue}if(W(Ft)){const At=Qe(W);K.push(new j(At,f.NumericLiteral));continue}if(J(Ft)){const At=Qe(J),ns=Object.hasOwn(L,At)?L[At]:f.Identifier;ns===f.In&&((It=K.at(-1))==null?void 0:It.type)===f.Not?(K.pop(),K.push(new j("not in",f.NotIn))):K.push(new j(At,ns));continue}throw new SyntaxError(`Unexpected character: ${Ft}`)}return K}var b=class{constructor(){ge(this,"type","Statement")}},D=class extends b{constructor(ne){super();ge(this,"type","Program");this.body=ne}},H=class extends b{constructor(ne,K,ce){super();ge(this,"type","If");this.test=ne,this.body=K,this.alternate=ce}},re=class extends b{constructor(ne,K,ce,Ie){super();ge(this,"type","For");this.loopvar=ne,this.iterable=K,this.body=ce,this.defaultBlock=Ie}},ie=class extends b{constructor(ne,K){super();ge(this,"type","Set");this.assignee=ne,this.value=K}},z=class extends b{constructor(ne,K,ce){super();ge(this,"type","Macro");this.name=ne,this.args=K,this.body=ce}},V=class extends b{constructor(){super(...arguments);ge(this,"type","Expression")}},Q=class extends V{constructor(ne,K,ce){super();ge(this,"type","MemberExpression");this.object=ne,this.property=K,this.computed=ce}},F=class extends V{constructor(ne,K){super();ge(this,"type","CallExpression");this.callee=ne,this.args=K}},$=class extends V{constructor(ne){super();ge(this,"type","Identifier");this.value=ne}},g=class extends V{constructor(ne){super();ge(this,"type","Literal");this.value=ne}},C=class extends g{constructor(){super(...arguments);ge(this,"type","NumericLiteral")}},T=class extends g{constructor(){super(...arguments);ge(this,"type","StringLiteral")}},ee=class extends g{constructor(){super(...arguments);ge(this,"type","BooleanLiteral")}},Y=class extends g{constructor(){super(...arguments);ge(this,"type","NullLiteral")}},le=class extends g{constructor(){super(...arguments);ge(this,"type","ArrayLiteral")}},de=class extends g{constructor(){super(...arguments);ge(this,"type","TupleLiteral")}},fe=class extends g{constructor(){super(...arguments);ge(this,"type","ObjectLiteral")}},Pe=class extends V{constructor(ne,K,ce){super();ge(this,"type","BinaryExpression");this.operator=ne,this.left=K,this.right=ce}},xe=class extends V{constructor(ne,K){super();ge(this,"type","FilterExpression");this.operand=ne,this.filter=K}},Le=class extends V{constructor(ne,K){super();ge(this,"type","SelectExpression");this.iterable=ne,this.test=K}},qe=class extends V{constructor(ne,K,ce){super();ge(this,"type","TestExpression");this.operand=ne,this.negate=K,this.test=ce}},je=class extends V{constructor(ne,K){super();ge(this,"type","UnaryExpression");this.operator=ne,this.argument=K}},dt=class extends V{constructor(ne=void 0,K=void 0,ce=void 0){super();ge(this,"type","SliceExpression");this.start=ne,this.stop=K,this.step=ce}},ue=class extends V{constructor(ne,K){super();ge(this,"type","KeywordArgumentExpression");this.key=ne,this.value=K}};function te(I){const ne=new D([]);let K=0;function ce(nt,gt){const Ot=I[K++];if(!Ot||Ot.type!==nt)throw new Error(`Parser Error: ${gt}. ${Ot.type} !== ${nt}.`);return Ot}function Ie(){switch(I[K].type){case f.Text:return pt();case f.OpenStatement:return It();case f.OpenExpression:return St();default:throw new SyntaxError(`Unexpected token type: ${I[K].type}`)}}function Qe(...nt){return K+nt.length<=I.length&&nt.some((gt,Ot)=>gt!==I[K+Ot].type)}function rt(...nt){return K+nt.length<=I.length&&nt.every((gt,Ot)=>gt===I[K+Ot].type)}function pt(){return new T(ce(f.Text,"Expected text token").value)}function It(){ce(f.OpenStatement,"Expected opening statement token");let nt;switch(I[K].type){case f.Set:++K,nt=Ft(),ce(f.CloseStatement,"Expected closing statement token");break;case f.If:++K,nt=At(),ce(f.OpenStatement,"Expected {% token"),ce(f.EndIf,"Expected endif token"),ce(f.CloseStatement,"Expected %} token");break;case f.Macro:++K,nt=ns(),ce(f.OpenStatement,"Expected {% token"),ce(f.EndMacro,"Expected endmacro token"),ce(f.CloseStatement,"Expected %} token");break;case f.For:++K,nt=Ss(),ce(f.OpenStatement,"Expected {% token"),ce(f.EndFor,"Expected endfor token"),ce(f.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${I[K].type}`)}return nt}function St(){ce(f.OpenExpression,"Expected opening expression token");const nt=As();return ce(f.CloseExpression,"Expected closing expression token"),nt}function Ft(){const nt=As();if(rt(f.Equals)){++K;const gt=Ft();return new ie(nt,gt)}return nt}function At(){var ls,vr,ts,er,Rr,Zr,Nr,Tr;const nt=As();ce(f.CloseStatement,"Expected closing statement token");const gt=[],Ot=[];for(;!(((ls=I[K])==null?void 0:ls.type)===f.OpenStatement&&(((vr=I[K+1])==null?void 0:vr.type)===f.ElseIf||((ts=I[K+1])==null?void 0:ts.type)===f.Else||((er=I[K+1])==null?void 0:er.type)===f.EndIf));)gt.push(Ie());if(((Rr=I[K])==null?void 0:Rr.type)===f.OpenStatement&&((Zr=I[K+1])==null?void 0:Zr.type)!==f.EndIf)if(++K,rt(f.ElseIf))ce(f.ElseIf,"Expected elseif token"),Ot.push(At());else for(ce(f.Else,"Expected else token"),ce(f.CloseStatement,"Expected closing statement token");!(((Nr=I[K])==null?void 0:Nr.type)===f.OpenStatement&&((Tr=I[K+1])==null?void 0:Tr.type)===f.EndIf);)Ot.push(Ie());return new H(nt,gt,Ot)}function ns(){const nt=ar();if(nt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const gt=Br();ce(f.CloseStatement,"Expected closing statement token");const Ot=[];for(;Qe(f.OpenStatement,f.EndMacro);)Ot.push(Ie());return new z(nt,gt,Ot)}function gs(nt=!1){const gt=nt?ar:As,Ot=[gt()],ls=rt(f.Comma);for(;ls&&(++K,Ot.push(gt()),!!rt(f.Comma)););return ls?new de(Ot):Ot[0]}function Ss(){const nt=gs(!0);if(!(nt instanceof $||nt instanceof de))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${nt.type} instead`);ce(f.In,"Expected `in` keyword following loop variable");const gt=As();ce(f.CloseStatement,"Expected closing statement token");const Ot=[];for(;Qe(f.OpenStatement,f.EndFor)&&Qe(f.OpenStatement,f.Else);)Ot.push(Ie());const ls=[];if(rt(f.OpenStatement,f.Else))for(++K,++K,ce(f.CloseStatement,"Expected closing statement token");Qe(f.OpenStatement,f.EndFor);)ls.push(Ie());return new re(nt,gt,Ot,ls)}function As(){return Xs()}function Xs(){const nt=ir();if(rt(f.If)){++K;const gt=ir();if(rt(f.Else)){++K;const Ot=ir();return new H(gt,[nt],[Ot])}else return new Le(nt,gt)}return nt}function ir(){let nt=Qr();for(;rt(f.Or);){const gt=I[K];++K;const Ot=Qr();nt=new Pe(gt,nt,Ot)}return nt}function Qr(){let nt=zr();for(;rt(f.And);){const gt=I[K];++K;const Ot=zr();nt=new Pe(gt,nt,Ot)}return nt}function zr(){let nt;for(;rt(f.Not);){const gt=I[K];++K;const Ot=zr();nt=new je(gt,Ot)}return nt??br()}function br(){let nt=Nt();for(;rt(f.ComparisonBinaryOperator)||rt(f.In)||rt(f.NotIn);){const gt=I[K];++K;const Ot=Nt();nt=new Pe(gt,nt,Ot)}return nt}function Nt(){let nt=pr();for(;rt(f.AdditiveBinaryOperator);){const gt=I[K];++K;const Ot=pr();nt=new Pe(gt,nt,Ot)}return nt}function Yr(){const nt=$r();return rt(f.OpenParen)?kr(nt):nt}function kr(nt){let gt=new F(nt,Br());return rt(f.OpenParen)&&(gt=kr(gt)),gt}function Br(){ce(f.OpenParen,"Expected opening parenthesis for arguments list");const nt=Sr();return ce(f.CloseParen,"Expected closing parenthesis for arguments list"),nt}function Sr(){const nt=[];for(;!rt(f.CloseParen);){let gt=As();if(rt(f.Equals)){if(++K,!(gt instanceof $))throw new SyntaxError("Expected identifier for keyword argument");const Ot=As();gt=new ue(gt,Ot)}nt.push(gt),rt(f.Comma)&&++K}return nt}function or(){const nt=[];let gt=!1;for(;!rt(f.CloseSquareBracket);)rt(f.Colon)?(nt.push(void 0),++K,gt=!0):(nt.push(As()),rt(f.Colon)&&(++K,gt=!0));if(nt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(gt){if(nt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new dt(...nt)}return nt[0]}function $r(){let nt=ar();for(;rt(f.Dot)||rt(f.OpenSquareBracket);){const gt=I[K];++K;let Ot;const ls=gt.type!==f.Dot;if(ls)Ot=or(),ce(f.CloseSquareBracket,"Expected closing square bracket");else if(Ot=ar(),Ot.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");nt=new Q(nt,Ot,ls)}return nt}function pr(){let nt=Ar();for(;rt(f.MultiplicativeBinaryOperator);){const gt=I[K];++K;const Ot=Ar();nt=new Pe(gt,nt,Ot)}return nt}function Ar(){let nt=Jr();for(;rt(f.Is);){++K;const gt=rt(f.Not);gt&&++K;let Ot=ar();if(Ot instanceof ee?Ot=new $(Ot.value.toString()):Ot instanceof Y&&(Ot=new $("none")),!(Ot instanceof $))throw new SyntaxError("Expected identifier for the test");nt=new qe(nt,gt,Ot)}return nt}function Jr(){let nt=Yr();for(;rt(f.Pipe);){++K;let gt=ar();if(!(gt instanceof $))throw new SyntaxError("Expected identifier for the filter");rt(f.OpenParen)&&(gt=kr(gt)),nt=new xe(nt,gt)}return nt}function ar(){const nt=I[K];switch(nt.type){case f.NumericLiteral:return++K,new C(Number(nt.value));case f.StringLiteral:return++K,new T(nt.value);case f.BooleanLiteral:return++K,new ee(nt.value.toLowerCase()==="true");case f.NullLiteral:return++K,new Y(null);case f.Identifier:return++K,new $(nt.value);case f.OpenParen:{++K;const gt=gs();if(I[K].type!==f.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${I[K].type} instead`);return++K,gt}case f.OpenSquareBracket:{++K;const gt=[];for(;!rt(f.CloseSquareBracket);)gt.push(As()),rt(f.Comma)&&++K;return++K,new le(gt)}case f.OpenCurlyBracket:{++K;const gt=new Map;for(;!rt(f.CloseCurlyBracket);){const Ot=As();ce(f.Colon,"Expected colon between key and value in object literal");const ls=As();gt.set(Ot,ls),rt(f.Comma)&&++K}return++K,new fe(gt)}default:throw new SyntaxError(`Unexpected token: ${nt.type}`)}}for(;K=0?(ne=(ne??(ne=0))<0?Math.max(I.length+ne,0):Math.min(ne,I.length),K=(K??(K=I.length))<0?Math.max(I.length+K,0):Math.min(K,I.length)):(ne=(ne??(ne=I.length-1))<0?Math.max(I.length+ne,-1):Math.min(ne,I.length-1),K=(K??(K=-1))<-1?Math.max(I.length+K,-1):Math.min(K,I.length-1));const Qe=[];for(let rt=ne;Ie*rtne.toUpperCase())}var et=class{constructor(I=void 0){ge(this,"type","RuntimeValue");ge(this,"value");ge(this,"builtins",new Map);this.value=I}__bool__(){return new Je(!!this.value)}},Xe=class extends et{constructor(){super(...arguments);ge(this,"type","NumericValue")}},oe=class extends et{constructor(){super(...arguments);ge(this,"type","StringValue");ge(this,"builtins",new Map([["upper",new We(()=>new oe(this.value.toUpperCase()))],["lower",new We(()=>new oe(this.value.toLowerCase()))],["strip",new We(()=>new oe(this.value.trim()))],["title",new We(()=>new oe(ze(this.value)))],["length",new Xe(this.value.length)],["rstrip",new We(()=>new oe(this.value.trimEnd()))],["lstrip",new We(()=>new oe(this.value.trimStart()))]]))}},Je=class extends et{constructor(){super(...arguments);ge(this,"type","BooleanValue")}},Fe=class extends et{constructor(){super(...arguments);ge(this,"type","ObjectValue");ge(this,"builtins",new Map([["get",new We(([ne,K])=>{if(!(ne instanceof oe))throw new Error(`Object key must be a string: got ${ne.type}`);return this.value.get(ne.value)??K??new Ve})],["items",new We(()=>new ve(Array.from(this.value.entries()).map(([ne,K])=>new ve([new oe(ne),K]))))]]))}__bool__(){return new Je(this.value.size>0)}},pe=class extends Fe{constructor(){super(...arguments);ge(this,"type","KeywordArgumentsValue")}},ve=class extends et{constructor(){super(...arguments);ge(this,"type","ArrayValue");ge(this,"builtins",new Map([["length",new Xe(this.value.length)]]))}__bool__(){return new Je(this.value.length>0)}},Re=class extends ve{constructor(){super(...arguments);ge(this,"type","TupleValue")}},We=class extends et{constructor(){super(...arguments);ge(this,"type","FunctionValue")}},Ve=class extends et{constructor(){super(...arguments);ge(this,"type","NullValue")}},Ne=class extends et{constructor(){super(...arguments);ge(this,"type","UndefinedValue")}},Ze=class{constructor(I){ge(this,"variables",new Map([["namespace",new We(I=>{if(I.length===0)return new Fe(new Map);if(I.length!==1||!(I[0]instanceof Fe))throw new Error("`namespace` expects either zero arguments or a single object argument");return I[0]})]]));ge(this,"tests",new Map([["boolean",I=>I.type==="BooleanValue"],["callable",I=>I instanceof We],["odd",I=>{if(I.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${I.type}`);return I.value%2!==0}],["even",I=>{if(I.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${I.type}`);return I.value%2===0}],["false",I=>I.type==="BooleanValue"&&!I.value],["true",I=>I.type==="BooleanValue"&&I.value],["none",I=>I.type==="NullValue"],["string",I=>I.type==="StringValue"],["number",I=>I.type==="NumericValue"],["integer",I=>I.type==="NumericValue"&&Number.isInteger(I.value)],["iterable",I=>I.type==="ArrayValue"||I.type==="StringValue"],["mapping",I=>I.type==="ObjectValue"],["lower",I=>{const ne=I.value;return I.type==="StringValue"&&ne===ne.toLowerCase()}],["upper",I=>{const ne=I.value;return I.type==="StringValue"&&ne===ne.toUpperCase()}],["none",I=>I.type==="NullValue"],["defined",I=>I.type!=="UndefinedValue"],["undefined",I=>I.type==="UndefinedValue"],["equalto",(I,ne)=>I.value===ne.value],["eq",(I,ne)=>I.value===ne.value]]));this.parent=I}set(I,ne){return this.declareVariable(I,ft(ne))}declareVariable(I,ne){if(this.variables.has(I))throw new SyntaxError(`Variable already declared: ${I}`);return this.variables.set(I,ne),ne}setVariable(I,ne){return this.variables.set(I,ne),ne}resolve(I){if(this.variables.has(I))return this;if(this.parent)return this.parent.resolve(I);throw new Error(`Unknown variable: ${I}`)}lookupVariable(I){try{return this.resolve(I).variables.get(I)??new Ne}catch{return new Ne}}},at=class{constructor(I){ge(this,"global");this.global=I??new Ze}run(I){return this.evaluate(I,this.global)}evaluateBinaryExpression(I,ne){const K=this.evaluate(I.left,ne);switch(I.operator.value){case"and":return K.__bool__().value?this.evaluate(I.right,ne):K;case"or":return K.__bool__().value?K:this.evaluate(I.right,ne)}const ce=this.evaluate(I.right,ne);switch(I.operator.value){case"==":return new Je(K.value==ce.value);case"!=":return new Je(K.value!=ce.value)}if(K instanceof Ne||ce instanceof Ne)throw new Error("Cannot perform operation on undefined values");if(K instanceof Ve||ce instanceof Ve)throw new Error("Cannot perform operation on null values");if(K instanceof Xe&&ce instanceof Xe)switch(I.operator.value){case"+":return new Xe(K.value+ce.value);case"-":return new Xe(K.value-ce.value);case"*":return new Xe(K.value*ce.value);case"/":return new Xe(K.value/ce.value);case"%":return new Xe(K.value%ce.value);case"<":return new Je(K.value":return new Je(K.value>ce.value);case">=":return new Je(K.value>=ce.value);case"<=":return new Je(K.value<=ce.value)}else if(K instanceof ve&&ce instanceof ve)switch(I.operator.value){case"+":return new ve(K.value.concat(ce.value))}else if(ce instanceof ve){const Ie=ce.value.find(Qe=>Qe.value===K.value)!==void 0;switch(I.operator.value){case"in":return new Je(Ie);case"not in":return new Je(!Ie)}}if(K instanceof oe||ce instanceof oe)switch(I.operator.value){case"+":return new oe(K.value.toString()+ce.value.toString())}if(K instanceof oe&&ce instanceof oe)switch(I.operator.value){case"in":return new Je(ce.value.includes(K.value));case"not in":return new Je(!ce.value.includes(K.value))}if(K instanceof oe&&ce instanceof Fe)switch(I.operator.value){case"in":return new Je(ce.value.has(K.value));case"not in":return new Je(!ce.value.has(K.value))}throw new SyntaxError(`Unknown operator "${I.operator.value}" between ${K.type} and ${ce.type}`)}evaluateArguments(I,ne){const K=[],ce=new Map;for(const Ie of I)if(Ie.type==="KeywordArgumentExpression"){const Qe=Ie;ce.set(Qe.key.value,this.evaluate(Qe.value,ne))}else{if(ce.size>0)throw new Error("Positional arguments must come before keyword arguments");K.push(this.evaluate(Ie,ne))}return[K,ce]}evaluateFilterExpression(I,ne){const K=this.evaluate(I.operand,ne);if(I.filter.type==="Identifier"){const ce=I.filter;if(ce.value==="tojson")return new oe(lt(K));if(K instanceof ve)switch(ce.value){case"list":return K;case"first":return K.value[0];case"last":return K.value[K.value.length-1];case"length":return new Xe(K.value.length);case"reverse":return new ve(K.value.reverse());case"sort":return new ve(K.value.sort((Ie,Qe)=>{if(Ie.type!==Qe.type)throw new Error(`Cannot compare different types: ${Ie.type} and ${Qe.type}`);switch(Ie.type){case"NumericValue":return Ie.value-Qe.value;case"StringValue":return Ie.value.localeCompare(Qe.value);default:throw new Error(`Cannot compare type: ${Ie.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${ce.value}`)}else if(K instanceof oe)switch(ce.value){case"length":return new Xe(K.value.length);case"upper":return new oe(K.value.toUpperCase());case"lower":return new oe(K.value.toLowerCase());case"title":return new oe(ze(K.value));case"capitalize":return new oe(K.value.charAt(0).toUpperCase()+K.value.slice(1));case"trim":return new oe(K.value.trim());case"indent":return new oe(K.value.split(` `).map((Ie,Qe)=>Qe===0||Ie.length===0?Ie:" "+Ie).join(` `));case"string":return K;default:throw new Error(`Unknown StringValue filter: ${ce.value}`)}else if(K instanceof Xe)switch(ce.value){case"abs":return new Xe(Math.abs(K.value));default:throw new Error(`Unknown NumericValue filter: ${ce.value}`)}else if(K instanceof Fe)switch(ce.value){case"items":return new ve(Array.from(K.value.entries()).map(([Ie,Qe])=>new ve([new oe(Ie),Qe])));case"length":return new Xe(K.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ce.value}`)}throw new Error(`Cannot apply filter "${ce.value}" to type: ${K.type}`)}else if(I.filter.type==="CallExpression"){const ce=I.filter;if(ce.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ce.callee.type}`);const Ie=ce.callee.value;if(Ie==="tojson"){const[,Qe]=this.evaluateArguments(ce.args,ne),rt=Qe.get("indent")??new Ve;if(!(rt instanceof Xe||rt instanceof Ve))throw new Error("If set, indent must be a number");return new oe(lt(K,rt.value))}if(K instanceof ve){switch(Ie){case"selectattr":case"rejectattr":{const Qe=Ie==="selectattr";if(K.value.some(At=>!(At instanceof Fe)))throw new Error(`\`${Ie}\` can only be applied to array of objects`);if(ce.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${Ie}\` must be strings`);const[rt,pt,It]=ce.args.map(At=>this.evaluate(At,ne));let St;if(pt){const At=ne.tests.get(pt.value);if(!At)throw new Error(`Unknown test: ${pt.value}`);St=At}else St=(...At)=>At[0].__bool__().value;const Ft=K.value.filter(At=>{const ns=At.value.get(rt.value),gs=ns?St(ns,It):!1;return Qe?gs:!gs});return new ve(Ft)}case"map":{const[,Qe]=this.evaluateArguments(ce.args,ne);if(Qe.has("attribute")){const rt=Qe.get("attribute");if(!(rt instanceof oe))throw new Error("attribute must be a string");const pt=Qe.get("default"),It=K.value.map(St=>{if(!(St instanceof Fe))throw new Error("items in map must be an object");return St.value.get(rt.value)??pt??new Ne});return new ve(It)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Ie}`)}else if(K instanceof oe){switch(Ie){case"indent":{const[Qe,rt]=this.evaluateArguments(ce.args,ne),pt=Qe.at(0)??rt.get("width")??new Xe(4);if(!(pt instanceof Xe))throw new Error("width must be a number");const It=Qe.at(1)??rt.get("first")??new Je(!1),St=Qe.at(2)??rt.get("blank")??new Je(!1),Ft=K.value.split(` `),At=" ".repeat(pt.value),ns=Ft.map((gs,Ss)=>!It.value&&Ss===0||!St.value&&gs.length===0?gs:At+gs);return new oe(ns.join(` `))}}throw new Error(`Unknown StringValue filter: ${Ie}`)}else throw new Error(`Cannot apply filter "${Ie}" to type: ${K.type}`)}throw new Error(`Unknown filter: ${I.filter.type}`)}evaluateTestExpression(I,ne){const K=this.evaluate(I.operand,ne),ce=ne.tests.get(I.test.value);if(!ce)throw new Error(`Unknown test: ${I.test.value}`);const Ie=ce(K);return new Je(I.negate?!Ie:Ie)}evaluateUnaryExpression(I,ne){const K=this.evaluate(I.argument,ne);switch(I.operator.value){case"not":return new Je(!K.value);default:throw new SyntaxError(`Unknown operator: ${I.operator.value}`)}}evalProgram(I,ne){return this.evaluateBlock(I.body,ne)}evaluateBlock(I,ne){let K="";for(const ce of I){const Ie=this.evaluate(ce,ne);Ie.type!=="NullValue"&&Ie.type!=="UndefinedValue"&&(K+=Ie.value)}return new oe(K)}evaluateIdentifier(I,ne){return ne.lookupVariable(I.value)}evaluateCallExpression(I,ne){const[K,ce]=this.evaluateArguments(I.args,ne);ce.size>0&&K.push(new pe(ce));const Ie=this.evaluate(I.callee,ne);if(Ie.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Ie.type}`);return Ie.value(K,ne)}evaluateSliceExpression(I,ne,K){if(!(I instanceof ve||I instanceof oe))throw new Error("Slice object must be an array or string");const ce=this.evaluate(ne.start,K),Ie=this.evaluate(ne.stop,K),Qe=this.evaluate(ne.step,K);if(!(ce instanceof Xe||ce instanceof Ne))throw new Error("Slice start must be numeric or undefined");if(!(Ie instanceof Xe||Ie instanceof Ne))throw new Error("Slice stop must be numeric or undefined");if(!(Qe instanceof Xe||Qe instanceof Ne))throw new Error("Slice step must be numeric or undefined");return I instanceof ve?new ve(Te(I.value,ce.value,Ie.value,Qe.value)):new oe(Te(Array.from(I.value),ce.value,Ie.value,Qe.value).join(""))}evaluateMemberExpression(I,ne){const K=this.evaluate(I.object,ne);let ce;if(I.computed){if(I.property.type==="SliceExpression")return this.evaluateSliceExpression(K,I.property,ne);ce=this.evaluate(I.property,ne)}else ce=new oe(I.property.value);let Ie;if(K instanceof Fe){if(!(ce instanceof oe))throw new Error(`Cannot access property with non-string: got ${ce.type}`);Ie=K.value.get(ce.value)??K.builtins.get(ce.value)}else if(K instanceof ve||K instanceof oe)if(ce instanceof Xe)Ie=K.value.at(ce.value),K instanceof oe&&(Ie=new oe(K.value.at(ce.value)));else if(ce instanceof oe)Ie=K.builtins.get(ce.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ce.type}`);else{if(!(ce instanceof oe))throw new Error(`Cannot access property with non-string: got ${ce.type}`);Ie=K.builtins.get(ce.value)}return Ie instanceof et?Ie:new Ne}evaluateSet(I,ne){const K=this.evaluate(I.value,ne);if(I.assignee.type==="Identifier"){const ce=I.assignee.value;ne.setVariable(ce,K)}else if(I.assignee.type==="MemberExpression"){const ce=I.assignee,Ie=this.evaluate(ce.object,ne);if(!(Ie instanceof Fe))throw new Error("Cannot assign to member of non-object");if(ce.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Ie.value.set(ce.property.value,K)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(I.assignee)}`);return new Ve}evaluateIf(I,ne){const K=this.evaluate(I.test,ne);return this.evaluateBlock(K.__bool__().value?I.body:I.alternate,ne)}evaluateFor(I,ne){const K=new Ze(ne);let ce,Ie;if(I.iterable.type==="SelectExpression"){const St=I.iterable;Ie=this.evaluate(St.iterable,K),ce=St.test}else Ie=this.evaluate(I.iterable,K);if(!(Ie instanceof ve))throw new Error(`Expected iterable type in for loop: got ${Ie.type}`);const Qe=[],rt=[];for(let St=0;Stgs.setVariable(I.loopvar.value,At);else if(I.loopvar.type==="TupleLiteral"){const gs=I.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const Ss=At;if(gs.value.length!==Ss.value.length)throw new Error(`Too ${gs.value.length>Ss.value.length?"few":"many"} items to unpack`);ns=As=>{for(let Xs=0;Xs0?Qe[St-1]:new Ne],["nextitem",St{var rt;const Ie=new Ze(ce);K=K.slice();let Qe;((rt=K.at(-1))==null?void 0:rt.type)==="KeywordArgumentsValue"&&(Qe=K.pop());for(let pt=0;ptthis.evaluate(K,ne)));case"TupleLiteral":return new Re(I.value.map(K=>this.evaluate(K,ne)));case"ObjectLiteral":{const K=new Map;for(const[ce,Ie]of I.value){const Qe=this.evaluate(ce,ne);if(!(Qe instanceof oe))throw new Error(`Object keys must be strings: got ${Qe.type}`);K.set(Qe.value,this.evaluate(Ie,ne))}return new Fe(K)}case"Identifier":return this.evaluateIdentifier(I,ne);case"CallExpression":return this.evaluateCallExpression(I,ne);case"MemberExpression":return this.evaluateMemberExpression(I,ne);case"UnaryExpression":return this.evaluateUnaryExpression(I,ne);case"BinaryExpression":return this.evaluateBinaryExpression(I,ne);case"FilterExpression":return this.evaluateFilterExpression(I,ne);case"TestExpression":return this.evaluateTestExpression(I,ne);default:throw new SyntaxError(`Unknown node type: ${I.type}`)}}};function ft(I){switch(typeof I){case"number":return new Xe(I);case"string":return new oe(I);case"boolean":return new Je(I);case"undefined":return new Ne;case"object":return I===null?new Ve:Array.isArray(I)?new ve(I.map(ft)):new Fe(new Map(Object.entries(I).map(([ne,K])=>[ne,ft(K)])));case"function":return new We((ne,K)=>{const ce=I(...ne.map(Ie=>Ie.value))??null;return ft(ce)});default:throw new Error(`Cannot convert to runtime value: ${I}`)}}function lt(I,ne,K){const ce=K??0;switch(I.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(I.value);case"ArrayValue":case"ObjectValue":{const Ie=ne?" ".repeat(ne):"",Qe=` `+Ie.repeat(ce),rt=Qe+Ie;if(I.type==="ArrayValue"){const pt=I.value.map(It=>lt(It,ne,ce+1));return ne?`[${rt}${pt.join(`,${rt}`)}${Qe}]`:`[${pt.join(", ")}]`}else{const pt=Array.from(I.value.entries()).map(([It,St])=>{const Ft=`"${It}": ${lt(St,ne,ce+1)}`;return ne?`${rt}${Ft}`:Ft});return ne?`{${pt.join(",")}${Qe}}`:`{${pt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${I.type}`)}}var ht=class{constructor(I){ge(this,"parsed");const ne=M(I,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=te(ne)}render(I){const ne=new Ze;ne.set("false",!1),ne.set("true",!0),ne.set("raise_exception",Ie=>{throw new Error(Ie)}),ne.set("range",he);for(const[Ie,Qe]of Object.entries(I))ne.set(Ie,Qe);return new at(ne).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(De,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>j,resolveBackendAndExecutionProviders:()=>W});const f=new Map,L=[],j=(w,v,y)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const M=f.get(w);if(M===void 0)f.set(w,{backend:v,priority:y});else{if(M.priority>y)return;if(M.priority===y&&M.backend!==v)throw new Error(`cannot register backend "${w}" using priority ${y}`)}if(y>=0){const b=L.indexOf(w);b!==-1&&L.splice(b,1);for(let D=0;D{const v=f.get(w);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const y=!!v.initPromise;try{return y||(v.initPromise=v.backend.init(w)),await v.initPromise,v.initialized=!0,v.backend}catch(M){return y||(v.error=`${M}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},W=async w=>{const v=w.executionProviders||[],y=v.map(ie=>typeof ie=="string"?ie:ie.name),M=y.length===0?L:y;let b;const D=[],H=new Set;for(const ie of M){const z=await J(ie);typeof z=="string"?D.push({name:ie,err:z}):(b||(b=z),b===z&&H.add(ie))}if(!b)throw new Error(`no available backend found. ERR: ${D.map(ie=>`[${ie.name}] ${ie.err}`).join(", ")}`);for(const{name:ie,err:z}of D)y.includes(ie)&&console.warn(`removing requested execution provider "${ie}" from session options because it is not available: ${z}`);const re=v.filter(ie=>H.has(typeof ie=="string"?ie:ie.name));return[b,new Proxy(w,{get:(ie,z)=>z==="executionProviders"?re:Reflect.get(ie,z)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(De,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(De,A,r)=>{r.r(A),r.d(A,{env:()=>j});var f=r("./node_modules/onnxruntime-common/dist/esm/version.js");let L="warning";const j={wasm:{},webgl:{},webgpu:{},versions:{common:f.version},set logLevel(J){if(J!==void 0){if(typeof J!="string"||["verbose","info","warning","error","fatal"].indexOf(J)===-1)throw new Error(`Unsupported logging level: ${J}`);L=J}},get logLevel(){return L}};Object.defineProperty(j,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(De,A,r)=>{r.r(A),r.d(A,{env:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const L=f.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>j.InferenceSession,TRACE:()=>W.TRACE,TRACE_FUNC_BEGIN:()=>W.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>W.TRACE_FUNC_END,Tensor:()=>J.Tensor,TrainingSession:()=>w.TrainingSession,env:()=>L.env,registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),L=r("./node_modules/onnxruntime-common/dist/esm/env.js"),j=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),J=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 W=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 w=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>J});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),L=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),j=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class J{constructor(w){this.handler=w}async run(w,v,y){(0,j.TRACE_FUNC_BEGIN)();const M={};let b={};if(typeof w!="object"||w===null||w instanceof L.Tensor||Array.isArray(w))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let D=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof L.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(v)){if(v.length===0)throw new TypeError("'fetches' cannot be an empty array.");D=!1;for(const ie of v){if(typeof ie!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ie)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ie}.`);M[ie]=null}if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else{let ie=!1;const z=Object.getOwnPropertyNames(v);for(const V of this.outputNames)if(z.indexOf(V)!==-1){const Q=v[V];(Q===null||Q instanceof L.Tensor)&&(ie=!0,D=!1,M[V]=Q)}if(ie){if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else b=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ie of this.inputNames)if(typeof w[ie]>"u")throw new Error(`input '${ie}' is missing in 'feeds'.`);if(D)for(const ie of this.outputNames)M[ie]=null;const H=await this.handler.run(w,M,b),re={};for(const ie in H)if(Object.hasOwnProperty.call(H,ie)){const z=H[ie];z instanceof L.Tensor?re[ie]=z:re[ie]=new L.Tensor(z.type,z.data,z.dims)}return(0,j.TRACE_FUNC_END)(),re}async release(){return this.handler.dispose()}static async create(w,v,y,M){(0,j.TRACE_FUNC_BEGIN)();let b,D={};if(typeof w=="string"){if(b=w,typeof v=="object"&&v!==null)D=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(w instanceof Uint8Array){if(b=w,typeof v=="object"&&v!==null)D=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(w instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&w instanceof SharedArrayBuffer){const z=w;let V=0,Q=w.byteLength;if(typeof v=="object"&&v!==null)D=v;else if(typeof v=="number"){if(V=v,!Number.isSafeInteger(V))throw new RangeError("'byteOffset' must be an integer.");if(V<0||V>=z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${z.byteLength}).`);if(Q=w.byteLength-V,typeof y=="number"){if(Q=y,!Number.isSafeInteger(Q))throw new RangeError("'byteLength' must be an integer.");if(Q<=0||V+Q>z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${z.byteLength-V}].`);if(typeof M=="object"&&M!==null)D=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 v<"u")throw new TypeError("'options' must be an object.");b=new Uint8Array(z,V,Q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[H,re]=await(0,f.resolveBackendAndExecutionProviders)(D),ie=await H.createInferenceSessionHandler(b,re);return(0,j.TRACE_FUNC_END)(),new J(ie)}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":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const L=f.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(De,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>f,tensorToImageData:()=>L});const f=(j,J)=>{const W=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);W.width=j.dims[3],W.height=j.dims[2];const w=W.getContext("2d");if(w!=null){let v,y;(J==null?void 0:J.tensorLayout)!==void 0&&J.tensorLayout==="NHWC"?(v=j.dims[2],y=j.dims[3]):(v=j.dims[3],y=j.dims[2]);const M=(J==null?void 0:J.format)!==void 0?J.format:"RGB",b=J==null?void 0:J.norm;let D,H;b===void 0||b.mean===void 0?D=[255,255,255,255]:typeof b.mean=="number"?D=[b.mean,b.mean,b.mean,b.mean]:(D=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(D[3]=b.mean[3])),b===void 0||b.bias===void 0?H=[0,0,0,0]:typeof b.bias=="number"?H=[b.bias,b.bias,b.bias,b.bias]:(H=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(H[3]=b.bias[3]));const re=y*v;let ie=0,z=re,V=re*2,Q=-1;M==="RGBA"?(ie=0,z=re,V=re*2,Q=re*3):M==="RGB"?(ie=0,z=re,V=re*2):M==="RBG"&&(ie=0,V=re,z=re*2);for(let F=0;F{const W=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let w;if(W!=null){let v,y,M;(J==null?void 0:J.tensorLayout)!==void 0&&J.tensorLayout==="NHWC"?(v=j.dims[2],y=j.dims[1],M=j.dims[3]):(v=j.dims[3],y=j.dims[2],M=j.dims[1]);const b=J!==void 0&&J.format!==void 0?J.format:"RGB",D=J==null?void 0:J.norm;let H,re;D===void 0||D.mean===void 0?H=[255,255,255,255]:typeof D.mean=="number"?H=[D.mean,D.mean,D.mean,D.mean]:(H=[D.mean[0],D.mean[1],D.mean[2],255],D.mean[3]!==void 0&&(H[3]=D.mean[3])),D===void 0||D.bias===void 0?re=[0,0,0,0]:typeof D.bias=="number"?re=[D.bias,D.bias,D.bias,D.bias]:(re=[D.bias[0],D.bias[1],D.bias[2],0],D.bias[3]!==void 0&&(re[3]=D.bias[3]));const ie=y*v;if(J!==void 0&&(J.format!==void 0&&M===4&&J.format!=="RGBA"||M===3&&J.format!=="RGB"&&J.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const z=4;let V=0,Q=1,F=2,$=3,g=0,C=ie,T=ie*2,ee=-1;b==="RGBA"?(g=0,C=ie,T=ie*2,ee=ie*3):b==="RGB"?(g=0,C=ie,T=ie*2):b==="RBG"&&(g=0,T=ie,C=ie*2),w=W.createImageData(v,y);for(let Y=0;Y{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(De,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>L,tensorFromGpuBuffer:()=>W,tensorFromImage:()=>j,tensorFromMLTensor:()=>w,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>J});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const L=(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:b,width:D}=M,H=M.norm??{mean:255,bias:0};let re,ie;typeof H.mean=="number"?re=[H.mean,H.mean,H.mean,H.mean]:re=[H.mean[0],H.mean[1],H.mean[2],H.mean[3]??255],typeof H.bias=="number"?ie=[H.bias,H.bias,H.bias,H.bias]:ie=[H.bias[0],H.bias[1],H.bias[2],H.bias[3]??0];const z=M.format!==void 0?M.format:"RGBA",V=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",Q=b*D,F=V==="RGBA"?new Float32Array(Q*4):new Float32Array(Q*3);let $=4,g=0,C=1,T=2,ee=3,Y=0,le=Q,de=Q*2,fe=-1;z==="RGB"&&($=3,g=0,C=1,T=2,ee=-1),V==="RGBA"?fe=Q*3:V==="RBG"?(Y=0,de=Q,le=Q*2):V==="BGR"&&(de=0,le=Q,Y=Q*2);for(let xe=0;xe{const b=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,D=typeof ImageData<"u"&&y instanceof ImageData,H=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,re=typeof y=="string";let ie,z=M??{};const V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Q=F=>typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||F instanceof OffscreenCanvas?F.getContext("2d"):null;if(b){const F=V();F.width=y.width,F.height=y.height;const $=Q(F);if($!=null){let g=y.height,C=y.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(g=M.resizedHeight,C=M.resizedWidth),M!==void 0){if(z=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");z.tensorFormat="RGBA",z.height=g,z.width=C}else z.tensorFormat="RGBA",z.height=g,z.width=C;$.drawImage(y,0,0),ie=$.getImageData(0,0,C,g).data}else throw new Error("Can not access image data")}else if(D){let F,$;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(F=M.resizedHeight,$=M.resizedWidth):(F=y.height,$=y.width),M!==void 0&&(z=M),z.format="RGBA",z.height=F,z.width=$,M!==void 0){const g=V();g.width=$,g.height=F;const C=Q(g);if(C!=null)C.putImageData(y,0,0),ie=C.getImageData(0,0,$,F).data;else throw new Error("Can not access image data")}else ie=y.data}else if(H){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const F=V();F.width=y.width,F.height=y.height;const $=Q(F);if($!=null){const g=y.height,C=y.width;return $.drawImage(y,0,0,C,g),ie=$.getImageData(0,0,C,g).data,z.height=g,z.width=C,L(ie,z)}else throw new Error("Can not access image data")}else{if(re)return new Promise((F,$)=>{const g=V(),C=Q(g);if(!y||!C)return $();const T=new Image;T.crossOrigin="Anonymous",T.src=y,T.onload=()=>{g.width=T.width,g.height=T.height,C.drawImage(T,0,0,g.width,g.height);const ee=C.getImageData(0,0,g.width,g.height);z.height=g.height,z.width=g.width,F(L(ee.data,z))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ie!==void 0)return L(ie,z);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(y,M)=>{const{width:b,height:D,download:H,dispose:re}=M,ie=[1,D,b,4];return new f.Tensor({location:"texture",type:"float32",texture:y,dims:ie,download:H,dispose:re})},W=(y,M)=>{const{dataType:b,dims:D,download:H,dispose:re}=M;return new f.Tensor({location:"gpu-buffer",type:b??"float32",gpuBuffer:y,dims:D,download:H,dispose:re})},w=(y,M)=>{const{dataType:b,dims:D,download:H,dispose:re}=M;return new f.Tensor({location:"ml-tensor",type:b??"float32",mlTensor:y,dims:D,download:H,dispose:re})},v=(y,M,b)=>new f.Tensor({location:"cpu-pinned",type:y,data:M,dims:b??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(De,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>L,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>f,checkTypedArray:()=>J});const f=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),L=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let j=!1;const J=()=>{if(!j){j=!0;const W=typeof BigInt64Array<"u"&&BigInt64Array.from,w=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;W&&(f.set("int64",BigInt64Array),L.set(BigInt64Array,"int64")),w&&(f.set("uint64",BigUint64Array),L.set(BigUint64Array,"uint64")),v?(f.set("float16",Float16Array),L.set(Float16Array,"float16")):f.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>W});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),L=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),j=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),J=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class W{constructor(v,y,M){(0,j.checkTypedArray)();let b,D;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,b=v.type,D=v.dims,v.location){case"cpu-pinned":{const re=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(!re)throw new TypeError(`unsupported type "${b}" to create tensor from pinned buffer`);if(!(v.data instanceof re))throw new TypeError(`buffer should be of type ${re.name}`);this.cpuData=v.data;break}case"texture":{if(b!=="float32")throw new TypeError(`unsupported type "${b}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint8"&&b!=="bool"&&b!=="uint4"&&b!=="int4")throw new TypeError(`unsupported type "${b}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint64"&&b!=="int8"&&b!=="uint8"&&b!=="bool")throw new TypeError(`unsupported type "${b}" to create tensor from MLTensor`);this.mlTensorData=v.mlTensor,this.downloader=v.download,this.disposer=v.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let re,ie;if(typeof v=="string")if(b=v,ie=M,v==="string"){if(!Array.isArray(y))throw new TypeError("A string tensor's data must be a string array.");re=y}else{const z=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(z===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(y)){if(v==="float16"&&z===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${z.name} as data.`);v==="uint64"||v==="int64"?re=z.from(y,BigInt):re=z.from(y)}else if(y instanceof z)re=y;else if(y instanceof Uint8ClampedArray)if(v==="uint8")re=Uint8Array.from(y);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${b} tensor's data must be type of ${z}`)}else if(ie=y,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const z=typeof v[0];if(z==="string")b="string",re=v;else if(z==="boolean")b="bool",re=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${z}.`)}else if(v instanceof Uint8ClampedArray)b="uint8",re=Uint8Array.from(v);else{const z=j.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(z===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);b=z,re=v}if(ie===void 0)ie=[re.length];else if(!Array.isArray(ie))throw new TypeError("A tensor's dims must be a number array");D=ie,this.cpuData=re,this.dataLocation="cpu"}const H=(0,J.calculateSize)(D);if(this.cpuData&&H!==this.cpuData.length&&!((b==="uint4"||b==="int4")&&Math.ceil(H/2)===this.cpuData.length))throw new Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=b,this.dims=D,this.size=H}static async fromImage(v,y){return(0,L.tensorFromImage)(v,y)}static fromTexture(v,y){return(0,L.tensorFromTexture)(v,y)}static fromGpuBuffer(v,y){return(0,L.tensorFromGpuBuffer)(v,y)}static fromMLTensor(v,y){return(0,L.tensorFromMLTensor)(v,y)}static fromPinnedBuffer(v,y,M){return(0,L.tensorFromPinnedBuffer)(v,y,M)}toDataURL(v){return(0,f.tensorToDataURL)(this,v)}toImageData(v){return(0,f.tensorToImageData)(this,v)}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(v){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,v&&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(v){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,J.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(De,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>L,tensorReshape:()=>j});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const L=J=>{let W=1;for(let w=0;w{switch(J.location){case"cpu":return new f.Tensor(J.type,J.data,W);case"cpu-pinned":return new f.Tensor({location:"cpu-pinned",data:J.data,type:J.type,dims:W});case"texture":return new f.Tensor({location:"texture",texture:J.texture,type:J.type,dims:W});case"gpu-buffer":return new f.Tensor({location:"gpu-buffer",gpuBuffer:J.gpuBuffer,type:J.type,dims:W});case"ml-tensor":return new f.Tensor({location:"ml-tensor",mlTensor:J.mlTensor,type:J.type,dims:W});default:throw new Error(`tensorReshape: tensor location ${J.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const L=f.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(De,A,r)=>{r.r(A),r.d(A,{TRACE:()=>L,TRACE_FUNC_BEGIN:()=>J,TRACE_FUNC_END:()=>W});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const L=(w,v)=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||console.timeStamp(`${w}::ORT::${v}`)},j=(w,v)=>{var b;const y=((b=new Error().stack)==null?void 0:b.split(/\r\n|\r|\n/g))||[];let M=!1;for(let D=0;D{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||j("BEGIN",w)},W=w=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||j("END",w)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(De,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>J});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),L=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const j="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class J{constructor(w,v,y){this.handler=w,this.hasOptimizerModel=v,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(w,v){const y=w.evalModel||"",M=w.optimizerModel||"",b=v||{},[D,H]=await(0,f.resolveBackendAndExecutionProviders)(b);if(D.createTrainingSessionHandler){const re=await D.createTrainingSessionHandler(w.checkpointState,w.trainModel,y,M,H);return new J(re,!!w.optimizerModel,!!w.evalModel)}else throw new Error(j)}typeNarrowingForRunStep(w,v,y,M,b){const D={};let H={};if(typeof y!="object"||y===null||y instanceof L.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof M=="object"){if(M===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(M instanceof L.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(M)){if(M.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const ie of M){if(typeof ie!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ie)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ie}.`);D[ie]=null}if(typeof b=="object"&&b!==null)H=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ie=!1;const z=Object.getOwnPropertyNames(M);for(const V of v)if(z.indexOf(V)!==-1){const Q=M[V];(Q===null||Q instanceof L.Tensor)&&(ie=!0,re=!1,D[V]=Q)}if(ie){if(typeof b=="object"&&b!==null)H=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else H=M}}else if(typeof M<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ie of w)if(typeof y[ie]>"u")throw new Error(`input '${ie}' is missing in 'feeds'.`);if(re)for(const ie of v)D[ie]=null;return[D,H]}convertHandlerReturnTypeToMapOfTensors(w){const v={};for(const y in w)if(Object.hasOwnProperty.call(w,y)){const M=w[y];M instanceof L.Tensor?v[y]=M:v[y]=new L.Tensor(M.type,M.data,M.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(w,v,y){const[M,b]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,w,v,y),D=await this.handler.runTrainStep(w,M,b);return this.convertHandlerReturnTypeToMapOfTensors(D)}async runOptimizerStep(w){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(w||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(w,v,y){if(this.hasEvalModel){const[M,b]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,w,v,y),D=await this.handler.runEvalStep(w,M,b);return this.convertHandlerReturnTypeToMapOfTensors(D)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(w=!0){return this.handler.getParametersSize(w)}async loadParametersBuffer(w,v=!0){const y=await this.getParametersSize(v);if(w.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(w,v)}async getContiguousParameters(w=!0){return this.handler.getContiguousParameters(w)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(De,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const L=f.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(De,A,r)=>{r.r(A),r.d(A,{version:()=>f});const f="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>lt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>Ve,TRACE_FUNC_END:()=>Ne,Tensor:()=>pe,default:()=>l_,env:()=>T,registerBackend:()=>H});/*! * ONNX Runtime Web v1.21.0-dev.20241205-d27fecd3d3 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var f=Object.defineProperty,L=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyNames,J=Object.prototype.hasOwnProperty,W=(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')}),w=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var s in t)f(e,s,{get:t[s],enumerable:!0})},y=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of j(t))!J.call(e,i)&&i!==s&&f(e,i,{get:()=>t[i],enumerable:!(n=L(t,i))||n.enumerable});return e},M=e=>y(f({},"__esModule",{value:!0}),e),b,D,H,re,ie,z=w(()=>{b=new Map,D=[],H=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=b.get(e);if(n===void 0)b.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=D.indexOf(e);i!==-1&&D.splice(i,1);for(let a=0;a{let t=b.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}}},ie=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?D:s,i,a=[],o=new Set;for(let p of n){let h=await re(p);typeof h=="string"?a.push({name:p,err:h}):(i||(i=h),i===h&&o.add(p))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let d=t.filter(p=>o.has(typeof p=="string"?p:p.name));return[i,new Proxy(e,{get:(p,h)=>h==="executionProviders"?d:Reflect.get(p,h)})]}}),V=w(()=>{z()}),Q,F=w(()=>{Q="1.21.0-dev.20241205-6ed77cc374"}),$,g,C=w(()=>{F(),$="warning",g={wasm:{},webgl:{},webgpu:{},versions:{common:Q},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);$=e}},get logLevel(){return $}},Object.defineProperty(g,"logLevel",{enumerable:!0})}),T,ee=w(()=>{C(),T=g}),Y,le,de=w(()=>{Y=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,h;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let k=a*i,S=0,u=k,B=k*2,R=-1;o==="RGBA"?(S=0,u=k,B=k*2,R=k*3):o==="RGB"?(S=0,u=k,B=k*2):o==="RBG"&&(S=0,B=k,u=k*2);for(let U=0;U{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let i,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let S=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,B=0,R=1,U=2,Z=3,se=0,X=S,_e=S*2,me=-1;d==="RGBA"?(se=0,X=S,_e=S*2,me=S*3):d==="RGB"?(se=0,X=S,_e=S*2):d==="RBG"&&(se=0,_e=S,X=S*2),n=s.createImageData(i,a);for(let Me=0;Me{Fe(),fe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,i=t.norm??{mean:255,bias:0},a,o;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),S=4,u=0,B=1,R=2,U=3,Z=0,se=h,X=h*2,_e=-1;d==="RGB"&&(S=3,u=0,B=1,R=2,U=-1),p==="RGBA"?_e=h*3:p==="RBG"?(Z=0,X=h,se=h*2):p==="BGR"&&(X=0,se=h,Z=h*2);for(let me=0;me{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,d=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(s){let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,B=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=u,d.width=B}else d.tensorFormat="RGBA",d.height=u,d.width=B;S.drawImage(e,0,0),o=S.getImageData(0,0,B,u).data}else throw new Error("Can not access image data")}else if(n){let k,S;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,S=t.resizedWidth):(k=e.height,S=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=k,d.width=S,t!==void 0){let u=p();u.width=S,u.height=k;let B=h(u);if(B!=null)B.putImageData(e,0,0),o=B.getImageData(0,0,S,k).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;return S.drawImage(e,0,0,B,u),o=S.getImageData(0,0,B,u).data,d.height=u,d.width=B,fe(o,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,S)=>{let u=p(),B=h(u);if(!e||!B)return S();let R=new Image;R.crossOrigin="Anonymous",R.src=e,R.onload=()=>{u.width=R.width,u.height=R.height,B.drawImage(R,0,0,u.width,u.height);let U=B.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,k(fe(U.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return fe(o,d);throw new Error("Input data provided is not supported - aborted tensor creation")},xe=(e,t)=>{let{width:s,height:n,download:i,dispose:a}=t,o=[1,n,s,4];return new Je({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:a})},Le=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Je({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},qe=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Je({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:i,dispose:a})},je=(e,t,s)=>new Je({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),ue,te,he,Te,ze=w(()=>{ue=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),te=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),he=!1,Te=()=>{if(!he){he=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(ue.set("int64",BigInt64Array),te.set(BigInt64Array,"int64")),t&&(ue.set("uint64",BigUint64Array),te.set(BigUint64Array,"uint64")),s?(ue.set("float16",Float16Array),te.set(Float16Array,"float16")):ue.set("float16",Uint16Array)}}}),et,Xe,oe=w(()=>{Fe(),et=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Je(e.type,e.data,t);case"cpu-pinned":return new Je({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Je({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Je({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Je({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Je,Fe=w(()=>{de(),dt(),ze(),oe(),Je=class{constructor(e,t,s){Te();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=ue.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,d;if(typeof e=="string")if(n=e,d=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let p=ue.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?o=p.from(t,BigInt):o=p.from(t)}else if(t instanceof p)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${p}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",o=e;else if(p==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let p=te.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,o=e}if(d===void 0)d=[o.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");i=d,this.cpuData=o,this.dataLocation="cpu"}let a=et(i);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=a}static async fromImage(e,t){return Pe(e,t)}static fromTexture(e,t){return xe(e,t)}static fromGpuBuffer(e,t){return Le(e,t)}static fromMLTensor(e,t){return qe(e,t)}static fromPinnedBuffer(e,t,s){return je(e,t,s)}toDataURL(e){return Y(this,e)}toImageData(e){return le(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,e)}}}),pe,ve=w(()=>{Fe(),pe=Je}),Re,We,Ve,Ne,Ze=w(()=>{C(),Re=(e,t)=>{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||console.timeStamp(`${e}::ORT::${t}`)},We=(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 g.trace>"u"?!g.wasm.trace:!g.trace)||We("BEGIN",e)},Ne=e=>{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||We("END",e)}}),at,ft=w(()=>{z(),ve(),Ze(),at=class Qm{constructor(t){this.handler=t}async run(t,s,n){Ve();let i={},a={};if(typeof t!="object"||t===null||t instanceof pe||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof pe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);i[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(s);for(let S of this.outputNames)if(k.indexOf(S)!==-1){let u=s[S];(u===null||u instanceof pe)&&(h=!0,o=!1,i[S]=u)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(o)for(let h of this.outputNames)i[h]=null;let d=await this.handler.run(t,i,a),p={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let k=d[h];k instanceof pe?p[h]=k:p[h]=new pe(k.type,k.data,k.dims)}return Ne(),p}async release(){return this.handler.dispose()}static async create(t,s,n,i){Ve();let a,o={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,S=0,u=t.byteLength;if(typeof s=="object"&&s!==null)o=s;else if(typeof s=="number"){if(S=s,!Number.isSafeInteger(S))throw new RangeError("'byteOffset' must be an integer.");if(S<0||S>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(u=t.byteLength-S,typeof n=="number"){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||S+u>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-S}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(k,S,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,p]=await ie(o),h=await d.createInferenceSessionHandler(a,p);return Ne(),new Qm(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,ht=w(()=>{ft(),lt=at}),I=w(()=>{}),ne=w(()=>{}),K=w(()=>{}),ce=w(()=>{}),Ie={};v(Ie,{InferenceSession:()=>lt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>Ve,TRACE_FUNC_END:()=>Ne,Tensor:()=>pe,env:()=>T,registerBackend:()=>H});var Qe=w(()=>{V(),ee(),ht(),ve(),I(),ne(),Ze(),K(),ce()}),rt=w(()=>{}),pt={};v(pt,{default:()=>Ft});var It,St,Ft,At=w(()=>{var e;gh(),Ot(),Sr(),It="ort-wasm-proxy-worker",St=((e=globalThis.self)==null?void 0:e.name)===It,St&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":nt(n.wasm).then(()=>{Xn(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;xc(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;cr(i,a).then(o=>{postMessage({type:s,out:o})},o=>{postMessage({type:s,err:o})});break}case"release":Rp(n),postMessage({type:s});break;case"run":{let{sessionId:i,inputIndices:a,inputs:o,outputIndices:d,options:p}=n;jp(i,a,o,d,new Array(d.length).fill(null),p).then(h=>{h.some(k=>k[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:h},Up([...o,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":Wp(n),postMessage({type:s});break;default:}}catch(i){postMessage({type:s,err:i})}}),Ft=St?null:t=>new Worker(t??ir,{type:"module",name:It})}),ns={};v(ns,{default:()=>As});var gs,Ss,As,Xs=w(()=>{var e;Ss=(gs=self.location.href,async function(t={}){function s(){return jt.buffer!=Gt.buffer&&xs(),Gt}function n(){return jt.buffer!=Gt.buffer&&xs(),Ps}function i(){return jt.buffer!=Gt.buffer&&xs(),it}function a(){return jt.buffer!=Gt.buffer&&xs(),Et}function o(){return jt.buffer!=Gt.buffer&&xs(),cs}function d(){return jt.buffer!=Gt.buffer&&xs(),Ls}function p(){return jt.buffer!=Gt.buffer&&xs(),Mr}function h(){return jt.buffer!=Gt.buffer&&xs(),zi}var k,S,u=Object.assign({},t),B=new Promise((l,m)=>{k=l,S=m}),R=typeof window=="object",U=typeof importScripts=="function",Z=U&&self.name=="em-pthread";u.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(u.Fb||(u.Fb=new Map)).set(l,m)},u.unmountExternalData=()=>{delete u.Fb};var se=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let X=()=>{let l=(E,O,G)=>(...we)=>{let Ke=mn,st=O==null?void 0:O();we=E(...we);let bt=O==null?void 0:O();return st!==bt&&(E=bt,G(st),O=G=null),mn!=Ke?new Promise((kt,Ut)=>{uh={resolve:kt,reject:Ut}}):we},m=E=>async(...O)=>{var G;try{if(u.Gb)throw Error("Session already started");let we=u.Gb={hc:O[0],errors:[]},Ke=await E(...O);if(u.Gb!==we)throw Error("Session mismatch");(G=u.Hb)==null||G.flush();let st=we.errors;if(0kt),0u._OrtCreateSession,E=>u._OrtCreateSession=E),u._OrtRun=m(l(u._OrtRun,()=>u._OrtRun,E=>u._OrtRun=E)),u._OrtRunWithBinding=m(l(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,E=>u._OrtRunWithBinding=E)),u._OrtBindInput=l(u._OrtBindInput,()=>u._OrtBindInput,E=>u._OrtBindInput=E),X=void 0};u.jsepInit=(l,m)=>{if(X==null||X(),l==="webgpu"){[u.Hb,u.Vb,u.Zb,u.Ob,u.Yb,u.kb,u.$b,u.cc,u.Wb,u.Xb,u.ac]=m;let E=u.Hb;u.jsepRegisterBuffer=(O,G,we,Ke)=>E.registerBuffer(O,G,we,Ke),u.jsepGetBuffer=O=>E.getBuffer(O),u.jsepCreateDownloader=(O,G,we)=>E.createDownloader(O,G,we),u.jsepOnCreateSession=O=>{E.onCreateSession(O)},u.jsepOnReleaseSession=O=>{E.onReleaseSession(O)},u.jsepOnRunStart=O=>E.onRunStart(O),u.dc=(O,G)=>{E.upload(O,G)}}else if(l==="webnn"){[u.Hb,u.bc,u.Pb,u.jsepEnsureTensor,u.ec,u.jsepDownloadTensor]=m,u.jsepReleaseTensorId=u.Pb;let E=u.Hb;u.jsepOnRunStart=O=>E.onRunStart(O),u.jsepRegisterMLContext=(O,G)=>{E.registerMLContext(O,G)},u.jsepOnReleaseSession=O=>{E.onReleaseSession(O)},u.jsepCreateMLTensorDownloader=(O,G)=>E.createMLTensorDownloader(O,G),u.jsepRegisterMLTensor=(O,G,we)=>E.registerMLTensor(O,G,we),u.jsepCreateMLContext=O=>E.createMLContext(O),u.jsepRegisterMLConstant=(O,G,we,Ke,st)=>E.registerMLConstant(O,G,we,Ke,st,u.Fb)}};var _e,me,Me=Object.assign({},u),$e="./this.program",Ae=(l,m)=>{throw m},Ge="";(R||U)&&(U?Ge=self.location.href:typeof document<"u"&&document.currentScript&&(Ge=document.currentScript.src),gs&&(Ge=gs),Ge=Ge.startsWith("blob:")?"":Ge.substr(0,Ge.replace(/[?#].*/,"").lastIndexOf("/")+1),U&&(me=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),_e=(l,m,E)=>{var O=new XMLHttpRequest;O.open("GET",l,!0),O.responseType="arraybuffer",O.onload=()=>{O.status==200||O.status==0&&O.response?m(O.response):E()},O.onerror=E,O.send(null)});var ut,xt=console.log.bind(console),Kt=console.error.bind(console),Yt=xt,Ct=Kt;if(Object.assign(u,Me),Me=null,Z){let l=function(m){try{var E=m.data,O=E.cmd;if(O==="load"){let G=[];self.onmessage=we=>G.push(we),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let we of G)l(we);self.onmessage=l};for(let we of E.handlers)u[we]&&!u[we].proxy||(u[we]=(...Ke)=>{postMessage({Nb:"callHandler",pc:we,args:Ke})},we=="print"&&(Yt=u[we]),we=="printErr"&&(Ct=u[we]));jt=E.wasmMemory,xs(),Jt(E.wasmModule)}else if(O==="run"){hh(E.pthread_ptr,0,0,1,0,0),ah(E.pthread_ptr),c_(),jh(),$t||(Bm(),$t=!0);try{p_(E.start_routine,E.arg)}catch(G){if(G!="unwind")throw G}}else O==="cancel"?ba()&&Op(-1):E.target!=="setimmediate"&&(O==="checkMailbox"?$t&&Tp():O&&(Ct(`worker: received unknown command ${O}`),Ct(E)))}catch(G){throw Rm(),G}};var Jt,$t=!1;Ct=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:ba()})},u.instantiateWasm=(m,E)=>new Promise(O=>{Jt=G=>{G=new WebAssembly.Instance(G,Lh()),E(G),O()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}u.wasmBinary&&(ut=u.wasmBinary);var jt,vs,Ht,Gt,Ps,it,Et,cs,Ls,Mr,Ks,cn,zi,Os=!1;function xs(){var l=jt.buffer;u.HEAP8=Gt=new Int8Array(l),u.HEAP16=it=new Int16Array(l),u.HEAPU8=Ps=new Uint8Array(l),u.HEAPU16=Et=new Uint16Array(l),u.HEAP32=cs=new Int32Array(l),u.HEAPU32=Ls=new Uint32Array(l),u.HEAPF32=Mr=new Float32Array(l),u.HEAPF64=zi=new Float64Array(l),u.HEAP64=Ks=new BigInt64Array(l),u.HEAPU64=cn=new BigUint64Array(l)}if(!Z){if(!((jt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof se))throw Ct("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");xs()}var Yn=[],Cc=[],qp=[],kc=0,Sc=null;function Ah(){if(--kc==0&&Sc){var l=Sc;Sc=null,l()}}function Jn(l){throw Ct(l="Aborted("+l+")"),Os=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),S(l),l}var Xp,Ih=l=>l.startsWith("data:application/octet-stream;base64,"),Oh=l=>l.startsWith("file://");function Fh(l){if(l==Xp&&ut)return new Uint8Array(ut);if(me)return me(l);throw"both async and sync fetching of the wasm failed"}function Dh(l,m,E){return function(O){if(!ut&&(R||U)){if(typeof fetch=="function"&&!Oh(O))return fetch(O,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${O}'`;return G.arrayBuffer()}).catch(()=>Fh(O));if(_e)return new Promise((G,we)=>{_e(O,Ke=>G(new Uint8Array(Ke)),we)})}return Promise.resolve().then(()=>Fh(O))}(l).then(O=>WebAssembly.instantiate(O,m)).then(E,O=>{Ct(`failed to asynchronously prepare wasm: ${O}`),Jn(O)})}function Lh(){return{a:{O:d_,Aa:u_,b:m_,aa:Gh,B:qh,qa:Xh,Y:Yh,_:Jh,ra:Zh,oa:em,ha:tm,na:sm,L:rm,Z:nm,W:im,pa:om,X:am,va:__,F:f_,Q:g_,P:y_,E:b_,u:v_,q:T_,G:x_,A:A_,R:I_,ua:O_,ka:F_,U:D_,ba:L_,H:z_,ja:ah,ta:B_,t:R_,Ba:N_,x:U_,n:V_,l:K_,c:ih,o:H_,j:Q_,w:Y_,p:J_,f:Z_,s:ef,m:tf,e:sf,k:rf,i:nf,h:of,d:af,ea:lf,fa:uf,ga:df,ca:bm,da:vm,T:cf,g:pf,D:hf,I:mf,M:_f,y:ff,sa:gf,V:wf,v:xm,z:yf,N:Mf,S:bf,za:vf,ya:Tf,la:Cm,ma:km,$:eh,C:Sm,K:$m,ia:Am,J:Im,a:jt,xa:Zp,wa:Dm,r:Pf}}}var Qp={874308:(l,m,E,O,G)=>{if(u===void 0||!u.Fb)return 1;if((l=zs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=u.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),O=Number(O>>>0),m+E>l.byteLength)return 3;try{let we=l.subarray(m,m+E);switch(G){case 0:n().set(we,O>>>0);break;case 1:u.dc(O,we);break;default:return 4}return 0}catch{return 4}},875023:(l,m,E)=>{u.ec(l,n().subarray(m>>>0,m+E>>>0))},875086:()=>u.bc(),875127:l=>{u.Pb(l)},875163:()=>{u.Wb()},875194:()=>{u.Xb()},875223:()=>{u.ac()},875248:l=>u.Vb(l),875281:l=>u.Zb(l),875313:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E),!0)},875376:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E))},875433:()=>typeof wasmOffsetConverter<"u",875490:l=>{u.kb("Abs",l,void 0)},875541:l=>{u.kb("Neg",l,void 0)},875592:l=>{u.kb("Floor",l,void 0)},875645:l=>{u.kb("Ceil",l,void 0)},875697:l=>{u.kb("Reciprocal",l,void 0)},875755:l=>{u.kb("Sqrt",l,void 0)},875807:l=>{u.kb("Exp",l,void 0)},875858:l=>{u.kb("Erf",l,void 0)},875909:l=>{u.kb("Sigmoid",l,void 0)},875964:(l,m,E)=>{u.kb("HardSigmoid",l,{alpha:m,beta:E})},876043:l=>{u.kb("Log",l,void 0)},876094:l=>{u.kb("Sin",l,void 0)},876145:l=>{u.kb("Cos",l,void 0)},876196:l=>{u.kb("Tan",l,void 0)},876247:l=>{u.kb("Asin",l,void 0)},876299:l=>{u.kb("Acos",l,void 0)},876351:l=>{u.kb("Atan",l,void 0)},876403:l=>{u.kb("Sinh",l,void 0)},876455:l=>{u.kb("Cosh",l,void 0)},876507:l=>{u.kb("Asinh",l,void 0)},876560:l=>{u.kb("Acosh",l,void 0)},876613:l=>{u.kb("Atanh",l,void 0)},876666:l=>{u.kb("Tanh",l,void 0)},876718:l=>{u.kb("Not",l,void 0)},876769:(l,m,E)=>{u.kb("Clip",l,{min:m,max:E})},876838:l=>{u.kb("Clip",l,void 0)},876890:(l,m)=>{u.kb("Elu",l,{alpha:m})},876948:l=>{u.kb("Gelu",l,void 0)},877e3:l=>{u.kb("Relu",l,void 0)},877052:(l,m)=>{u.kb("LeakyRelu",l,{alpha:m})},877116:(l,m)=>{u.kb("ThresholdedRelu",l,{alpha:m})},877186:(l,m)=>{u.kb("Cast",l,{to:m})},877244:l=>{u.kb("Add",l,void 0)},877295:l=>{u.kb("Sub",l,void 0)},877346:l=>{u.kb("Mul",l,void 0)},877397:l=>{u.kb("Div",l,void 0)},877448:l=>{u.kb("Pow",l,void 0)},877499:l=>{u.kb("Equal",l,void 0)},877552:l=>{u.kb("Greater",l,void 0)},877607:l=>{u.kb("GreaterOrEqual",l,void 0)},877669:l=>{u.kb("Less",l,void 0)},877721:l=>{u.kb("LessOrEqual",l,void 0)},877780:(l,m,E,O,G)=>{u.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},877955:(l,m,E,O,G)=>{u.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878129:(l,m,E,O,G)=>{u.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878303:(l,m,E,O,G)=>{u.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878478:(l,m,E,O,G)=>{u.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878652:(l,m,E,O,G)=>{u.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878825:(l,m,E,O,G)=>{u.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},878998:(l,m,E,O,G)=>{u.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},879175:(l,m,E,O,G)=>{u.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},879355:(l,m,E,O,G)=>{u.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},879535:l=>{u.kb("Where",l,void 0)},879588:(l,m,E)=>{u.kb("Transpose",l,{perm:m?Array.from(o().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},879712:(l,m,E,O)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:zs(E),format:O?"NHWC":"NCHW"})},879845:(l,m,E,O)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:zs(E),format:O?"NHWC":"NCHW"})},879978:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue,as)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:O,kernelShape:[G],pads:[we,Ke],strides:[st],wIsConst:()=>!!s()[kt>>>0],outputPadding:Ut?Array.from(o().subarray(Number(Ut)>>>0,Number(ps)>>>0)):[],outputShape:Ms?Array.from(o().subarray(Number(Ms)>>>0,Number(Ue)>>>0)):[],activation:zs(as)})},880411:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue)=>{u.kb("ConvTranspose",l,{format:st?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:O,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!s()[bt>>>0],outputPadding:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],outputShape:ps?Array.from(o().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[],activation:zs(Ue)})},881072:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue,as)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:O,kernelShape:[G],pads:[we,Ke],strides:[st],wIsConst:()=>!!s()[kt>>>0],outputPadding:Ut?Array.from(o().subarray(Number(Ut)>>>0,Number(ps)>>>0)):[],outputShape:Ms?Array.from(o().subarray(Number(Ms)>>>0,Number(Ue)>>>0)):[],activation:zs(as)})},881505:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue)=>{u.kb("ConvTranspose",l,{format:st?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:O,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!s()[bt>>>0],outputPadding:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],outputShape:ps?Array.from(o().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[],activation:zs(Ue)})},882166:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882257:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue)=>{u.kb("AveragePool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},882736:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882827:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue)=>{u.kb("AveragePool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},883306:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883393:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue)=>{u.kb("MaxPool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},883868:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883955:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue)=>{u.kb("MaxPool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:O,storage_order:G,dilations:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},884430:(l,m,E,O,G)=>{u.kb("Gemm",l,{alpha:m,beta:E,transA:O,transB:G})},884534:l=>{u.kb("MatMul",l,void 0)},884588:(l,m,E,O)=>{u.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:O})},884696:(l,m,E,O)=>{u.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:O})},884804:(l,m)=>{u.kb("Softmax",l,{axis:m})},884867:(l,m)=>{u.kb("Concat",l,{axis:m})},884927:(l,m,E,O,G)=>{u.kb("Split",l,{axis:m,numOutputs:E,splitSizes:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},885083:l=>{u.kb("Expand",l,void 0)},885137:(l,m)=>{u.kb("Gather",l,{axis:Number(m)})},885208:(l,m)=>{u.kb("GatherElements",l,{axis:Number(m)})},885287:(l,m)=>{u.kb("GatherND",l,{batch_dims:Number(m)})},885366:(l,m,E,O,G,we,Ke,st,bt,kt,Ut)=>{u.kb("Resize",l,{antialias:m,axes:E?Array.from(o().subarray(Number(E)>>>0,Number(O)>>>0)):[],coordinateTransformMode:zs(G),cubicCoeffA:we,excludeOutside:Ke,extrapolationValue:st,keepAspectRatioPolicy:zs(bt),mode:zs(kt),nearestMode:zs(Ut)})},885728:(l,m,E,O,G,we,Ke)=>{u.kb("Slice",l,{starts:m?Array.from(o().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[],axes:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[]})},885992:l=>{u.kb("Tile",l,void 0)},886044:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886158:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886272:l=>{u.kb("Range",l,void 0)},886325:(l,m)=>{u.kb("Einsum",l,{equation:zs(m)})},886406:(l,m,E,O,G)=>{u.kb("Pad",l,{mode:m,value:E,pads:O?Array.from(o().subarray(Number(O)>>>0,Number(G)>>>0)):[]})},886549:(l,m,E,O,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!O,format:we?"NHWC":"NCHW"})},886718:(l,m,E,O,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!O,format:we?"NHWC":"NCHW"})},886887:(l,m,E)=>{u.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},886984:(l,m,E)=>{u.kb("DequantizeLinear",l,{axis:m,blockSize:E})},887074:(l,m,E,O,G)=>{u.kb("GridSample",l,{align_corners:m,mode:zs(E),padding_mode:zs(O),format:G?"NHWC":"NCHW"})},887244:(l,m,E,O,G)=>{u.kb("GridSample",l,{align_corners:m,mode:zs(E),padding_mode:zs(O),format:G?"NHWC":"NCHW"})},887414:(l,m)=>{u.kb("ScatterND",l,{reduction:zs(m)})},887499:(l,m,E,O,G,we,Ke,st,bt)=>{u.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:O,scale:G,doRotary:we,qkvHiddenSizes:Ke?Array.from(o().subarray(Number(st)>>>0,Number(st)+Ke>>>0)):[],pastPresentShareBuffer:!!bt})},887771:l=>{u.kb("BiasAdd",l,void 0)},887826:l=>{u.kb("BiasSplitGelu",l,void 0)},887887:l=>{u.kb("FastGelu",l,void 0)},887943:(l,m,E,O,G,we,Ke,st,bt,kt,Ut,ps,Ms,Ue,as,Bs)=>{u.kb("Conv",l,{format:ps?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(o().subarray(Number(E)>>>0,Number(O)>>>0)):[],group:G,kernel_shape:we?Array.from(o().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],pads:st?Array.from(o().subarray(Number(st)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(o().subarray(Number(kt)>>>0,Number(Ut)>>>0)):[],w_is_const:()=>!!s()[Number(Ms)>>>0],activation:zs(Ue),activation_params:as?Array.from(p().subarray(Number(as)>>>0,Number(Bs)>>>0)):[]})},888527:l=>{u.kb("Gelu",l,void 0)},888579:(l,m,E,O,G,we,Ke,st,bt)=>{u.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:O,softcap:G,doRotary:we,rotaryInterleaved:Ke,smoothSoftmax:st,localWindowSize:bt})},888796:(l,m,E,O)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!O})},888907:(l,m,E,O)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!O})},889018:(l,m,E,O,G,we)=>{u.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:O,bits:G,blockSize:we})},889145:(l,m,E,O,G,we)=>{u.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:O,scale:G,doRotary:we})},889304:(l,m)=>{u.kb("QuickGelu",l,{alpha:m})},889368:(l,m,E,O,G)=>{u.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:O,scale:G})},889507:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889609:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889711:(l,m,E,O)=>{u.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:O})},889832:l=>{u.$b(l)},889866:(l,m)=>u.cc(Number(l),Number(m),u.Gb.hc,u.Gb.errors)};function u_(l,m,E){return fm(async()=>{await u.Yb(Number(l),Number(m),Number(E))})}function d_(){return typeof wasmOffsetConverter<"u"}function Yp(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var Jp=l=>{l.terminate(),l.onmessage=()=>{}},zh=l=>{Zn.length==0&&(Uh(),Wh(Zn[0]));var m=Zn.pop();if(!m)return 6;Ri.push(m),pn[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},Bi=0,Fs=(l,m,...E)=>{for(var O=2*E.length,G=fh(),we=_h(8*O),Ke=we>>>3,st=0;st>>0]=bt)}return l=Nm(l,0,O,we,m),Fp(G),l};function Zp(l){if(Z)return Fs(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw Bh(l),"unwind";Zp(l)},Zn=[],Ri=[],Rh=[],pn={},Nh=l=>{var m=l.Bb;delete pn[m],Zn.push(l),Ri.splice(Ri.indexOf(l),1),l.Bb=0,mh(m)};function jh(){Rh.forEach(l=>l())}var Wh=l=>new Promise(m=>{l.onmessage=G=>{var we=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=ba()){var Ke=pn[G.targetThread];Ke?Ke.postMessage(G,G.transferList):Ct(`Internal error! Worker sent a message "${we}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else we==="checkMailbox"?Tp():we==="spawnThread"?zh(G):we==="cleanupThread"?Nh(pn[G.thread]):we==="killThread"?(G=G.thread,we=pn[G],delete pn[G],Jp(we),mh(G),Ri.splice(Ri.indexOf(we),1),we.Bb=0):we==="cancelThread"?pn[G.thread].postMessage({cmd:"cancel"}):we==="loaded"?(l.loaded=!0,m(l)):we==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):we==="callHandler"?u[G.handler](...G.args):we&&Ct(`worker sent an unknown command ${we}`)},l.onerror=G=>{throw Ct(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var E,O=[];for(E of[])u.hasOwnProperty(E)&&O.push(E);l.postMessage({cmd:"load",handlers:O,wasmMemory:jt,wasmModule:vs})});function Uh(){var l=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Zn.push(l)}var vp=l=>{for(;0{var l=ba(),m=d()[l+52>>>2>>>0];l=d()[l+56>>>2>>>0],Wm(m,m-l),Fp(m)},p_=(l,m)=>{Bi=0,l=Um(l,m),0>>=0);throw m>>>=0,E>>>=0,d()[O.Kb+16>>>2>>>0]=0,d()[O.Kb+4>>>2>>>0]=m,d()[O.Kb+8>>>2>>>0]=E,l}function Vh(l,m,E,O){return Z?Fs(2,1,l,m,E,O):Gh(l,m,E,O)}function Gh(l,m,E,O){if(l>>>=0,m>>>=0,E>>>=0,O>>>=0,se===void 0)return Ct("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?Vh(l,m,E,O):(l={ic:E,Bb:l,Rb:O,nc:G},Z?(l.Nb="spawnThread",postMessage(l,G),0):zh(l))}var Kh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Hh=(l,m,E)=>{var O=(m>>>=0)+E;for(E=m;l[E]&&!(E>=O);)++E;if(16(G=(240&G)==224?(15&G)<<12|we<<6|Ke:(7&G)<<18|we<<12|Ke<<6|63&l[m++])?O+=String.fromCharCode(G):(G-=65536,O+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else O+=String.fromCharCode(G)}return O},zs=(l,m)=>(l>>>=0)?Hh(n(),l,m):"";function qh(l,m,E){return Z?Fs(3,1,l,m,E):0}function Xh(l,m){if(Z)return Fs(4,1,l,m)}var th=l=>{for(var m=0,E=0;E=O?m++:2047>=O?m+=2:55296<=O&&57343>=O?(m+=4,++E):m+=3}return m},Qh=(l,m,E,O)=>{if(!(0>>=0;O=E+O-1;for(var we=0;we=Ke&&(Ke=65536+((1023&Ke)<<10)|1023&l.charCodeAt(++we)),127>=Ke){if(E>=O)break;m[E++>>>0]=Ke}else{if(2047>=Ke){if(E+1>=O)break;m[E++>>>0]=192|Ke>>6}else{if(65535>=Ke){if(E+2>=O)break;m[E++>>>0]=224|Ke>>12}else{if(E+3>=O)break;m[E++>>>0]=240|Ke>>18,m[E++>>>0]=128|Ke>>12&63}m[E++>>>0]=128|Ke>>6&63}m[E++>>>0]=128|63&Ke}}return m[E>>>0]=0,E-G},ya=(l,m,E)=>Qh(l,n(),m,E);function Yh(l,m){if(Z)return Fs(5,1,l,m)}function Jh(l,m,E){if(Z)return Fs(6,1,l,m,E)}function Zh(l,m,E){return Z?Fs(7,1,l,m,E):0}function em(l,m){if(Z)return Fs(8,1,l,m)}function tm(l,m,E){if(Z)return Fs(9,1,l,m,E)}function sm(l,m,E,O){if(Z)return Fs(10,1,l,m,E,O)}function rm(l,m,E,O){if(Z)return Fs(11,1,l,m,E,O)}function nm(l,m,E,O){if(Z)return Fs(12,1,l,m,E,O)}function im(l){if(Z)return Fs(13,1,l)}function om(l,m){if(Z)return Fs(14,1,l,m)}function am(l,m,E){if(Z)return Fs(15,1,l,m,E)}var lm,ei,__=()=>{Jn("")},hn=l=>{for(var m="";n()[l>>>0];)m+=lm[n()[l++>>>0]];return m},sh={},rh={};function Sn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(O,G,we={}){var Ke=G.name;if(!O)throw new ei(`type "${Ke}" must have a positive integer typeid pointer`);if(rh.hasOwnProperty(O)){if(we.Tb)return;throw new ei(`Cannot register type '${Ke}' twice`)}rh[O]=G,sh.hasOwnProperty(O)&&(G=sh[O],delete sh[O],G.forEach(st=>st()))}(l,m,E)}var um=(l,m,E)=>{switch(m){case 1:return E?O=>s()[O>>>0]:O=>n()[O>>>0];case 2:return E?O=>i()[O>>>1>>>0]:O=>a()[O>>>1>>>0];case 4:return E?O=>o()[O>>>2>>>0]:O=>d()[O>>>2>>>0];case 8:return E?O=>Ks[O>>>3]:O=>cn[O>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function f_(l,m,E){E>>>=0,Sn(l>>>=0,{name:m=hn(m>>>0),fromWireType:O=>O,toWireType:function(O,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(O=typeof G)=="object"||O==="array"||O==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:ti,readValueFromPointer:um(m,E,m.indexOf("u")==-1),Eb:null})}var ti=8;function g_(l,m,E,O){Sn(l>>>=0,{name:m=hn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,we){return we?E:O},argPackAdvance:ti,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var nh=[],$n=[];function ih(l){9<(l>>>=0)&&--$n[l+1]==0&&($n[l]=void 0,nh.push(l))}var Cr=l=>{if(!l)throw new ei("Cannot use deleted val. handle = "+l);return $n[l]},Lr=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=nh.pop()||$n.length;return $n[m]=l,$n[m+1]=1,m}};function oh(l){return this.fromWireType(d()[l>>>2>>>0])}var w_={name:"emscripten::val",fromWireType:l=>{var m=Cr(l);return ih(l),m},toWireType:(l,m)=>Lr(m),argPackAdvance:ti,readValueFromPointer:oh,Eb:null};function y_(l){return Sn(l>>>0,w_)}var M_=(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 b_(l,m,E){E>>>=0,Sn(l>>>=0,{name:m=hn(m>>>0),fromWireType:O=>O,toWireType:(O,G)=>G,argPackAdvance:ti,readValueFromPointer:M_(m,E),Eb:null})}function v_(l,m,E,O,G){if(l>>>=0,E>>>=0,m=hn(m>>>0),G===-1&&(G=4294967295),G=st=>st,O===0){var we=32-8*E;G=st=>st<>>we}var Ke=m.includes("unsigned")?function(st,bt){return bt>>>0}:function(st,bt){return bt};Sn(l,{name:m,fromWireType:G,toWireType:Ke,argPackAdvance:ti,readValueFromPointer:um(m,E,O!==0),Eb:null})}function T_(l,m,E){function O(we){var Ke=d()[we>>>2>>>0];return we=d()[we+4>>>2>>>0],new G(s().buffer,we,Ke)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Sn(l>>>=0,{name:E=hn(E>>>0),fromWireType:O,argPackAdvance:ti,readValueFromPointer:O},{Tb:!0})}function x_(l,m){l>>>=0;var E=(m=hn(m>>>0))==="std::string";Sn(l,{name:m,fromWireType:function(O){var G=d()[O>>>2>>>0],we=O+4;if(E)for(var Ke=we,st=0;st<=G;++st){var bt=we+st;if(st==G||n()[bt>>>0]==0){if(Ke=zs(Ke,bt-Ke),kt===void 0)var kt=Ke;else kt+="\0",kt+=Ke;Ke=bt+1}}else{for(kt=Array(G),st=0;st>>0]);kt=kt.join("")}return _n(O),kt},toWireType:function(O,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var we=typeof G=="string";if(!(we||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new ei("Cannot pass non-string to std::string");var Ke=E&&we?th(G):G.length,st=Ip(4+Ke+1),bt=st+4;if(d()[st>>>2>>>0]=Ke,E&&we)ya(G,bt,Ke+1);else if(we)for(we=0;we>>0]=kt}else for(we=0;we>>0]=G[we];return O!==null&&O.push(_n,st),st},argPackAdvance:ti,readValueFromPointer:oh,Eb(O){_n(O)}})}var dm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,E_=(l,m)=>{for(var E=l>>1,O=E+m/2;!(E>=O)&&a()[E>>>0];)++E;if(32<(E<<=1)-l&&dm)return dm.decode(n().slice(l,E));for(E="",O=0;!(O>=m/2);++O){var G=i()[l+2*O>>>1>>>0];if(G==0)break;E+=String.fromCharCode(G)}return E},P_=(l,m,E)=>{if(E??(E=2147483647),2>E)return 0;var O=m;E=(E-=2)<2*l.length?E/2:l.length;for(var G=0;G>>1>>>0]=we,m+=2}return i()[m>>>1>>>0]=0,m-O},C_=l=>2*l.length,k_=(l,m)=>{for(var E=0,O="";!(E>=m/4);){var G=o()[l+4*E>>>2>>>0];if(G==0)break;++E,65536<=G?(G-=65536,O+=String.fromCharCode(55296|G>>10,56320|1023&G)):O+=String.fromCharCode(G)}return O},S_=(l,m,E)=>{if(m>>>=0,E??(E=2147483647),4>E)return 0;var O=m;E=O+E-4;for(var G=0;G=we&&(we=65536+((1023&we)<<10)|1023&l.charCodeAt(++G)),o()[m>>>2>>>0]=we,(m+=4)+4>E)break}return o()[m>>>2>>>0]=0,m-O},$_=l=>{for(var m=0,E=0;E=O&&++E,m+=4}return m};function A_(l,m,E){if(l>>>=0,m>>>=0,E=hn(E>>>=0),m===2)var O=E_,G=P_,we=C_,Ke=st=>a()[st>>>1>>>0];else m===4&&(O=k_,G=S_,we=$_,Ke=st=>d()[st>>>2>>>0]);Sn(l,{name:E,fromWireType:st=>{for(var bt,kt=d()[st>>>2>>>0],Ut=st+4,ps=0;ps<=kt;++ps){var Ms=st+4+ps*m;ps!=kt&&Ke(Ms)!=0||(Ut=O(Ut,Ms-Ut),bt===void 0?bt=Ut:(bt+="\0",bt+=Ut),Ut=Ms+m)}return _n(st),bt},toWireType:(st,bt)=>{if(typeof bt!="string")throw new ei(`Cannot pass non-string to C++ string type ${E}`);var kt=we(bt),Ut=Ip(4+kt+m);return d()[Ut>>>2>>>0]=kt/m,G(bt,Ut+4,kt+m),st!==null&&st.push(_n,Ut),Ut},argPackAdvance:ti,readValueFromPointer:oh,Eb(st){_n(st)}})}function I_(l,m){Sn(l>>>=0,{Ub:!0,name:m=hn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var O_=()=>1;function F_(l){hh(l>>>0,!U,1,!R,131072,!1),jh()}var cm=l=>{if(!Os)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(o(),l>>>2,l).value.then(Tp),l+=128,Atomics.store(o(),l>>>2,1))}var Tp=()=>{var l=ba();l&&(ah(l),cm(jm))};function D_(l,m){(l>>>=0)==m>>>0?setTimeout(Tp):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=pn[l])&&l.postMessage({cmd:"checkMailbox"})}var lh=[];function L_(l,m,E,O,G){for(m>>>=0,O/=2,lh.length=O,E=G>>>0>>>3,G=0;G>>0];return(m?Qp[m]:Cf[l])(...lh)}function z_(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):Nh(pn[l])}function B_(l){}var xp=(l,m)=>{var E=rh[l];if(E===void 0)throw l=zm(l),E=hn(l),_n(l),new ei(`${m} has unknown type ${E}`);return E},pm=(l,m,E)=>{var O=[];return l=l.toWireType(O,E),O.length&&(d()[m>>>2>>>0]=Lr(O)),l};function R_(l,m,E){return m>>>=0,E>>>=0,l=Cr(l>>>0),m=xp(m,"emval::as"),pm(m,E,l)}function N_(l,m){return m>>>=0,l=Cr(l>>>0),(m=xp(m,"emval::as")).toWireType(null,l)}var Ep=l=>{try{l()}catch(m){Jn(m)}},si=0,mn=null,hm=0,Pp=[],mm={},_m={},j_=0,uh=null,W_=[];function fm(l){return function(m){if(!Os){if(si===0){var E=!1,O=!1;m((G=0)=>{if(!Os&&(hm=G,E=!0,O)){si=2,Ep(()=>Km(mn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var we=function(){var bt=o()[mn+8>>>2>>>0];return bt=Rt[_m[bt]],--Bi,bt()}()}catch(bt){we=bt,G=!0}var Ke=!1;if(!mn){var st=uh;st&&(uh=null,(G?st.reject:st.resolve)(we),Ke=!0)}if(G&&!Ke)throw we}}),O=!0,E||(si=1,mn=function(){var G=Ip(65548),we=G+12;d()[G>>>2>>>0]=we,d()[G+4>>>2>>>0]=we+65536,we=Pp[0];var Ke=mm[we];return Ke===void 0&&(Ke=j_++,mm[we]=Ke,_m[Ke]=we),we=Ke,o()[G+8>>>2>>>0]=we,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Ep(()=>Vm(mn)))}else si===2?(si=0,Ep(Hm),_n(mn),mn=null,W_.forEach(cm)):Jn(`invalid state: ${si}`);return hm}}(m=>{l().then(m)})}function U_(l){return l>>>=0,fm(()=>(l=Cr(l)).then(Lr))}var Cp=[];function V_(l,m,E,O){return E>>>=0,O>>>=0,(l=Cp[l>>>0])(null,m=Cr(m>>>0),E,O)}var G_={},kp=l=>{var m=G_[l];return m===void 0?hn(l):m};function K_(l,m,E,O,G){return E>>>=0,O>>>=0,G>>>=0,(l=Cp[l>>>0])(m=Cr(m>>>0),m[E=kp(E)],O,G)}var gm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function H_(l){return(l>>>=0)==0?Lr(gm()):(l=kp(l),Lr(gm()[l]))}var q_=l=>{var m=Cp.length;return Cp.push(l),m},X_=(l,m)=>{for(var E=Array(l),O=0;O>>2>>>0],"parameter "+O);return E},wm=(l,m)=>Object.defineProperty(m,"name",{value:l});function Q_(l,m,E){var O=(m=X_(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { `,we=0,Ke=[];E===0&&Ke.push("obj");for(var st=["retType"],bt=[O],kt=0;ktUt.name).join(", ")}) => ${O.name}>`,q_(wm(E,l))}function Y_(l){return l=kp(l>>>0),Lr(u[l])}function J_(l,m){return m>>>=0,l=Cr(l>>>0),m=Cr(m),Lr(l[m])}function Z_(l){9<(l>>>=0)&&($n[l+1]+=1)}function ef(){return Lr([])}function tf(l){l=Cr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function rf(){return Lr({})}function nf(l){for(var m=Cr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}ih(l)}function of(l,m,E){m>>>=0,E>>>=0,l=Cr(l>>>0),m=Cr(m),E=Cr(E),l[m]=E}function af(l,m){return m>>>=0,l=(l=xp(l>>>0,"_emval_take_value")).readValueFromPointer(m),Lr(l)}function lf(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 Ma=l=>l%4==0&&(l%100!=0||l%400==0),ym=[0,31,60,91,121,152,182,213,244,274,305,335],Mm=[0,31,59,90,120,151,181,212,243,273,304,334];function uf(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=(Ma(l.getFullYear())?ym:Mm)[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 O=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=O&&l.getTimezoneOffset()==Math.min(O,E)),o()[m+32>>>2>>>0]=l}function df(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],O=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),we=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ke=Math.min(we,G);return 0>E?o()[l+32>>>2>>>0]=+(G!=we&&Ke==O):0>>2>>>0]=m.getDay(),E=(Ma(m.getFullYear())?ym:Mm)[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 bm(l,m,E,O,G,we,Ke){return Z?Fs(16,1,l,m,E,O,G,we,Ke):-52}function vm(l,m,E,O,G,we){if(Z)return Fs(17,1,l,m,E,O,G,we)}function cf(l,m,E,O){l>>>=0,m>>>=0,E>>>=0,O>>>=0;var G=new Date().getFullYear(),we=new Date(G,0,1),Ke=new Date(G,6,1);G=we.getTimezoneOffset();var st=Ke.getTimezoneOffset(),bt=Math.max(G,st);d()[l>>>2>>>0]=60*bt,o()[m>>>2>>>0]=+(G!=st),we=(l=kt=>kt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(we),Ke=l(Ke),st{dh.length=0;for(var E;E=n()[l++>>>0];){var O=E!=105;m+=(O&=E!=112)&&m%8?4:0,dh.push(E==112?d()[m>>>2>>>0]:E==106?Ks[m>>>3]:E==105?o()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=O?8:4}return dh};function pf(l,m,E){return l>>>=0,m=Tm(m>>>0,E>>>0),Qp[l](...m)}function hf(l,m,E){return l>>>=0,m=Tm(m>>>0,E>>>0),Qp[l](...m)}var mf=()=>{},_f=()=>Date.now();function ff(l,m){return Ct(zs(l>>>0,m>>>0))}var xm,gf=()=>{throw Bi+=1,"unwind"};function wf(){return 4294901760}xm=()=>performance.timeOrigin+performance.now();var yf=()=>navigator.hardwareConcurrency;function Mf(){return Jn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function bf(l){l>>>=0;var m=n().length;if(l<=m||4294901760=E;E*=2){var O=m*(1+.2/E);O=Math.min(O,l+100663296);var G=Math;O=Math.max(l,O);e:{G=(G.min.call(G,4294901760,O+(65536-O%65536)%65536)-jt.buffer.byteLength+65535)/65536;try{jt.grow(G),xs();var we=1;break e}catch{}we=void 0}if(we)return!0}return!1}var Sp=()=>(Jn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),$c={},Em=l=>{l.forEach(m=>{Sp()})};function vf(){var l=Error().stack.toString().split(` `);return l[0]=="Error"&&l.shift(),Em(l),$c.Qb=Sp(),$c.fc=l,$c.Qb}function Tf(l,m,E){if(l>>>=0,m>>>=0,$c.Qb==l)var O=$c.fc;else(O=Error().stack.toString().split(` `))[0]=="Error"&&O.shift(),Em(O);for(var G=3;O[G]&&Sp()!=l;)++G;for(l=0;l>>2>>>0]=Sp();return l}var ch,ph={},Pm=()=>{if(!ch){var l,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:$e};for(l in ph)ph[l]===void 0?delete m[l]:m[l]=ph[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);ch=E}return ch};function Cm(l,m){if(Z)return Fs(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Pm().forEach((O,G)=>{var we=m+E;for(G=d()[l+4*G>>>2>>>0]=we,we=0;we>>0]=O.charCodeAt(we);s()[G>>>0]=0,E+=O.length+1}),0}function km(l,m){if(Z)return Fs(19,1,l,m);l>>>=0,m>>>=0;var E=Pm();d()[l>>>2>>>0]=E.length;var O=0;return E.forEach(G=>O+=G.length+1),d()[m>>>2>>>0]=O,0}function Sm(l){return Z?Fs(20,1,l):52}function $m(l,m,E,O){return Z?Fs(21,1,l,m,E,O):52}function Am(l,m,E,O){return Z?Fs(22,1,l,m,E,O):70}var xf=[null,[],[]];function Im(l,m,E,O){if(Z)return Fs(23,1,l,m,E,O);m>>>=0,E>>>=0,O>>>=0;for(var G=0,we=0;we>>2>>>0],st=d()[m+4>>>2>>>0];m+=8;for(var bt=0;bt>>0],Ut=xf[l];kt===0||kt===10?((l===1?Yt:Ct)(Hh(Ut,0)),Ut.length=0):Ut.push(kt)}G+=st}return d()[O>>>2>>>0]=G,0}var Om=[31,29,31,30,31,30,31,31,30,31,30,31],Fm=[31,28,31,30,31,30,31,31,30,31,30,31],Ef=(l,m)=>{s().set(l,m>>>0)};function Dm(l,m,E,O){function G(Ue,as,Bs){for(Ue=typeof Ue=="number"?Ue.toString():Ue||"";Ue.lengthXm?-1:0Ni-Ue.getDate())){Ue.setDate(Ue.getDate()+as);break}as-=Ni-Ue.getDate()+1,Ue.setDate(1),11>Bs?Ue.setMonth(Bs+1):(Ue.setMonth(0),Ue.setFullYear(Ue.getFullYear()+1))}return Bs=new Date(Ue.getFullYear()+1,0,4),as=st(new Date(Ue.getFullYear(),0,4)),Bs=st(Bs),0>=Ke(as,Ue)?0>=Ke(Bs,Ue)?Ue.getFullYear()+1:Ue.getFullYear():Ue.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,O>>>=0;var kt=d()[O+40>>>2>>>0];for(var Ut in O={lc:o()[O>>>2>>>0],kc:o()[O+4>>>2>>>0],Ib:o()[O+8>>>2>>>0],Mb:o()[O+12>>>2>>>0],Jb:o()[O+16>>>2>>>0],Db:o()[O+20>>>2>>>0],vb:o()[O+24>>>2>>>0],Cb:o()[O+28>>>2>>>0],sc:o()[O+32>>>2>>>0],jc:o()[O+36>>>2>>>0],mc:kt?zs(kt):""},E=zs(E),kt={"%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(Ut,"g"),kt[Ut]);var ps="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ms="January February March April May June July August September October November December".split(" ");for(Ut in kt={"%a":Ue=>ps[Ue.vb].substring(0,3),"%A":Ue=>ps[Ue.vb],"%b":Ue=>Ms[Ue.Jb].substring(0,3),"%B":Ue=>Ms[Ue.Jb],"%C":Ue=>we((Ue.Db+1900)/100|0,2),"%d":Ue=>we(Ue.Mb,2),"%e":Ue=>G(Ue.Mb,2," "),"%g":Ue=>bt(Ue).toString().substring(2),"%G":bt,"%H":Ue=>we(Ue.Ib,2),"%I":Ue=>((Ue=Ue.Ib)==0?Ue=12:12{for(var as=0,Bs=0;Bs<=Ue.Jb-1;as+=(Ma(Ue.Db+1900)?Om:Fm)[Bs++]);return we(Ue.Mb+as,3)},"%m":Ue=>we(Ue.Jb+1,2),"%M":Ue=>we(Ue.kc,2),"%n":()=>` `,"%p":Ue=>0<=Ue.Ib&&12>Ue.Ib?"AM":"PM","%S":Ue=>we(Ue.lc,2),"%t":()=>" ","%u":Ue=>Ue.vb||7,"%U":Ue=>we(Math.floor((Ue.Cb+7-Ue.vb)/7),2),"%V":Ue=>{var as=Math.floor((Ue.Cb+7-(Ue.vb+6)%7)/7);if(2>=(Ue.vb+371-Ue.Cb-2)%7&&as++,as)as==53&&((Bs=(Ue.vb+371-Ue.Cb)%7)==4||Bs==3&&Ma(Ue.Db)||(as=1));else{as=52;var Bs=(Ue.vb+7-Ue.Cb-1)%7;(Bs==4||Bs==5&&Ma(Ue.Db%400-1))&&as++}return we(as,2)},"%w":Ue=>Ue.vb,"%W":Ue=>we(Math.floor((Ue.Cb+7-(Ue.vb+6)%7)/7),2),"%y":Ue=>(Ue.Db+1900).toString().substring(2),"%Y":Ue=>Ue.Db+1900,"%z":Ue=>{var as=0<=(Ue=Ue.jc);return Ue=Math.abs(Ue)/60,(as?"+":"-")+("0000"+(Ue/60*100+Ue%60)).slice(-4)},"%Z":Ue=>Ue.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),kt)E.includes(Ut)&&(E=E.replace(new RegExp(Ut,"g"),kt[Ut](O)));return Ut=function(Ue){var as=Array(th(Ue)+1);return Qh(Ue,as,0,as.length),as}(E=E.replace(/\0\0/g,"%")),Ut.length>m?0:(Ef(Ut,l),Ut.length-1)}function Pf(l,m,E,O){return Dm(l>>>0,m>>>0,E>>>0,O>>>0)}Z||function(){for(var l=u.numThreads-1;l--;)Uh();Yn.unshift(()=>{kc++,function(m){Z?m():Promise.all(Zn.map(Wh)).then(m)}(()=>Ah())})}();for(var Lm=Array(256),$p=0;256>$p;++$p)Lm[$p]=String.fromCharCode($p);lm=Lm,ei=u.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},u.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},$n.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>$n.length/2-5-nh.length;var Cf=[Zp,Bh,Vh,qh,Xh,Yh,Jh,Zh,em,tm,sm,rm,nm,im,om,am,bm,vm,Cm,km,Sm,$m,Am,Im],Rt=function(){function l(E,O){return Rt=E.exports,Rt=function(){var G=Rt,we={};for(let[Ke,st]of Object.entries(G))we[Ke]=typeof st=="function"?(...bt)=>{Pp.push(Ke);try{return st(...bt)}finally{Os||(Pp.pop(),mn&&si===1&&Pp.length===0&&(si=0,Bi+=1,Ep(Gm),typeof Fibers<"u"&&Fibers.tc()))}}:st;return we}(),Rt=function(){var G=Rt,we=st=>bt=>st(bt)>>>0,Ke=st=>()=>st()>>>0;return(G=Object.assign({},G)).Da=we(G.Da),G.gb=Ke(G.gb),G.ib=we(G.ib),G.emscripten_main_runtime_thread_id=Ke(G.emscripten_main_runtime_thread_id),G.tb=we(G.tb),G.ub=Ke(G.ub),G}(),Rh.push(Rt.jb),Cc.unshift(Rt.Ca),vs=O,Ah(),Rt}var m=Lh();if(kc++,u.instantiateWasm)try{return u.instantiateWasm(m,l)}catch(E){Ct(`Module.instantiateWasm callback failed with error: ${E}`),S(E)}return Xp||(Xp=u.locateFile?Ih("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ge):Ge+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(E,O){var G=Xp;return ut||typeof WebAssembly.instantiateStreaming!="function"||Ih(G)||Oh(G)||typeof fetch!="function"?Dh(G,E,O):fetch(G,{credentials:"same-origin"}).then(we=>WebAssembly.instantiateStreaming(we,E).then(O,function(Ke){return Ct(`wasm streaming compile failed: ${Ke}`),Ct("falling back to ArrayBuffer instantiation"),Dh(G,E,O)}))}(m,function(E){l(E.instance,E.module)}).catch(S),{}}(),zm=l=>(zm=Rt.Da)(l),Bm=()=>(Bm=Rt.Ea)();u._OrtInit=(l,m)=>(u._OrtInit=Rt.Fa)(l,m),u._OrtGetLastError=(l,m)=>(u._OrtGetLastError=Rt.Ga)(l,m),u._OrtCreateSessionOptions=(l,m,E,O,G,we,Ke,st,bt,kt)=>(u._OrtCreateSessionOptions=Rt.Ha)(l,m,E,O,G,we,Ke,st,bt,kt),u._OrtAppendExecutionProvider=(l,m)=>(u._OrtAppendExecutionProvider=Rt.Ia)(l,m),u._OrtAddFreeDimensionOverride=(l,m,E)=>(u._OrtAddFreeDimensionOverride=Rt.Ja)(l,m,E),u._OrtAddSessionConfigEntry=(l,m,E)=>(u._OrtAddSessionConfigEntry=Rt.Ka)(l,m,E),u._OrtReleaseSessionOptions=l=>(u._OrtReleaseSessionOptions=Rt.La)(l),u._OrtCreateSession=(l,m,E)=>(u._OrtCreateSession=Rt.Ma)(l,m,E),u._OrtReleaseSession=l=>(u._OrtReleaseSession=Rt.Na)(l),u._OrtGetInputOutputCount=(l,m,E)=>(u._OrtGetInputOutputCount=Rt.Oa)(l,m,E),u._OrtGetInputName=(l,m)=>(u._OrtGetInputName=Rt.Pa)(l,m),u._OrtGetOutputName=(l,m)=>(u._OrtGetOutputName=Rt.Qa)(l,m),u._OrtFree=l=>(u._OrtFree=Rt.Ra)(l),u._OrtCreateTensor=(l,m,E,O,G,we)=>(u._OrtCreateTensor=Rt.Sa)(l,m,E,O,G,we),u._OrtGetTensorData=(l,m,E,O,G)=>(u._OrtGetTensorData=Rt.Ta)(l,m,E,O,G),u._OrtReleaseTensor=l=>(u._OrtReleaseTensor=Rt.Ua)(l),u._OrtCreateRunOptions=(l,m,E,O)=>(u._OrtCreateRunOptions=Rt.Va)(l,m,E,O),u._OrtAddRunConfigEntry=(l,m,E)=>(u._OrtAddRunConfigEntry=Rt.Wa)(l,m,E),u._OrtReleaseRunOptions=l=>(u._OrtReleaseRunOptions=Rt.Xa)(l),u._OrtCreateBinding=l=>(u._OrtCreateBinding=Rt.Ya)(l),u._OrtBindInput=(l,m,E)=>(u._OrtBindInput=Rt.Za)(l,m,E),u._OrtBindOutput=(l,m,E,O)=>(u._OrtBindOutput=Rt._a)(l,m,E,O),u._OrtClearBoundOutputs=l=>(u._OrtClearBoundOutputs=Rt.$a)(l),u._OrtReleaseBinding=l=>(u._OrtReleaseBinding=Rt.ab)(l),u._OrtRunWithBinding=(l,m,E,O,G)=>(u._OrtRunWithBinding=Rt.bb)(l,m,E,O,G),u._OrtRun=(l,m,E,O,G,we,Ke,st)=>(u._OrtRun=Rt.cb)(l,m,E,O,G,we,Ke,st),u._OrtEndProfiling=l=>(u._OrtEndProfiling=Rt.db)(l),u._JsepOutput=(l,m,E)=>(u._JsepOutput=Rt.eb)(l,m,E),u._JsepGetNodeName=l=>(u._JsepGetNodeName=Rt.fb)(l);var Ap,ba=()=>(ba=Rt.gb)(),_n=u._free=l=>(_n=u._free=Rt.hb)(l),Ip=u._malloc=l=>(Ip=u._malloc=Rt.ib)(l),hh=(l,m,E,O,G,we)=>(hh=Rt.lb)(l,m,E,O,G,we),Rm=()=>(Rm=Rt.mb)(),Nm=(l,m,E,O,G)=>(Nm=Rt.nb)(l,m,E,O,G),mh=l=>(mh=Rt.ob)(l),Op=l=>(Op=Rt.pb)(l),jm=()=>(jm=Rt.qb)(),Wm=(l,m)=>(Wm=Rt.rb)(l,m),Fp=l=>(Fp=Rt.sb)(l),_h=l=>(_h=Rt.tb)(l),fh=()=>(fh=Rt.ub)(),Um=u.dynCall_ii=(l,m)=>(Um=u.dynCall_ii=Rt.wb)(l,m),Vm=l=>(Vm=Rt.xb)(l),Gm=()=>(Gm=Rt.yb)(),Km=l=>(Km=Rt.zb)(l),Hm=()=>(Hm=Rt.Ab)();function qm(){0fh(),u.stackRestore=l=>Fp(l),u.stackAlloc=l=>_h(l),u.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":Ks[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":d()[l>>>2>>>0]=m;break;default:Jn(`invalid type for setValue: ${E}`)}},u.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return s()[l>>>0];case"i16":return i()[l>>>1>>>0];case"i32":return o()[l>>>2>>>0];case"i64":return Ks[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return d()[l>>>2>>>0];default:Jn(`invalid type for getValue: ${m}`)}},u.UTF8ToString=zs,u.stringToUTF8=ya,u.lengthBytesUTF8=th,Sc=function l(){Ap||qm(),Ap||(Sc=l)},qm(),u.PTR_SIZE=4,B}),As=Ss,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Ss()}),ir,Qr,zr,br,Nt,Yr,kr,Br,Sr=w(()=>{var e,t;rt(),ir=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Qr=typeof location>"u"?void 0:location.origin,zr=(s,n)=>{try{let i=n??ir;return(i?new URL(s,i):new URL(s)).origin===Qr}catch{return!1}},br=async s=>{let n=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Nt=(At(),M(pt)).default,Yr=async()=>{if(!ir)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(ir))return[void 0,Nt()];let s=await br(ir);return[s,Nt(s)]},kr=(Xs(),M(ns)).default,Br=async(s,n,i)=>[void 0,kr]}),or,$r,pr,Ar,Jr,ar,nt,gt,Ot=w(()=>{Sr(),$r=!1,pr=!1,Ar=!1,Jr=()=>{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}},ar=()=>{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}},nt=async e=>{if($r)return Promise.resolve();if(pr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ar)throw new Error("previous call to 'initializeWebAssembly()' failed.");pr=!0;let t=e.initTimeout,s=e.numThreads;if(!ar())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Jr();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let i=e.wasmPaths,a=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,d=(o==null?void 0:o.href)??o,p=i==null?void 0:i.wasm,h=(p==null?void 0:p.href)??p,k=e.wasmBinary,[S,u]=await Br(d,a,s>1),B=!1,R=[];if(t>0&&R.push(new Promise(U=>{setTimeout(()=>{B=!0,U()},t)})),R.push(new Promise((U,Z)=>{let se={numThreads:s};k?se.wasmBinary=k:(h||a)&&(se.locateFile=(X,_e)=>h??(a??_e)+X),u(se).then(X=>{pr=!1,$r=!0,or=X,U(),S&&URL.revokeObjectURL(S)},X=>{pr=!1,Ar=!0,Z(X)})})),await Promise.race(R),B)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},gt=()=>{if($r&&or)return or;throw new Error("WebAssembly is not initialized yet.")}}),ls,vr,ts,er=w(()=>{Ot(),ls=(e,t)=>{let s=gt(),n=s.lengthBytesUTF8(e)+1,i=s._malloc(n);return s.stringToUTF8(e,i,n),t.push(i),i},vr=(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")vr(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=gt(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let a=Number(t.getValue(i,n===4?"i32":"i64")),o=t.getValue(i+n,"*"),d=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),Rr,Zr=w(()=>{Ot(),er(),Rr=e=>{let t=gt(),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=ls(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&&vr(e.extra,"",new WeakSet,(o,d)=>{let p=ls(o,n),h=ls(d,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ts(`Can't set a run config entry: ${o} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(o=>t._free(o)),a}}}),Nr,Tr,An,jr,In,ni=w(()=>{Ot(),er(),Nr=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}`)}},Tr=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},An=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},jr=(e,t,s)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let o=n==null?void 0:n.deviceType;if(o){let d=ls("deviceType",s),p=ls(o,s);gt()._OrtAddSessionConfigEntry(e,d,p)!==0&&ts(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let o=n;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let d=ls("preferredLayout",s),p=ls(o.preferredLayout,s);gt()._OrtAddSessionConfigEntry(e,d,p)!==0&&ts(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=ls(i,s);gt()._OrtAppendExecutionProvider(e,a)!==0&&ts(`Can't append execution provider: ${i}.`)}},In=e=>{let t=gt(),s=0,n=[],i=e||{};An(i);try{let a=Nr(i.graphOptimizationLevel??"all"),o=Tr(i.executionMode??"sequential"),d=typeof i.logId=="string"?ls(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"?ls(i.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,d,p,h,k),s===0&&ts("Can't create session options."),i.executionProviders&&jr(s,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let S=ls("enableGraphCapture",n),u=ls(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,S,u)!==0&&ts(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[S,u]of Object.entries(i.freeDimensionOverrides)){if(typeof S!="string")throw new Error(`free dimension override name must be a string: ${S}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let B=ls(S,n);t._OrtAddFreeDimensionOverride(s,B,u)!==0&&ts(`Can't set a free dimension override: ${S} - ${u}.`)}return i.extra!==void 0&&vr(i.extra,"",new WeakSet,(S,u)=>{let B=ls(S,n),R=ls(u,n);t._OrtAddSessionConfigEntry(s,B,R)!==0&&ts(`Can't set a session config entry: ${S} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ts("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Wr,xr,lr,fn,en,gn,tn,Er,zt=w(()=>{Wr=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}`)}},xr=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}`)}},en=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}`)}},gn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",tn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Er=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),wn,On=w(()=>{rt(),wn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw d}let o=0;for(;;){let{done:d,value:p}=await i.read();if(d)break;let h=p.byteLength;new Uint8Array(a,o,h).set(p),o+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Fn,Dn,Ur,Ln,yn,zn,os,Qs=w(()=>{zt(),Fn=["V","I","W","E","F"],Dn=(e,t)=>{console.log(`[${Fn[e]},${new Date().toISOString()}]${t}`)},yn=(e,t)=>{Ur=e,Ln=t},zn=(e,t)=>{let s=en(e),n=en(Ur);s>=n&&Dn(s,typeof t=="function"?t():t)},os=(...e)=>{Ln&&zn(...e)}}),Mn,Bn=w(()=>{zt(),Mn=(e,t)=>new(fn(t))(e)}),bn=w(()=>{}),vn,Ee,P,q,ae,be,Ce,He,ct,yt=w(()=>{Qs(),bn(),vn=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ee=[],P=e=>Math.ceil(Number(e)/16)*16,q=e=>{for(let t=0;tae++,Ce=async(e,t,s,n)=>{let i=P(s),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let d=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(d,0,s)),p}else return new Uint8Array(d.slice(0,s))}finally{a.destroy()}},He=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of vn)Ee.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,i=t.byteLength,a=P(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,i)),d.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(d,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),d.destroy(),os("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=P(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 os("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=be();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),os("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),os("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=q(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let d=(i?this.freeBuffers:this.freeUniformBuffers).get(s);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let o={id:be(),type:0,buffer:n};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),os("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 os("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 Ce(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=vn.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&&(os("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ct=(...e)=>new He(...e)}),mt,ot,Pt=w(()=>{mt=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}},ot=e=>new mt(e)}),hs,ss,Se,ws,Rs,Ys,Js,Bt=w(()=>{hs=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ss=class{static calcShape(e,t,s=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=new Array(a);if(s){if(n<2||i<2)return;let d=hs.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(d===void 0)return;[o[a-2],o[a-1]]=d}for(let d=s?3:1;d<=a;d++){let p=n-d<0?1:e[n-d],h=i-d<0?1:t[i-d];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)o[a-d]=Math.max(p,h);else{if(k>1)return;o[a-d]=0}}return o}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let i=1;i<=s;i++)if(e[s-i]!==1&&e[s-i]!==t[n-i])return!1;return!0}},Se=class Dp{static size(t){return Dp.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 Dp.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 Dp.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])}},ws=class Ac{static adjustPoolAttributes(t,s,n,i,a,o){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d=n.length?n.push(s[d+2]):n[d]=s[d+2];for(let d=0;d=n[d]||o[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,i,a,o,d){if(d){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{zt(),Bt(),Ns=64,hr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},es=(e,t=1)=>{let s=hr(e,t);return typeof s=="string"?s:s[0]},_s=(e,t=1)=>{let s=hr(e,t);return typeof s=="string"?s:s[1]},vt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:Se.computeStrides(s)})}),t},ys=e=>e%4===0?4:e%2===0?2:1,Pr=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,Ds=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Hs=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Mt=(e,t,s,n)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,bs=(e,t,s,n,i)=>{let a=typeof s=="number",o=a?s:s.length,d=[...new Array(o).keys()],p=o<2?"u32":o<=4?`vec${o}`:`array`,h=hr(t,i),k=typeof h=="string"?h:h[1],S=typeof h=="string"?h:h[0],u={indices:p,value:k,storage:S,tensor:t},B=it=>typeof it=="string"?it:`${it}u`,R={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},U=a?"uniforms.":"",Z=`${U}${e}_shape`,se=`${U}${e}_strides`,X="";for(let it=0;it ${u.indices} { var indices: ${u.indices}; var current = offset; ${X} return indices; }`,me=it=>(R.offsetToIndices=!0,o<2?it:`o2i_${e}(${it})`),Me=[];if(o>=2)for(let it=o-1;it>=0;it--)Me.push(`${Mt(se,it,o)} * (indices[${it}])`);let $e=o<2?"":` fn i2o_${e}(indices: ${u.indices}) -> u32 { return ${Me.join("+")}; }`,Ae=it=>(R.indicesToOffset=!0,o<2?it:`i2o_${e}(${it})`),Ge=(...it)=>o===0?"0u":`${u.indices}(${it.map(B).join(",")})`,ut=(it,Et)=>o<2?`${it}`:`${Mt(it,Et,o)}`,xt=(it,Et,cs)=>o<2?`${it}=${cs};`:`${Mt(it,Et,o)}=${cs};`,Kt={},Yt=(it,Et)=>{R.broadcastedIndicesToOffset=!0;let cs=`${Et.name}broadcastedIndicesTo${e}Offset`;if(cs in Kt)return`${cs}(${it})`;let Ls=[];for(let Mr=o-1;Mr>=0;Mr--){let Ks=Et.indicesGet("outputIndices",Mr+Et.rank-o);Ls.push(`${ut(se,Mr)} * (${Ks} % ${ut(Z,Mr)})`)}return Kt[cs]=`fn ${cs}(outputIndices: ${Et.type.indices}) -> u32 { return ${Ls.length>0?Ls.join("+"):"0u"}; }`,`${cs}(${it})`},Ct=(it,Et)=>(()=>{if(u.storage===u.value)return`${e}[${it}]=${Et};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${it}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${it}]=vec2(u32(${Et}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${it}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Jt=it=>(()=>{if(u.storage===u.value)return`${e}[${it}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${it}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${it}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${it}] & 0xFFu), bool(${e}[${it}] & 0xFF00u), bool(${e}[${it}] & 0xFF0000u), bool(${e}[${it}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),$t=o<2?"":` fn get_${e}ByIndices(indices: ${u.indices}) -> ${k} { return ${Jt(`i2o_${e}(indices)`)}; }`,jt=o<2?"":(()=>{let it=d.map(cs=>`d${cs}: u32`).join(", "),Et=d.map(cs=>`d${cs}`).join(", ");return` fn get_${e}(${it}) -> ${k} { return get_${e}ByIndices(${Ge(Et)}); }`})(),vs=(...it)=>{if(it.length!==o)throw new Error(`indices length must be ${o}`);let Et=it.map(B).join(",");return o===0?Jt("0u"):o===1?Jt(Et[0]):(R.get=!0,R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}(${Et})`)},Ht=it=>o<2?Jt(it):(R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}ByIndices(${it})`),Gt=o<2?"":` fn set_${e}ByIndices(indices: ${u.indices}, value: ${k}) { ${Ct(`i2o_${e}(indices)`,"value")} }`,Ps=o<2?"":(()=>{let it=d.map(cs=>`d${cs}: u32`).join(", "),Et=d.map(cs=>`d${cs}`).join(", ");return` fn set_${e}(${it}, value: ${k}) { set_${e}ByIndices(${Ge(Et)}, value); }`})();return{impl:()=>{let it=[],Et=!1;return R.offsetToIndices&&(it.push(_e),Et=!0),R.indicesToOffset&&(it.push($e),Et=!0),R.broadcastedIndicesToOffset&&(Object.values(Kt).forEach(cs=>it.push(cs)),Et=!0),R.set&&(it.push(Ps),Et=!0),R.setByIndices&&(it.push(Gt),Et=!0),R.get&&(it.push(jt),Et=!0),R.getByIndices&&(it.push($t),Et=!0),!a&&Et&&it.unshift(`const ${Z} = ${u.indices}(${s.join(",")});`,`const ${se} = ${u.indices}(${Se.computeStrides(s).join(",")});`),it.join(` `)},type:u,offsetToIndices:me,indicesToOffset:Ae,broadcastedIndicesToOffset:Yt,indices:Ge,indicesGet:ut,indicesSet:xt,set:(...it)=>{if(it.length!==o+1)throw new Error(`indices length must be ${o}`);let Et=it[o];if(typeof Et!="string")throw new Error("value must be string");let cs=it.slice(0,o).map(B).join(",");return o===0?Ct("0u",Et):o===1?Ct(cs[0],Et):(R.set=!0,R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}(${cs}, ${Et})`)},setByOffset:Ct,setByIndices:(it,Et)=>o<2?Ct(it,Et):(R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}ByIndices(${it}, ${Et});`),get:vs,getByOffset:Jt,getByIndices:Ht,usage:n,name:e,strides:se,shape:Z,rank:o}},Be=(e,t,s,n=1)=>bs(e,t,s,"input",n),wt=(e,t,s,n=1)=>bs(e,t,s,"output",n),tr=(e,t,s)=>bs(e,t,s,"atomicOutput",1),sn=(e,t,s,n=1)=>bs(e,t,s,"internal",n),ii=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Ns){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,o=i?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) fn main(${a}) { ${o} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${i}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Tn=(e,t)=>new ii(e,t)}),va,ji,Ta,xa,Wi,Ea,sr,Ui,Pa,Vr=w(()=>{zt(),Bt(),Pt(),Qt(),va=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},ji=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Ta=(e,t)=>Se.sortBasedOnPerm(e,ji(e.length,t)),xa=(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=ji(n,t),a=Ta(e.dims,i),o=e.dims,d=a,p=n<2||Ea(i,e.dims),h;if(p)return h=R=>{let U=Be("input",s,o,4),Z=wt("output",s,d,4);return` ${R.registerUniform("output_size","u32").declareVariables(U,Z)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let R=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(R/4)}]}},getShaderSource:h};let{newShape:k,newPerm:S}=Wi(e.dims,i),u=Se.areEqual(S,[2,3,1]),B=Se.areEqual(S,[3,1,2]);if(k.length===2||u||B){o=u?[k[0],k[1]*k[2]]:B?[k[0]*k[1],k[2]]:k,d=[o[1],o[0]];let R=16;return h=U=>{let Z=Be("a",s,o.length),se=wt("output",s,d.length);return` ${U.registerUniform("output_size","u32").declareVariables(Z,se)} var tile : array, ${R}>; ${U.mainStart([R,R,1])} let stride = (uniforms.output_shape[1] - 1) / ${R} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${R}u + local_id.x; let input_row = workgroup_id_x * ${R}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${Z.getByIndices(`${Z.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${R}u + local_id.x; let output_row = workgroup_id_y * ${R}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${se.setByIndices(`${se.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let U=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d[1]/R),y:Math.ceil(d[0]/R)},programUniforms:[{type:12,data:U},...vt(o,d)]}},getShaderSource:h}}return h=R=>{let U=Be("a",s,o.length),Z=wt("output",s,d.length);return` ${R.registerUniform("output_size","u32").declareVariables(U,Z)} ${xa(i,n,U,Z)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${Z.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${Z.setByOffset("global_idx",U.getByIndices("aIndices"))} }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let R=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...vt(o,d)]}},getShaderSource:h}},Ui=(e,t)=>{va(e.inputs),e.compute(sr(e.inputs[0],t.perm))},Pa=e=>ot({perm:e.perm})}),Vi,Oc,Ca,Gi,ka,oi,Sa,$a,Aa,Ia,mr,Oa,Fa,Ki,Da,Hi,rn,La,Fc,za,Dc,Lc=w(()=>{zt(),Bt(),Qt(),to(),Vr(),Vi={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"},Oc={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"},Ca={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Gi={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ka=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,i]},Sa=(e,t)=>{let s=e.length+t.length,n=[],i=0;for(let a=0;a{for(let s=0;s{let s=[];if(!$a(e,t)){for(let n=0;ns.push(n))}return s},Ia=(e,t,s,n,i,a,o)=>{let d=s[0].dims,p=Se.size(a),h=Se.size(o),k=Be("_A",s[0].dataType,d),S=wt("output",i,a),u=64;p===1&&(u=256);let B=` var aBestValues : array; `,R=U=>` ${U.registerUniform("reduceSize","u32").declareVariables(k,S)} ${B} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${U.mainStart(u)} let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Ca[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${k.getByOffset("offset + k")}); bestValue = ${Vi[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${u}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Oc[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${S.setByOffset("outputIndex",`${n==="mean"?`${S.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${S.type.storage}(${Gi[n]})`}`)}; } }`;return{name:e,shaderCache:{hint:`${t};${u}`,inputDependencies:["type"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},mr=(e,t,s,n)=>{let i=e.inputs.length===1?s:qi(e.inputs,s),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((B,R)=>R));let o=Se.normalizeAxes(a,e.inputs[0].dims.length),d=o,p=e.inputs[0],h=Aa(d,e.inputs[0].dims.length);h.length>0&&(p=e.compute(sr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=ka(d.length,p.dims.length));let[k,S]=oi(p.dims,d),u=k;i.keepDims&&(u=Sa(k,o)),e.compute(Ia(t,i.cacheKey,[p],n,e.inputs[0].dataType,u,S),{inputs:[p]})},Oa=(e,t)=>{mr(e,"ReduceMeanShared",t,"mean")},Fa=(e,t)=>{mr(e,"ReduceL1Shared",t,"l1")},Ki=(e,t)=>{mr(e,"ReduceL2Shared",t,"l2")},Da=(e,t)=>{mr(e,"ReduceLogSumExpShared",t,"logSumExp")},Hi=(e,t)=>{mr(e,"ReduceMaxShared",t,"max")},rn=(e,t)=>{mr(e,"ReduceMinShared",t,"min")},La=(e,t)=>{mr(e,"ReduceProdShared",t,"prod")},Fc=(e,t)=>{mr(e,"ReduceSumShared",t,"sum")},za=(e,t)=>{mr(e,"ReduceSumSquareShared",t,"sumSquare")},Dc=(e,t)=>{mr(e,"ReduceLogSumShared",t,"logSum")}}),ur,Ba,ai,qi,_r,Ra,li,Na,ja,Wa,Xi,Ua,Va,Qi,Ga,fr,Yi,Ka,Ha,Ji,qa,Xa,Zi,Qa,Ya,eo,to=w(()=>{zt(),Bt(),Pt(),Qt(),Lc(),ur=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.")},Ba=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ai=(e,t,s,n,i,a,o=!1,d=!1)=>{let p=[],h=s[0].dims,k=h.length,S=Se.normalizeAxes(i,k),u=!d&&S.length===0;h.forEach((U,Z)=>{u||S.indexOf(Z)>=0?o&&p.push(1):p.push(U)});let B=p.length,R=Se.size(p);return{name:e,shaderCache:t,getShaderSource:U=>{let Z=[],se=Be("_A",s[0].dataType,k),X=wt("output",a,B),_e=n(se,X,S),me=_e[2];for(let Me=0,$e=0;Me=0?(o&&$e++,me=`for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { ${_e[2].includes("last_index")?`let last_index = j${Me};`:""} ${se.indicesSet("input_indices",Me,`j${Me}`)} ${me} }`):(Z.push(`${se.indicesSet("input_indices",Me,X.indicesGet("output_indices",$e))};`),$e++);return` ${U.registerUniform("output_size","u32").declareVariables(se,X)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${se.type.indices}; let output_indices = ${X.offsetToIndices("global_idx")}; ${Z.join(` `)} ${_e[0]} // init ops for reduce max/min ${_e[1]} ${me} ${_e[3]} ${_e.length===4?X.setByOffset("global_idx","value"):_e.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...vt(h,p)]})}},qi=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),ot({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},_r=(e,t,s,n)=>{let i=e.inputs,a=i.length===1?s:qi(i,s);e.compute(ai(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?Ba:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Ra=(e,t)=>{ur(e.inputs),_r(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},li=(e,t)=>{ur(e.inputs),_r(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Na=(e,t)=>{ur(e.inputs),_r(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);"])},ja=(e,t)=>{ur(e.inputs),_r(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},Wa=(e,t)=>{ur(e.inputs),_r(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")});`,""]})},Xi=(e,t)=>{ur(e.inputs),_r(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});`]})},Ua=(e,t)=>{ur(e.inputs),_r(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")});`,""]})},Va=(e,t)=>{ur(e.inputs),_r(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Qi=(e,t)=>{ur(e.inputs),_r(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Ga=(e,t)=>{ur(e.inputs),_r(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;`,""])},fr=(e,t,s)=>{if(t.length===0)return s;let n=1,i=1;for(let a=0;a1024},Yi=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xi(e,t):Oa(e,t)},Ka=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?li(e,t):Fa(e,t)},Ha=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Na(e,t):Ki(e,t)},Ji=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ja(e,t):Da(e,t)},qa=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wa(e,t):Hi(e,t)},Xa=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ua(e,t):rn(e,t)},Zi=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Va(e,t):La(e,t)},Qa=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qi(e,t):Fc(e,t)},Ya=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ga(e,t):za(e,t)},eo=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ra(e,t):Dc(e,t)}}),so,ro,Ja,no,Za=w(()=>{zt(),Pt(),to(),so=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.")},ro=(e,t)=>{so(e.inputs);let s=(n,i,a)=>{let o=[];for(let d=0;d=0||a.length===0)&&o.push(`input_indices[${d}] = 0;`);return[`${o.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(ai("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Ja=(e,t)=>{so(e.inputs);let s=(n,i,a)=>{let o=[];for(let d=0;d=0||a.length===0)&&o.push(`input_indices[${d}] = 0;`);return[`${o.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(ai("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},no=e=>ot(e)}),el,ui,io,tl,sl,xn,rl,nl,di=w(()=>{zt(),Bt(),bn(),Qt(),el=(e,t)=>{let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4],d=e[5];if(o&&d)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],k=s.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let S=i.dims[0]/3,u=S,B=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let _e of t.qkvHiddenSizes)if(_e%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");S=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],B=t.qkvHiddenSizes[2]}let R=h;if(S!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==S+u+B)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let U=0;if(o){if(u!==B)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==u/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(U=o.dims[3])}let Z=R+U,se=-1,X=0;if(a)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(d.dims[0]!==p||d.dims[1]!==t.numHeads||d.dims[2]!==h||d.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:U,kvSequenceLength:R,totalSequenceLength:Z,maxSequenceLength:se,inputHiddenSize:k,hiddenSize:S,vHiddenSize:B,headSize:Math.floor(S/t.numHeads),vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ui=(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; `,io=(e,t,s,n,i,a,o,d)=>{let p=ys(o?1:a),h=64,k=a/p;k{let X=wt("x",e.dataType,e.dims,p),_e=[X],me=o?Be("seq_lens",o.dataType,o.dims):void 0;me&&_e.push(me);let Me=d?Be("total_sequence_length_input",d.dataType,d.dims):void 0;Me&&_e.push(Me);let $e=_s(e.dataType),Ae=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${se.registerUniforms(Ae).declareVariables(..._e)} ${se.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; ${ui(me,Me,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${o?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${R}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${R}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(p){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${p}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${h}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${R}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${R}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${h}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${X.type.value}(${$e}(1.0) / ${$e}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${R}(x[offset + i]); x[offset + i] = ${X.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] = ${X.type.value}(${$e}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${B};${p}`,inputDependencies:U},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:i,z:t*s},programUniforms:u})}},tl=(e,t,s,n,i,a,o,d,p)=>{let h=o+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],S=e>1&&n,u=a.kvNumHeads?a.kvNumHeads:a.numHeads,B=S?[a.batchSize,u,h,a.headSize]:void 0,R=a.nReps?a.nReps:1,U=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=ys(a.headSize),se=a.headSize/Z,X=12,_e={x:Math.ceil(h/X),y:Math.ceil(a.sequenceLength/X),z:a.batchSize*a.numHeads},me=[{type:12,data:a.sequenceLength},{type:12,data:se},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:U},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:R}],Me=S&&n&&Se.size(n.dims)>0,$e=["type","type"];Me&&$e.push("type"),i&&$e.push("type"),d&&$e.push("type"),p&&$e.push("type");let Ae=[{dims:k,dataType:t.dataType,gpuDataType:0}];S&&Ae.push({dims:B,dataType:t.dataType,gpuDataType:0});let Ge=ut=>{let xt=Be("q",t.dataType,t.dims,Z),Kt=Be("key",s.dataType,s.dims,Z),Yt=[xt,Kt];if(Me){let Gt=Be("past_key",n.dataType,n.dims,Z);Yt.push(Gt)}i&&Yt.push(Be("attention_bias",i.dataType,i.dims));let Ct=d?Be("seq_lens",d.dataType,d.dims):void 0;Ct&&Yt.push(Ct);let Jt=p?Be("total_sequence_length_input",p.dataType,p.dims):void 0;Jt&&Yt.push(Jt);let $t=wt("output",t.dataType,k),jt=[$t];S&&jt.push(wt("present_key",t.dataType,B,Z));let vs=_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 = ${X}u; var tileQ: array<${xt.type.storage}, ${X*X}>; var tileK: array<${xt.type.storage}, ${X*X}>; ${ut.registerUniforms(Ht).declareVariables(...Yt,...jt)} ${ut.mainStart([X,X,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${R===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${R===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${ui(Ct,Jt,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${Me&&S?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${S?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${vs}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${Me&&S?` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }`:` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${S?`if (n + local_id.y < present_sequence_length) { present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${vs}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(Z){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${Z}`)}})()}; output[outputIdx] = ${$t.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${i!==void 0};${n!==void 0};${e}`,inputDependencies:$e},getRunData:()=>({outputs:Ae,dispatchGroup:_e,programUniforms:me}),getShaderSource:Ge}},sl=(e,t,s,n,i,a,o=void 0,d=void 0)=>{let p=a+i.kvSequenceLength,h=i.nReps?i.nReps:1,k=i.vHiddenSize*h,S=e>1&&n,u=i.kvNumHeads?i.kvNumHeads:i.numHeads,B=S?[i.batchSize,u,p,i.headSize]:void 0,R=[i.batchSize,i.sequenceLength,k],U=12,Z={x:Math.ceil(i.vHeadSize/U),y:Math.ceil(i.sequenceLength/U),z:i.batchSize*i.numHeads},se=[{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}],X=S&&n&&Se.size(n.dims)>0,_e=["type","type"];X&&_e.push("type"),o&&_e.push("type"),d&&_e.push("type");let me=[{dims:R,dataType:t.dataType,gpuDataType:0}];S&&me.push({dims:B,dataType:t.dataType,gpuDataType:0});let Me=$e=>{let Ae=Be("probs",t.dataType,t.dims),Ge=Be("v",s.dataType,s.dims),ut=[Ae,Ge];X&&ut.push(Be("past_value",n.dataType,n.dims));let xt=o?Be("seq_lens",o.dataType,o.dims):void 0;o&&ut.push(xt);let Kt=d?Be("total_sequence_length_input",d.dataType,d.dims):void 0;d&&ut.push(Kt);let Yt=[wt("output",t.dataType,R)];S&&Yt.push(wt("present_value",t.dataType,B));let Ct=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${U}u; var tileQ: array<${Ae.type.value}, ${U*U}>; var tileV: array<${Ae.type.value}, ${U*U}>; ${$e.registerUniforms(Ct).declareVariables(...ut,...Yt)} ${$e.mainStart([U,U,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${ui(xt,Kt,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${X&&S?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${S?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${Ae.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${X&&S?` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } `:` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${S?` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:_e},getRunData:()=>({outputs:me,dispatchGroup:Z,programUniforms:se}),getShaderSource:Me}},xn=(e,t,s,n,i,a,o,d,p,h,k=void 0,S=void 0)=>{let u=Math.min(e.outputCount,1+(o?1:0)+(d?1:0)),B=u>1?h.pastSequenceLength:0,R=B+h.kvSequenceLength,U=p&&Se.size(p.dims)>0?p:void 0,Z=[t,s];u>1&&o&&Se.size(o.dims)>0&&Z.push(o),U&&Z.push(U),k&&Z.push(k),S&&Z.push(S);let se=e.compute(tl(u,t,s,o,U,h,B,k,S),{inputs:Z,outputs:u>1?[-1,1]:[-1]})[0];e.compute(io(se,h.batchSize,h.numHeads,B,h.sequenceLength,R,k,S),{inputs:k&&S?[se,k,S]:[se],outputs:[]});let X=[se,n];u>1&&d&&Se.size(d.dims)>0&&X.push(d),k&&X.push(k),S&&X.push(S),e.compute(sl(u,se,n,d,h,B,k,S),{inputs:X,outputs:u>1?[0,2]:[0]})},rl=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o=12,d={x:Math.ceil(t.headSize/o),y:Math.ceil(t.sequenceLength/o),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],k=S=>{let u=wt("output_q",p[0].dataType,s),B=wt("output_k",p[0].dataType,s),R=wt("output_v",p[0].dataType,s),U=Be("input",p[0].dataType,p[0].dims),Z=Be("weight",p[1].dataType,p[1].dims),se=Be("bias",p[2].dataType,p[2].dims),X=U.type.storage,_e=[{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<${X}, ${o*o}>; var tileWeightQ: array<${X}, ${o*o}>; var tileWeightK: array<${X}, ${o*o}>; var tileWeightV: array<${X}, ${o*o}>; ${S.registerUniforms(_e).declareVariables(U,Z,se,u,B,R)} ${S.mainStart([o,o,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${X}(0); var valueK = ${X}(0); var valueV = ${X}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},nl=(e,t)=>{let s=el(e.inputs,t),[n,i,a]=rl(e,s);return xn(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),il,ol,oo,al,zc=w(()=>{Qe(),zt(),Bt(),Pt(),Qt(),il=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,i,a)=>{let o=i.length;if(o!==n.length)throw new Error(`${a}: num dimensions != ${o}`);i.forEach((d,p)=>{if(d!==n[p])throw new Error(`${a}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},ol=(e,t)=>{let{epsilon:s,spatial:n,format:i}=t,a=e[0].dims,o=n?ys(a[a.length-1]):1,d=i==="NHWC"&&a.length>1?o:1,p=Se.size(a)/o,h=n,k=h?a.length:a,S=Be("x",e[0].dataType,e[0].dims,o),u=Be("scale",e[1].dataType,e[1].dims,d),B=Be("bias",e[2].dataType,e[2].dims,d),R=Be("inputMean",e[3].dataType,e[3].dims,d),U=Be("inputVar",e[4].dataType,e[4].dims,d),Z=wt("y",e[0].dataType,k,o),se=()=>{let _e="";if(n)_e=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")_e=` ${Z.indicesSet("outputIndices","0","0")} let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{_e=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let me=1;me` const epsilon = ${s}; ${_e.registerUniform("outputSize","u32").declareVariables(S,u,B,R,U,Z)} ${_e.mainStart()} ${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${Z.offsetToIndices(`global_idx * ${o}`)}; ${se()} let scale = ${u.getByOffset("cOffset")}; let bias = ${B.getByOffset("cOffset")}; let inputMean = ${R.getByOffset("cOffset")}; let inputVar = ${U.getByOffset("cOffset")}; let x = ${S.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${Z.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${o}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:X,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...vt(a)]:[{type:12,data:p}]})}},oo=e=>ot(e),al=(e,t)=>{let{inputs:s,outputCount:n}=e,i=oo({...t,outputCount:n});if(T.webgpu.validateInputContent&&il(s,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ol(s,i))}}),ao,ll,ul,dl=w(()=>{Bt(),Qt(),ao=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")},ll=e=>{let t=e[0].dims,s=e[0].dims[2],n=Se.size(t)/4,i=e[0].dataType,a=Be("input",i,t,4),o=Be("bias",i,[s],4),d=Be("residual",i,t,4),p=wt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` const channels = ${s}u / 4; ${h.declareVariables(a,o,d,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${o.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${p.setByOffset("global_idx","value")} }`}},ul=e=>{ao(e.inputs),e.compute(ll(e.inputs))}}),cl,us,lo,pl,hl,uo,ml,_l,co,fl,gl,po,wl,yl,ho,Ml,Rn,bl,ci,mo,vl,Tl,_o,xl,El,fo,Pl,Cl,go,kl,Sl,wo,$l,Al,yo,Mo,Il,pi,bo,Ol,Fl,Dl,vo,Ll,zl,To=w(()=>{zt(),Bt(),Pt(),Qt(),cl=(e,t,s,n,i,a,o)=>{let d=Math.ceil(t/4),p="";typeof i=="string"?p=`${i}(a)`:p=i("a");let h=Be("inputData",s,[d],4),k=wt("outputData",n,[d],4),S=[{name:"vec_size",type:"u32"}];return o&&S.push(...o),` ${e.registerUniforms(S).declareVariables(h,k)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${k.setByOffset("global_idx",p)} }`},us=(e,t,s,n,i,a=e.dataType,o,d)=>{let p=[{type:12,data:Math.ceil(Se.size(e.dims)/4)}];return o&&p.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:h=>cl(h,Se.size(e.dims),e.dataType,a,s,n,d),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Se.size(h[0].dims)/64/4)},programUniforms:p})}},lo=e=>{e.compute(us(e.inputs[0],"Abs","abs"))},pl=e=>{e.compute(us(e.inputs[0],"Acos","acos"))},hl=e=>{e.compute(us(e.inputs[0],"Acosh","acosh"))},uo=e=>{e.compute(us(e.inputs[0],"Asin","asin"))},ml=e=>{e.compute(us(e.inputs[0],"Asinh","asinh"))},_l=e=>{e.compute(us(e.inputs[0],"Atan","atan"))},co=e=>{e.compute(us(e.inputs[0],"Atanh","atanh"))},fl=e=>ot(e),gl=(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(us(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},po=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 ot({min:t,max:s})},wl=(e,t)=>{let s=t||po(e.inputs),n=_s(e.inputs[0].dataType);e.compute(us(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]})},yl=e=>{e.compute(us(e.inputs[0],"Ceil","ceil"))},ho=e=>{e.compute(us(e.inputs[0],"Cos","cos"))},Ml=e=>{e.compute(us(e.inputs[0],"Cosh","cosh"))},Rn=e=>ot(e),bl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(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))},ci=(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)); }`,mo=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ci(t)))},vl=e=>{e.compute(us(e.inputs[0],"Exp","exp"))},Tl=e=>{e.compute(us(e.inputs[0],"Floor","floor"))},_o=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,ci(t)))},xl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(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))},El=e=>{e.compute(us(e.inputs[0],"Not",t=>`!${t}`))},fo=e=>{e.compute(us(e.inputs[0],"Neg",t=>`-${t}`))},Pl=e=>{e.compute(us(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Cl=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},go=e=>{e.compute(us(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},kl=e=>ot(e),Sl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(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))},wo=e=>{e.compute(us(e.inputs[0],"Sin","sin"))},$l=e=>{e.compute(us(e.inputs[0],"Sinh","sinh"))},Al=e=>{e.compute(us(e.inputs[0],"Sqrt","sqrt"))},yo=e=>{e.compute(us(e.inputs[0],"Tan","tan"))},Mo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Il=e=>{e.compute(us(e.inputs[0],"Tanh",Mo))},pi=(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}`,Ol=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"FastGelu",bo,pi(t),void 0,e.inputs[0].dataType))},Fl=(e,t)=>{let s=_s(e.inputs[0].dataType);return e.compute(us(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},Dl=e=>{e.compute(us(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; } `,Ll=e=>`quick_gelu_impl(${e})`,zl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"QuickGelu",Ll,vo(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Bl,xo,Rl,Bc=w(()=>{Bt(),Qt(),To(),Bl=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")},xo=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=Be("input",e[0].dataType,e[0].dims,4),n=Be("bias",e[0].dataType,[e[0].dims[2]],4),i=wt("output",e[0].dataType,t,4),a=Se.size(t)/4,o=es(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${d.declareVariables(s,n,i)} ${ci(o)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${i.setByOffset("global_idx","valueLeft * geluRight")} }`}},Rl=e=>{Bl(e.inputs),e.compute(xo(e.inputs))}}),Nl,jl,dr,Wl,Ul,Vl,Gl,Eo,Kl,Hl,Po,ql,Xl,Ql=w(()=>{zt(),Bt(),Qt(),Nl=(e,t,s,n,i,a,o,d,p,h,k,S)=>{let u,B;typeof d=="string"?u=B=(X,_e)=>`${d}((${X}),(${_e}))`:typeof d=="function"?u=B=d:(u=d.scalar,B=d.vector);let R=wt("outputData",k,n.length,4),U=Be("aData",p,t.length,4),Z=Be("bData",h,s.length,4),se;if(i)if(a){let X=Se.size(t)===1,_e=Se.size(s)===1,me=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;X||_e?se=R.setByOffset("global_idx",B(X?`${U.type.value}(${U.getByOffset("0")}.x)`:U.getByOffset("global_idx"),_e?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):se=` let outputIndices = ${R.offsetToIndices("global_idx * 4u")}; let offsetA = ${U.broadcastedIndicesToOffset("outputIndices",R)}; let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",R)}; ${R.setByOffset("global_idx",B(o||me?U.getByOffset("offsetA / 4u"):`${U.type.value}(${U.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||Me?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else se=R.setByOffset("global_idx",B(U.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let X=(_e,me,Me="")=>{let $e=`aData[indexA${me}][componentA${me}]`,Ae=`bData[indexB${me}][componentB${me}]`;return` let outputIndices${me} = ${R.offsetToIndices(`global_idx * 4u + ${me}u`)}; let offsetA${me} = ${U.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; let offsetB${me} = ${Z.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; let indexA${me} = offsetA${me} / 4u; let indexB${me} = offsetB${me} / 4u; let componentA${me} = offsetA${me} % 4u; let componentB${me} = offsetB${me} % 4u; ${_e}[${me}] = ${Me}(${u($e,Ae)}); `};k===9?se=` var data = vec4(0); ${X("data",0,"u32")} ${X("data",1,"u32")} ${X("data",2,"u32")} ${X("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:se=` ${X("outputData[global_idx]",0)} ${X("outputData[global_idx]",1)} ${X("outputData[global_idx]",2)} ${X("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(U,Z,R)} ${S??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${se} }`},jl=(e,t,s,n,i,a,o=s.dataType)=>{let d=s.dims.map(U=>Number(U)??1),p=n.dims.map(U=>Number(U)??1),h=!Se.areEqual(d,p),k=d,S=Se.size(d),u=!1,B=!1,R=[h];if(h){let U=ss.calcShape(d,p,!1);if(!U)throw new Error("Can't perform binary op on the given tensors");k=U.slice(),S=Se.size(k);let Z=Se.size(d)===1,se=Se.size(p)===1,X=d.length>0&&d[d.length-1]%4===0,_e=p.length>0&&p[p.length-1]%4===0;R.push(Z),R.push(se),R.push(X),R.push(_e);let me=1;for(let Me=1;MeU.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:U=>Nl(U,d,p,k,u,h,B,i,s.dataType,n.dataType,o,a),getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(S/64/4)},programUniforms:[{type:12,data:Math.ceil(Se.size(k)/4)},...vt(d,p,k)]})}},dr=(e,t,s,n,i,a)=>{e.compute(jl(t,i??"",e.inputs[0],e.inputs[1],s,n,a))},Wl=e=>{dr(e,"Add",(t,s)=>`${t}+${s}`)},Ul=e=>{dr(e,"Div",(t,s)=>`${t}/${s}`)},Vl=e=>{dr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},Gl=e=>{dr(e,"Mul",(t,s)=>`${t}*${s}`)},Eo=e=>{let t=Be("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;dr(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)); } `)},Kl=e=>{dr(e,"Sub",(t,s)=>`${t}-${s}`)},Hl=e=>{dr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},Po=e=>{dr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},ql=e=>{dr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},Xl=e=>{dr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),Yl,Jl,Co,Zl,eu,ko,Rc=w(()=>{zt(),Bt(),Pt(),Qt(),Yl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],i=n.dataType,a=n.dims.length;e.forEach((o,d)=>{if(d!==s){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==a)throw new Error("input tensors should have the same shape");o.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},Jl=(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; }`,Co=(e,t)=>{let s=e.length,n=[];for(let i=0;i{let i=Se.size(s),a=new Array(e.length),o=new Array(e.length),d=0,p=[],h=[],k=[{type:12,data:i}];for(let U=0;U`uniforms.sizeInConcatAxis${U}`).join(","),R=U=>` ${(()=>{U.registerUniform("outputSize","u32");for(let Z=0;Z(${B}); ${u} -= sizeInConcatAxis[inputIndex - 1u]; } ${Co(o,S)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:k}),getShaderSource:R}},eu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=Se.normalizeAxis(t.axis,n.length);Yl(s,i);let a=n.slice();a[i]=s.reduce((d,p)=>d+(p.dims.length>i?p.dims[i]:0),0);let o=s.filter(d=>Se.size(d.dims)>0);e.compute(Zl(o,i,a,s[0].dataType),{inputs:o})},ko=e=>ot({axis:e.axis})}),nn,Ir,on,So,Gr=w(()=>{zt(),Bt(),nn=(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}`)}},Ir=(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})},on=(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)||[Ys,Js];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Vs,tu,hi=w(()=>{Vs=(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.`)}},tu=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),su,Nc=w(()=>{su=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)); } `}),Nn,mi,$o=w(()=>{zt(),Bt(),Qt(),Gr(),Nn=(e,t,s,n,i)=>{let a=n-s;return` ${Array.from({length:s}).map((o,d)=>` if (${Mt(t.shape,d,t.rank)} != 1) { ${t.indicesSet(e,d,Mt(i,d+a,n))} } else { ${t.indicesSet(e,d,0)} }`).join("")} `},mi=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,d=e[1].dims,p=o[o.length-2],h=d[d.length-1],k=o[o.length-1],S=ys(h),u=ys(k),B=ys(p),R=Se.size(s)/S/B,U=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),se=[Se.size(Z),p,h],X=[{type:12,data:R},{type:12,data:p},{type:12,data:h},{type:12,data:k}];Ir(t,X),X.push(...vt(Z,o,d)),U&&X.push(...vt(e[2].dims)),X.push(...vt(se));let _e=me=>{let Me=sn("batch_dims",e[0].dataType,Z.length),$e=Be("a",e[0].dataType,o.length,u),Ae=Be("b",e[1].dataType,d.length,S),Ge=wt("output",e[0].dataType,se.length,S),ut=es(Ge.type.tensor),xt=nn(t,Ge.type.value,ut),Kt=[$e,Ae],Yt="";if(U){let $t=i?S:1;Kt.push(Be("bias",e[2].dataType,e[2].dims.length,$t)),Yt=`${i?`value += bias[col / ${$t}];`:`value += ${Ge.type.value}(bias[row + i]);`}`}let Ct=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];on(t,Ct);let Jt=()=>{let $t=`var a_data: ${$e.type.value};`;for(let jt=0;jt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { ${Jt()} } for (var i = 0u; i < ${B}u; i++) { var value = values[i]; ${Yt} ${xt} let cur_indices = ${Ge.type.indices}(batch, row + i, col); let offset = ${Ge.indicesToOffset("cur_indices")}; ${Ge.setByOffset(`offset / ${S}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${S};${u};${B};${i}`,inputDependencies:U?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:X}),getShaderSource:_e}}}),ru,nu,_i,Ao,iu,fi,ou,gi,wi=w(()=>{zt(),Bt(),Qt(),Gr(),$o(),hi(),ru=(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":""}); `,nu=(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];"} }`,_i=(e,t,s="f32",n,i=!1,a=32,o=!1,d=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=i?p:a,S=i?a:p,u=k/t[0],B=a/t[1];if(!((i&&u===4&&e[1]===4||!i&&(u===3||u===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${u} must be 3 or 4. tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${k/u}>, ${S}>; var mm_Bsub: array, ${h/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${u}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${o?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${p}; let num_tiles = ${o?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${d}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${B}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${ru(i,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${nu(i,u)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Ao=(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":""}); `,iu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",fi=(e,t,s="f32",n,i=!1,a=32,o=!1,d=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],S=i?h:a,u=i?a:h;if(!(u%t[1]===0&&S%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${S} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let B=u/t[1],R=S/t[0],U=a/t[1],Z=p?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${k}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${S}; inputCol = inputCol + ${t[0]}) { ${Ao(i,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${s}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${h}; let tileRowA = i32(localId.y) * ${B}; let tileColA = i32(localId.x) * ${R}; let tileRowB = i32(localId.y) * ${U}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Ao(i,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${U}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${s}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${iu(i)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${u}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${o?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${o?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${d}`:"0"}; var acc : array, rowPerThread>; ${Z} } `},ou=(e,t,s,n,i=!1)=>{let[a,o,d,p]=n,h=es(n[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Vs(e,h)} { var value = ${Vs(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${o.type.indices}; ${Nn("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}) -> ${Vs(e,h)} { var value = ${Vs(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${d.type.indices}; ${Nn("bIndices",d,d.rank-2,a.rank,"batchIndices")} ${d.indicesSet("bIndices",d.rank-2,"u32(row)")} ${d.indicesSet("bIndices",d.rank-1,"u32(colIn)")} value = ${d.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Vs(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]":`${Vs(e,h)}(bias[row])`};`:""} ${s} ${p.setByIndices("vec3(coords)","value")} } } `},gi=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,d=e[1].dims,p=o.slice(0,-2),h=d.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),S=Se.size(k),u=o[o.length-2],B=o[o.length-1],R=d[d.length-1],U=B%4===0&&R%4===0,Z=u<=8?[4,1,1]:[4,4,1],se=[8,8,1],X=[Math.ceil(R/se[0]/Z[0]),Math.ceil(u/se[1]/Z[1]),Math.ceil(S/se[2]/Z[2])],_e=U?4:1,me=[...p,u,B/_e],Me=me.length,$e=[...h,B,R/_e],Ae=$e.length,Ge=[S,u,R/_e],ut=[{type:6,data:u},{type:6,data:R},{type:6,data:B}];Ir(t,ut),ut.push(...vt(k,me,$e));let xt=["rank","rank"],Kt=e.length>2;Kt&&(ut.push(...vt(e[2].dims)),xt.push("rank")),ut.push(...vt(Ge));let Yt=Ct=>{let Jt=k.length,$t=sn("batchDims",e[0].dataType,Jt,1),jt=es(e[0].dataType),vs=Be("a",e[0].dataType,Me,_e),Ht=Be("b",e[1].dataType,Ae,_e),Gt=wt("result",e[0].dataType,Ge.length,_e),Ps=[vs,Ht];if(Kt){let Mr=i?_e:1;Ps.push(Be("bias",e[2].dataType,e[2].dims.length,Mr))}let it=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];on(t,it);let Et=es(Gt.type.tensor),cs=nn(t,Gt.type.value,Et),Ls=ou(_e,Kt,cs,[$t,vs,Ht,Gt],i);return` ${Ct.registerUniforms(it).registerInternalVariables($t).declareVariables(...Ps,Gt)} ${Ls} ${U?_i(Z,se,jt,$t):fi(Z,se,jt,$t)} `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${U};${i}`,inputDependencies:xt},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:X[0],y:X[1],z:X[2]},programUniforms:ut}),getShaderSource:Yt}}}),au,lu,uu=w(()=>{zt(),Qs(),Qt(),Gr(),hi(),Nc(),wi(),au=(e,t,s,n,i=!1,a,o=4,d=4,p=4,h="f32")=>{let k=ut=>{switch(ut){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 ${ut} is not supported.`)}},S=ut=>{switch(ut){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 ${ut} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,B=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,R=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",U=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",se=e?"col":"row",X=` 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 = ${se} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${se} / 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 = ${se} % inChannels; var resData = ${Vs(o,h)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${R} && xCol >= 0 && xCol < ${U}) { ${u} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${k(o)} } return resData;`,_e=e?t&&n?` let col = colIn * ${o}; ${X}`:` let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${X} } return ${Vs(o,h)}(0.0);`:n&&s?` let col = colIn * ${o}; ${X}`:` let col = colIn * ${o}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${X} } return ${Vs(o,h)}(0.0);`,me=`${S(d)}`,Me=Vs(p,h),$e=Vs(e?o:d,h),Ae=Vs(e?d:o,h),Ge=nn(a,Me,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${$e} { ${e?_e:me} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ae} { ${e?me:_e} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { let col = colIn * ${p}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${B} ${tu(i)} ${Ge} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},lu=(e,t,s,n,i,a,o,d,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],S=s[0],u=h?s[2]:s[3],B=h?s[1]:s[2],R=h?s[3]:s[1],U=h&&(k%4===0||k%3===0)&&R%4===0,Z=h?R:u*B,se=h?u*B:R,X=[8,8,1],_e=n<=8?[4,1,1]:[4,4,1],me=[Math.ceil(Z/X[0]/_e[0]),Math.ceil(se/X[1]/_e[1]),Math.ceil(S/X[2]/_e[2])];os("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${me}`);let Me=U?h&&k%4!==0?3:4:1,$e=X[1]*_e[1],Ae=X[0]*_e[0],Ge=Math.max(X[0]*Me,X[1]),ut=n%$e===0,xt=i%Ae===0,Kt=a%Ge===0,Yt=U?[Me,4,4]:[1,1,1],Ct=[{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}];Ir(t,Ct),Ct.push(...vt(e[0].dims,e[1].dims));let Jt=["rank","rank"];o&&(Ct.push(...vt(e[2].dims)),Jt.push("rank")),Ct.push(...vt(s));let $t=jt=>{let vs=[{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}];on(t,vs);let Ht=U?4:1,Gt=es(e[0].dataType),Ps=` fn setOutputAtIndex(flatIndex : i32, value : ${U?`vec4<${Gt}>`:Gt}) { result[flatIndex] = ${U?`vec4<${Gt}>`:Gt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${U?`vec4<${Gt}>`:Gt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${U?"/ 4":""}, value); }`,it=Be("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Et=Be("w",e[1].dataType,e[1].dims.length,Ht),cs=[it,Et],Ls=wt("result",e[0].dataType,s.length,Ht);if(o){let Mr=Be("bias",e[2].dataType,e[2].dims.length,Ht);cs.push(Mr),Ps+=` fn getBiasByOutputCoords(coords : vec4) -> ${U?`vec4<${Gt}>`:Gt} { return bias[coords.${h?"w":"y"}${U?"/ 4":""}]; }`}return` ${su("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${jt.registerUniforms(vs).declareVariables(...cs,Ls)} ${Ps} ${au(h,ut,xt,Kt,o,t,Yt[0],Yt[1],Yt[2],Gt)} ${U?_i(_e,X,Gt,void 0,!h,Ge):fi(_e,X,Gt,void 0,!h,Ge,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${U};${ut};${xt};${Kt};${$e};${Ae};${Ge}`,inputDependencies:Jt},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:me[0],y:me[1],z:me[2]},programUniforms:Ct}),getShaderSource:$t}}}),du,Io,En,cu,Oo,Fo,pu,hu,jc=w(()=>{zt(),Qs(),Bt(),Qt(),Gr(),hi(),du=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,En=(e,t)=>t<=1?e:e+(e-1)*(t-1),cu=(e,t,s,n=1)=>{let i=En(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)},Oo=(e,t,s,n,i)=>{i==null&&(i=cu(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},Fo=(e,t,s,n,i,a,o,d,p,h)=>{let k,S,u,B;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let R=Oo([t,s,n,1],[d,p,h],1,[i,a,o],e);S=R[0],u=R[1],B=R[2]}else if(Array.isArray(e)){if(!e.every((U,Z,se)=>U===se[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let R=Oo([t,s,n,1],[d,p,h],1,[i,a,o],e[0]);S=R[0],u=R[1],B=R[2]}else if(e==="SAME_UPPER"){S=Math.ceil(t/i),u=Math.ceil(s/a),B=Math.ceil(n/o);let R=(S-1)*i+d-t,U=(u-1)*a+p-s,Z=(B-1)*o+h-n,se=Math.floor(R/2),X=R-se,_e=Math.floor(U/2),me=U-_e,Me=Math.floor(Z/2),$e=Z-Me;k={top:_e,bottom:me,left:Me,right:$e,front:se,back:X}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:S,outHeight:u,outWidth:B}},pu=(e,t,s,n,i,a=!1,o="channelsLast")=>{let d,p,h,k,S;if(o==="channelsLast")[d,p,h,k,S]=e;else if(o==="channelsFirst")[d,S,p,h,k]=e;else throw new Error(`Unknown dataFormat ${o}`);let[u,,B,R,U]=t,[Z,se,X]=Io(s),[_e,me,Me]=Io(n),$e=En(B,_e),Ae=En(R,me),Ge=En(U,Me),{padInfo:ut,outDepth:xt,outHeight:Kt,outWidth:Yt}=Fo(i,p,h,k,Z,se,X,$e,Ae,Ge),Ct=a?u*S:u,Jt=[0,0,0,0,0];return o==="channelsFirst"?Jt=[d,Ct,xt,Kt,Yt]:o==="channelsLast"&&(Jt=[d,xt,Kt,Yt,Ct]),{batchSize:d,dataFormat:o,inDepth:p,inHeight:h,inWidth:k,inChannels:S,outDepth:xt,outHeight:Kt,outWidth:Yt,outChannels:Ct,padInfo:ut,strideDepth:Z,strideHeight:se,strideWidth:X,filterDepth:B,filterHeight:R,filterWidth:U,effectiveFilterDepth:$e,effectiveFilterHeight:Ae,effectiveFilterWidth:Ge,dilationDepth:_e,dilationHeight:me,dilationWidth:Me,inShape:e,outShape:Jt,filterShape:t}},hu=(e,t,s,n,i,a)=>{let o=a==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],p={x:s.map((Z,se)=>se)},h=[Math.ceil(du(p.x.map(Z=>s[Z]))/d[0]),1,1];os("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,S=Se.size(s),u=[{type:12,data:S},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Ir(t,u),u.push(...vt(e[0].dims,e[1].dims));let B=["rank","rank"],R=e.length===3;R&&(u.push(...vt(e[2].dims)),B.push("rank")),u.push(...vt(s));let U=Z=>{let se=[{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}];on(t,se);let X=1,_e=es(e[0].dataType),me=Be("x",e[0].dataType,e[0].dims.length,k),Me=Be("W",e[1].dataType,e[1].dims.length,X),$e=[me,Me],Ae=wt("result",e[0].dataType,s.length,X),Ge="";if(R){let Kt=Be("bias",e[2].dataType,e[2].dims.length,X);$e.push(Kt),Ge+=` fn getBiasByOutputCoords(coords : array) -> ${_e} { return bias[${o?Mt("coords",4,5):Mt("coords",1,5)}]; }`}let ut=Vs(k,_e),xt=nn(t,ut,_e);return` ${Ge} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${me.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${Me.getByIndices("aIndices")}; } ${Z.registerUniforms(se).declareVariables(...$e,Ae)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ae.offsetToIndices("global_idx")}; let batch = ${Mt("coords",0,me.rank)}; let d2 = ${o?Mt("coords",me.rank-1,me.rank):Mt("coords",1,me.rank)}; let xFRCCorner = vec3(${o?Mt("coords",1,me.rank):Mt("coords",2,me.rank)}, ${o?Mt("coords",2,me.rank):Mt("coords",3,me.rank)}, ${o?Mt("coords",3,me.rank):Mt("coords",4,me.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${o?Mt("uniforms.x_shape",1,me.rank):Mt("uniforms.x_shape",2,me.rank)}; let xShapeZ = ${o?Mt("uniforms.x_shape",2,me.rank):Mt("uniforms.x_shape",3,me.rank)}; let xShapeW = ${o?Mt("uniforms.x_shape",3,me.rank):Mt("uniforms.x_shape",4,me.rank)}; let xShapeU = ${o?Mt("uniforms.x_shape",4,me.rank):Mt("uniforms.x_shape",1,me.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${o?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${o?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${o?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${o?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${R?"value = value + getBiasByOutputCoords(coords)":""}; ${xt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${k};${R}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:u}),getShaderSource:U}}}),mu,yi,Wc=w(()=>{zt(),Bt(),Qt(),Gr(),mu=(e,t,s,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",o=e[0].dims,d=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,S=p&&k>=4?ys(h):1,u=Se.size(s)/S,B=[{type:12,data:u},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:k}];Ir(t,B),B.push(...vt(o,[d[0],d[1],d[2],d[3]/S]));let R=i?["rank","rank","rank"]:["rank","rank"];B.push(...vt([s[0],s[1],s[2],s[3]/S]));let U=Z=>{let se=wt("output",e[0].dataType,s.length,S),X=es(se.type.tensor),_e=nn(t,se.type.value,X),me=Be("x",e[0].dataType,o.length),Me=Be("w",e[1].dataType,d.length,S),$e=[me,Me];i&&$e.push(Be("b",e[2].dataType,e[2].dims,S));let Ae=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];on(t,Ae);let Ge=p?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${me.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${Me.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${me.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${Z.registerUniforms(Ae).declareVariables(...$e,se)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${se.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${p?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${S} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; var value: ${se.type.value} = ${se.type.value}(0); ${Ge} ${a} ${_e} ${se.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${S}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:U}},yi=(e,t,s,n)=>{let i=e.length>2,a=ys(s[3]),o=ys(s[2]),d=Se.size(s)/a/o,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],k=[s[0],s[1],s[2],s[3]/a],S=[{type:12,data:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Ir(t,S),S.push(...vt(p,h,k));let u=(o-1)*t.strides[1]+h[1],B=R=>{let U=wt("output",e[0].dataType,k.length,a),Z=es(U.type.tensor),se=nn(t,U.type.value,Z),X=Be("x",e[0].dataType,p.length,a),_e=Be("w",e[1].dataType,h.length,a),me=[X,_e];i&&me.push(Be("b",e[2].dataType,e[2].dims,a));let Me=i?"value += b[output_channel];":"",$e=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return on(t,$e),` ${R.registerUniforms($e).declareVariables(...me,U)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${o}u; let col = (index1 % width1) * ${o}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${X.type.value}, ${u}>; var values: array<${U.type.value}, ${o}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${u}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${X.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${X.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${_e.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} ${se} ${U.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${o};${u};${h[0]};${h[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:S}),getShaderSource:B}}}),_u,Mi,fu,bi,vi,Do,gu,Lo,zo,Uc=w(()=>{Bt(),uu(),jc(),wi(),Wc(),Gr(),$o(),Vr(),_u=(e,t,s,n,i,a)=>{let o=e[0],d=e.slice(a?1:2,a?3:4),p=d.length,h=t[0],k=t.slice(2).map((u,B)=>u+(u-1)*(s[B]-1)),S=d.map((u,B)=>u+n[B]+n[B+p]).map((u,B)=>Math.floor((u-k[B]+i[B])/i[B]));return S.splice(0,0,o),S.splice(a?3:1,0,h),S},Mi=[2,3,1,0],fu=(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")},bi=(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,d=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Do=(e,t,s,n)=>{let i=s.format==="NHWC",a=_u(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,i);if(s.group!==1){let $e=[t[0]];if(i){let Ae=e.kernelCustomData.wT??e.compute(sr(t[1],Mi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ae),$e.push(Ae)}else $e.push(t[1]);t.length===3&&$e.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(yi($e,s,a,n),{inputs:$e}):e.compute(mu($e,s,a,n),{inputs:$e});return}let o=t.length===3,d=t[0].dims[i?1:2],p=t[0].dims[i?2:3],h=t[0].dims[i?3:1],k=t[1].dims[2],S=t[1].dims[3],u=a[i?1:2],B=a[i?2:3],R=a[i?3:1],U=i&&k===d&&S===p&&s.pads[0]===0&&s.pads[1]===0;if(U||k===1&&S===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let $e=a[0],Ae,Ge,ut,xt=[];if(i){let Ct=e.kernelCustomData.wT??e.compute(sr(t[1],Mi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ct),U){let Jt=d*p*h;Ae=t[0].reshape([1,$e,Jt]),Ge=Ct.reshape([1,Jt,R]),ut=[1,$e,R]}else Ae=t[0].reshape([$e,d*p,h]),Ge=Ct.reshape([1,h,R]),ut=[$e,u*B,R];xt.push(Ae),xt.push(Ge)}else Ae=t[0].reshape([$e,h,d*p]),Ge=t[1].reshape([1,R,h]),ut=[$e,R,u*B],xt.push(Ge),xt.push(Ae);o&&xt.push(t[2]);let Kt=ut[2],Yt=xt[0].dims[xt[0].dims.length-1];Kt<8&&Yt<8?e.compute(mi(xt,s,a,ut,i,n),{inputs:xt}):e.compute(gi(xt,s,a,ut,i,n),{inputs:xt});return}let Z=!0,se=e.kernelCustomData.wT??e.compute(sr(t[1],Mi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=se);let X=[t[0],se];o&&X.push(t[2]);let _e=i?u*B:R,me=i?R:u*B,Me=k*S*h;e.compute(lu(X,s,a,_e,me,Me,o,Z,n),{inputs:X})},gu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),o=[1].concat(t.dilations),d=[1].concat(t.kernelShape),p=bi({...t,pads:i,strides:a,dilations:o,kernelShape:d},n);Do(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Lo=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",i=bi(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,o=pu(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(hu(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],n))},zo=(e,t)=>{if(fu(e.inputs,t),e.inputs[0].dims.length===3)gu(e,t);else if(e.inputs[0].dims.length===5)Lo(e,e.inputs,t);else{let s=bi(t,e.inputs);Do(e,e.inputs,s)}}}),wu,Vc=w(()=>{zt(),Qs(),Bt(),Qt(),wu=(e,t,s)=>{let n=e.length>2,i=t.outputShape,a=t.format==="NHWC",o=t.group,d=e[1].dims,p=d[2]/o,h=d[3],k=a?ys(h):1,S=Se.size(i)/k,u=[Math.ceil(S/64),1,1];os("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let B=["rank","rank"],R=[t.strides[0],t.strides[1]],U=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],Z=[t.dilations[0],t.dilations[1]],se=[U[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),U[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],X=[se[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),se[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],_e=[{type:12,data:S},{type:12,data:R},{type:12,data:U},{type:12,data:Z},{type:12,data:se},{type:6,data:X},{type:12,data:p},{type:12,data:h},...vt(e[0].dims,e[1].dims)];n&&(_e.push(...vt(e[2].dims)),B.push("rank")),_e.push(...vt(i));let me=Me=>{let $e=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:R.length},{name:"filter_dims",type:"u32",length:U.length},{name:"dilations",type:"u32",length:U.length},{name:"effective_filter_dims",type:"u32",length:se.length},{name:"pads",type:"i32",length:X.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ae=es(e[0].dataType),Ge=a?1:2,ut=a?2:3,xt=a?3:1,Kt=Be("W",e[1].dataType,e[1].dims.length,k),Yt=Be("Dy",e[0].dataType,e[0].dims.length),Ct=[Yt,Kt];n&&Ct.push(Be("bias",e[2].dataType,[i[xt]].length,k));let Jt=wt("result",e[0].dataType,i.length,k),$t=` let outputIndices = ${Jt.offsetToIndices(`global_idx * ${k}`)}; let batch = ${Jt.indicesGet("outputIndices",0)}; let d1 = ${Jt.indicesGet("outputIndices",xt)}; let r = ${Jt.indicesGet("outputIndices",Ge)}; let c = ${Jt.indicesGet("outputIndices",ut)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${Jt.type.value}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${Ae}(dyRCorner) + ${Ae}(wR)) / ${Ae}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${Ae}(uniforms.Dy_shape[${Ge}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${Ae}(dyCCorner) + ${Ae}(wC)) / ${Ae}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${Ae}(uniforms.Dy_shape[${ut}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${a?Yt.get("batch","idyR","idyC","inputChannel"):Yt.get("batch","inputChannel","idyR","idyC")}; let w_offset = ${Kt.indicesToOffset(`${Kt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${Kt.getByOffset(`w_offset / ${k}`)}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd${n?` + bias[d1 / ${k}]`:""}; ${Jt.setByOffset("global_idx","value")}; `;return` ${Me.registerUniforms($e).declareVariables(...Ct,Jt)} ${Me.mainStart()} ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${$t}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}`,inputDependencies:B},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:s?s(i):i,dataType:e[0].dataType}],programUniforms:_e}),getShaderSource:me}}}),Bo,yu,Mu,Ti,bu,vu,xi,Tu,xu,Eu=w(()=>{Vc(),Gr(),Vr(),Bo=(e,t,s,n,i,a)=>(e-1)*t+s+(n-1)*i+1-a,yu=(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)},Mu=(e,t,s,n,i,a,o,d,p,h)=>{let k=e.length-2,S=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((S,u)=>S*u,1)===0){s.length=0;for(let S=2;SS+u,0)===0){let S=t[0].dims.length-2;p=new Array(S).fill(1)}let h=e.strides.slice();if(h.reduce((S,u)=>S+u,0)===0){let S=t[0].dims.length-2;h=new Array(S).fill(1)}Mu(d,s,p,e.autoPad,e.group,i,h,n,o,a);let k=Object.assign({},e);return Object.assign(k,{kernelShape:s,pads:i,outputPadding:o,outputShape:a,dilations:p,strides:h}),k},bu=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,d=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,S=e.outputShape;return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,outputPadding:k,outputShape:S,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},vu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((o,d)=>o+d,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((o,d)=>o+d,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((o,d)=>o+d,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((o,d)=>o+d,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},xi=(e,t,s,n)=>{let i=e.kernelCustomData.wT??e.compute(sr(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(wu(a,s,n),{inputs:a})},Tu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let p=Ti({...t,pads:d,strides:o,dilations:a,kernelShape:i},n);xi(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},xu=(e,t)=>{if(vu(e.inputs,t),e.inputs[0].dims.length===3)Tu(e,t);else{let s=Ti(t,e.inputs);xi(e,e.inputs,s)}}}),Pu,Cu,Ro,Gc=w(()=>{zt(),Bt(),Pt(),Qt(),Pu=(e,t,s,n)=>{let i=Se.size(t),a=t.length,o=Be("input",e,a),d=wt("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=Se.normalizeAxis(p,a),k=S=>{let u=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,B=Mt("uniforms.input_shape","uniforms.axis",a),R=n.reverse?u+(n.exclusive?" + 1":""):"0",U=n.reverse?B:u+(n.exclusive?"":" + 1");return` ${S.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,d)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${d.offsetToIndices("global_idx")}; var sum = ${d.type.value}(0); let first : i32 = ${R}; let last : i32 = ${U}; for (var i : i32 = first; i < last; i++) { ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${o.getByIndices("inputIndices")}; } ${d.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...vt(t,t)]}),getShaderSource:k}},Cu=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(Pu(n,s,i,t),{inputs:[0]})},Ro=e=>{let t=e.exclusive===1,s=e.reverse===1;return ot({exclusive:t,reverse:s})}}),ku,Su,$u,Au,Iu,Ou=w(()=>{zt(),Bt(),Pt(),Qt(),ku=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.")},Su=(e,t,s,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`);for(let a=0;a{let s,n,i,a,o,d,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([s,n,i,a]=e.dims,o=k?[s,n,i,h,h,a/h**2]:[s,n,i,a/h**2,h,h],d=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=k?[s,h,h,a/h**2,n,i]:[s,a/h**2,h,h,n,i],d=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let S=e.reshape(o),u=S.dims.length,B=e.dataType,R=Be("a",B,u),U=wt("output",B,u),Z=se=>` ${se.registerUniform("output_size","u32").declareVariables(R,U)} ${Su(d,u,R,U)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${U.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${U.setByOffset("global_idx",R.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:se=>{let X=p?[s,n*h,i*h,a/h**2]:[s,a/h**2,n*h,i*h],_e=Se.size(X),me=S.dims,Me=Se.sortBasedOnPerm(me,d);return{outputs:[{dims:X,dataType:se[0].dataType}],dispatchGroup:{x:Math.ceil(_e/64)},programUniforms:[{type:12,data:_e},...vt(me,Me)]}},getShaderSource:Z}},Au=(e,t)=>{ku(e.inputs),e.compute($u(e.inputs[0],t))},Iu=e=>ot({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ei,jn,Pi,Fu,Du,Kr,Lu,No,zu,Bu,jo,Kc=w(()=>{zt(),Bt(),Pt(),Qt(),Ei="[a-zA-Z]|\\.\\.\\.",jn="("+Ei+")+",Pi="^"+jn+"$",Fu="("+jn+",)*"+jn,Du="^"+Fu+"$",Kr=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},Lu=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(Du)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,o)=>{let d=e[o].dims.slice();if(!a.match(RegExp(Pi)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,d,o);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,o])=>o.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(jn)))throw new Error("Invalid RHS");(i=n.match(RegExp(Ei,"g")))==null||i.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(a);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let i=s.length,a=!1,o=[],d=0;if(!e.match(RegExp(Pi))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(Ei,"g")),h=new Kr(n);return p==null||p.forEach((k,S)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let u=i-p.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(o=s.slice(d,d+u),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let B=0;Be+"_max",zu=(e,t,s,n)=>{let i=e.map(h=>h.length).map((h,k)=>Be(`input${k}`,t,h)),a=Se.size(n),o=wt("output",t,n.length),d=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],S="var prod = 1.0;",u="var sum = 0.0;",B="sum += prod;",R=[],U=[],Z=[],se=[],X=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((me,Me)=>{var $e;if(s.rhs.symbolToIndices.has(Me)){let Ae=($e=s.rhs.symbolToIndices.get(Me))==null?void 0:$e[0];Ae!==void 0&&s.lhs.forEach((Ge,ut)=>{if(me.inputIndices.includes(ut)){let xt=Ge.symbolToIndices.get(Me);if(xt===void 0)throw new Error("Invalid symbol error");xt.forEach(Kt=>{k.push(`${i[ut].indicesSet(`input${ut}Indices`,Kt,o.indicesGet("outputIndices",Ae))}`)})}})}else s.lhs.forEach((Ae,Ge)=>{if(me.inputIndices.includes(Ge)){let ut=Ae.symbolToIndices.get(Me);if(ut===void 0)throw new Error("Invalid symbol error");ut.forEach(xt=>{R.push(`${i[Ge].indicesSet(`input${Ge}Indices`,xt,`${Me}`)}`)}),se.push(`prod *= ${i[Ge].getByIndices(`input${Ge}Indices`)};`)}}),U.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${No(Me)}; ${Me}++) {`),Z.push("}")});let _e=X?[...k,`let sum = ${i.map((me,Me)=>me.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...k,u,...U,...R,S,...se,B,...Z];return` ${h.registerUniforms(d.map(me=>({name:`${No(me)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${o.offsetToIndices("global_idx")}; ${i.map((me,Me)=>`var input${Me}Indices: ${i[Me].type.indices};`).join(` `)} ${_e.join(` `)}; ${o.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=d.filter(S=>s.symbolToInfo.has(S)).map(S=>{var u;return{type:12,data:((u=s.symbolToInfo.get(S))==null?void 0:u.dimValue)||0}});h.push({type:12,data:a});let k=e.map((S,u)=>[...vt(S)]).reduce((S,u)=>S.concat(u),h);return k.push(...vt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},Bu=(e,t)=>{let s=new Lu(e.inputs,t.equation),n=s.outputDims,i=e.inputs.map((a,o)=>a.dims);e.compute(zu(i,e.inputs[0].dataType,s,n))},jo=e=>{let t=e.equation.replace(/\s+/g,"");return ot({equation:t})}}),Ru,Wo,Nu,Ci,ju,Hc=w(()=>{zt(),Bt(),Qt(),Ru=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?Wo(e,t):Wo(t,e),Ci=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Nu(t,s),i=e[0].dataType,a=i===9||Se.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4===0?4:1,d=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(Se.size(n)/d),h=S=>{let u=Be("input",i,t.length,o),B=wt("output",i,n.length,d),R;if(i===9){let U=(Z,se,X="")=>` let outputIndices${se} = ${B.offsetToIndices(`outputOffset + ${se}u`)}; let offset${se} = ${u.broadcastedIndicesToOffset(`outputIndices${se}`,B)}; let index${se} = offset${se} / 4u; let component${se} = offset${se} % 4u; ${Z}[${se}] = ${X}(${u.getByOffset(`index${se}`)}[component${se}]); `;R=` let outputOffset = global_idx * ${d}; var data = vec4(0); ${U("data",0,"u32")} ${U("data",1,"u32")} ${U("data",2,"u32")} ${U("data",3,"u32")} ${B.setByOffset("global_idx","data")} }`}else R=` let outputIndices = ${B.offsetToIndices(`global_idx * ${d}`)}; let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",B)}; let data = ${B.type.value}(${u.getByOffset(`inputOffset / ${o}`)}); ${B.setByOffset("global_idx","data")} }`;return` ${S.registerUniform("vec_size","u32").declareVariables(u,B)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${R}`},k=[{type:12,data:p},...vt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${o}${d}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},ju=e=>{Ru(e.inputs),e.compute(Ci(e.inputs),{inputs:[0]})}}),Wu,Wn,qc=w(()=>{zt(),Bt(),Qt(),To(),Wu=e=>{let t=e[0].dataType,s=Se.size(e[0].dims),n=Se.size(e[1].dims),i=n%4===0,a=o=>{let d=Be("x",t,[1],4),p=Be("bias",t,[1],4),h=wt("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],S=B=>` let bias${B}_offset: u32 = (global_idx * 4 + ${B}) % uniforms.bias_size; let bias${B} = ${p.getByOffset(`bias${B}_offset / 4`)}[bias${B}_offset % 4];`,u=i?` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${S(0)}${S(1)}${S(2)}${S(3)} let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(k).declareVariables(d,p,h)} ${pi(_s(t))} ${o.mainStart(Ns)} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${u} let x_in = x + bias; ${h.setByOffset("global_idx",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/Ns/4)}})}},Wn=e=>{e.inputs.length<2||Se.size(e.inputs[1].dims)===0?Ol(e):e.compute(Wu(e.inputs))}}),Uu,Vu,Gu,ki,Xc=w(()=>{zt(),Bt(),Pt(),Qt(),Uu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Vu=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=Se.normalizeAxis(t.axis,i),o=s.slice(0);o.splice(a,1,...n);let d=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(Se.size(o)/p),k=[{type:12,data:h},{type:6,data:d},{type:12,data:a},...vt(e[0].dims,e[1].dims,o)],S=u=>{let B=Be("data",e[0].dataType,e[0].dims.length,p),R=Be("inputIndices",e[1].dataType,e[1].dims.length),U=wt("output",e[0].dataType,o.length,p),Z=X=>{let _e=n.length,me=`var indicesIndices${X} = ${R.type.indices}(0);`;for(let Me=0;Me<_e;Me++)me+=`${_e>1?`indicesIndices${X}[${Me}]`:`indicesIndices${X}`} = ${o.length>1?`outputIndices${X}[uniforms.axis + ${Me}]`:`outputIndices${X}`};`;me+=` var idx${X} = ${R.getByIndices(`indicesIndices${X}`)}; if (idx${X} < 0) { idx${X} = idx${X} + uniforms.axisDimLimit; } var dataIndices${X} : ${B.type.indices}; `;for(let Me=0,$e=0;Me1?`dataIndices${X}[${Me}]`:`dataIndices${X}`} = u32(idx${X});`,$e+=_e):(me+=`${i>1?`dataIndices${X}[${Me}]`:`dataIndices${X}`} = ${o.length>1?`outputIndices${X}[${$e}]`:`outputIndices${X}`};`,$e++);return me},se;if(e[0].dataType===9){let X=(_e,me,Me="")=>` let outputIndices${me} = ${U.offsetToIndices(`outputOffset + ${me}u`)}; ${Z(me)}; let offset${me} = ${B.indicesToOffset(`dataIndices${me}`)}; let index${me} = offset${me} / 4u; let component${me} = offset${me} % 4u; ${_e}[${me}] = ${Me}(${B.getByOffset(`index${me}`)}[component${me}]); `;se=` let outputOffset = global_idx * ${p}; var value = vec4(0); ${X("value",0,"u32")} ${X("value",1,"u32")} ${X("value",2,"u32")} ${X("value",3,"u32")} ${U.setByOffset("global_idx","value")} `}else se=` let outputIndices = ${U.offsetToIndices("global_idx")}; ${Z("")}; let value = ${B.getByIndices("dataIndices")}; ${U.setByOffset("global_idx","value")}; `;return` ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(B,R,U)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${se} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:S}},Gu=e=>ot({axis:e.axis}),ki=(e,t)=>{let s=e.inputs;Uu(s),e.compute(Vu(e.inputs,t))}}),Ku,Hu,Qc,Yc=w(()=>{zt(),Bt(),Qt(),Ku=(e,t,s,n,i,a,o,d,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:i},{type:12,data:s},{type:12,data:o},{type:12,data:d},{type:12,data:p}],k=[a];h.push(...vt(t.dims,k));let S=u=>{let B=Be("indices_data",t.dataType,t.dims.length),R=wt("input_slice_offsets_data",12,1,1),U=[B,R],Z=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${u.registerUniforms(Z).declareVariables(...U)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${i.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} } ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:S},{inputs:[t],outputs:[-1]})[0]},Hu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=s[0].dataType,a=s[1].dims,o=a[a.length-1],d=Se.sizeToDimension(a,a.length-1),p=Se.sizeFromDimension(n,t.batchDims+o),h=Se.sizeToDimension(n,t.batchDims),k=Se.sizeFromDimension(n,t.batchDims),S=d/h,u=new Array(o),B=p;for(let me=0;men.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(U)),se=Se.size(Z),X=[{type:12,data:se},{type:12,data:p},...vt(s[0].dims,R.dims,Z)],_e=me=>{let Me=Be("data",s[0].dataType,s[0].dims.length),$e=Be("slice_offsets",12,R.dims.length),Ae=wt("output",s[0].dataType,Z.length);return` ${me.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,$e,Ae)} ${me.mainStart()} ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:i}],dispatchGroup:{x:Math.ceil(se/64)},programUniforms:X}),getShaderSource:_e},{inputs:[s[0],R]})},Qc=e=>({batchDims:e.batch_dims,cacheKey:""})}),qu,Xu,Pn,Qu,Jc=w(()=>{zt(),Bt(),Pt(),Qt(),qu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=Se.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],a=e[2],o=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((d,p)=>p===s?Math.ceil(d/n)===a.dims[p]:d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==a.dims.length||!o.dims.map((d,p)=>d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Xu=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=Se.normalizeAxis(t.gatherAxis,i),o=Se.normalizeAxis(t.quantizeAxis,i),d=s.slice(0);d.splice(a,1,...n);let p=Se.size(d),h=e[2].dataType,k=e[0].dataType===22,S=[{type:12,data:p},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...vt(...e.map((B,R)=>B.dims),d)],u=B=>{let R=Be("data",e[0].dataType,e[0].dims.length),U=Be("inputIndices",e[1].dataType,e[1].dims.length),Z=Be("scales",e[2].dataType,e[2].dims.length),se=e.length>3?Be("zeroPoint",e[3].dataType,e[3].dims.length):void 0,X=wt("output",h,d.length),_e=[R,U,Z];se&&_e.push(se);let me=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${B.registerUniforms(me).declareVariables(..._e,X)} ${B.mainStart()} let output_indices = ${X.offsetToIndices("global_idx")}; var indices_indices = ${U.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${X.indicesGet("output_indices","uniforms.gather_axis + i")}; ${U.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${X.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${R.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${X.indicesGet("output_indices","i")}; ${R.indicesSet("data_indices","i","index")}; } var index_from_indices = ${U.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${s[a]}; } ${R.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${d.length}; i++) { let index = ${X.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${R.indicesSet("data_indices","i","index")}; } let data_offset = ${R.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${Z.getByIndices("scale_indices")}; ${se?` let zero_point_indices = scale_indices; let zero_point_offset = ${se.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${se.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; ${X.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((B,R)=>R!==1).map(B=>B.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(B,R)=>"rank")},getRunData:()=>({outputs:[{dims:d,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:S}),getShaderSource:u}},Pn=(e,t)=>{let s=e.inputs;qu(s,t),e.compute(Xu(e.inputs,t))},Qu=e=>ot({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Yu,Ju,Zu,Si,zp=w(()=>{zt(),Bt(),Pt(),Qt(),Yu=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.`)},Ju=(e,t)=>{let s=e[0].dims,n=e[0].dataType,i=s.length,a=e[1].dims,o=e[1].dataType,d=Se.normalizeAxis(t.axis,i),p=s[d],h=a.slice(0),k=Se.size(h),S=Be("input",n,i),u=Be("indicesInput",o,a.length),B=wt("output",n,h.length),R=[{type:12,data:k},{type:6,data:p},{type:12,data:d}];return R.push(...vt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:R}),getShaderSource:U=>` ${U.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(S,u,B)} ${U.mainStart()} ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${B.offsetToIndices("global_idx")}; var idx = ${u.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${S.type.indices}(outputIndices); ${S.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${S.getByIndices("inputIndices")}; ${B.setByOffset("global_idx","value")}; }`}},Zu=e=>ot({axis:e.axis}),Si=(e,t)=>{let s=e.inputs;Yu(s),e.compute(Ju(e.inputs,t))}}),ed,td,sd,rd,Zc=w(()=>{zt(),Bt(),Qt(),ed=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")},td=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,o]=Rs.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),d=[i,a];if(!d)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(i/p),S=!0,u=Se.size(d),B=[{type:12,data:S?h:u},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],R=["type","type"];e.length===3&&(B.push(...vt(e[2].dims)),R.push("rank")),B.push(...vt(d));let U=se=>{let X="";t.transA&&t.transB?X="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?X="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?X="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(X="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let _e=t.alpha===1?"":"value *= uniforms.alpha;",me=Be("a",e[0].dataType,e[0].dims),Me=Be("b",e[1].dataType,e[1].dims),$e=me.type.value,Ae=null,Ge=[me,Me];e.length===3&&(Ae=Be("c",e[2].dataType,e[2].dims.length),Ge.push(Ae));let ut=wt("output",e[0].dataType,d.length);Ge.push(ut);let xt=[{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` ${se.registerUniforms(xt).declareVariables(...Ge)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${$e}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${X} } ${_e} ${Ae!=null?`let cOffset = ${Ae.broadcastedIndicesToOffset("vec2(m, n)",ut)}; value += ${$e}(uniforms.beta) * ${Ae.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},Z=se=>{let X=Be("a",e[0].dataType,e[0].dims),_e=Be("b",e[1].dataType,e[1].dims),me=null,Me=[X,_e];e.length===3&&(me=Be("c",e[2].dataType,e[2].dims.length),Me.push(me));let $e=wt("output",e[0].dataType,d.length);Me.push($e);let Ae=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],Ge="",ut="";t.transA&&t.transB?(ut=` 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] = ${X.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] = ${_e.type.value}(0); } `,Ge="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(ut=` 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] = ${X.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] = ${_e.type.value}(0); } `,Ge="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(ut=` 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] = ${X.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] = ${_e.type.value}(0); } `,Ge="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(ut=` 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] = ${X.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] = ${_e.type.value}(0); } `,Ge="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let xt=t.alpha===1?"":"value *= uniforms.alpha;";return` ${se.registerUniforms(Ae).declareVariables(...Me)} var tile_a: array, ${p}>; var tile_b: array, ${p}>; ${se.mainStart([p,p,1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; let num_tiles = (uniforms.K - 1) / ${p} + 1; var k_start = 0u; var value = ${$e.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${ut} k_start = k_start + ${p}; workgroupBarrier(); for (var k: u32 = 0u; k < ${p}; k++) { ${Ge} } workgroupBarrier(); } ${xt} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${me!=null?`let cOffset = ${me.broadcastedIndicesToOffset("vec2(m, n)",$e)}; value += ${$e.type.value}(uniforms.beta) * ${me.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return S?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:B}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:U}},sd=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}`}},rd=(e,t)=>{ed(e.inputs),e.compute(td(e.inputs,t))}}),gr,Or,an,Hr,nd,id,Uo,od,ad,$i,ld,ud,dd,cd,pd=w(()=>{zt(),Bt(),Pt(),Qt(),[gr,Or,an,Hr]=[0,1,2,3],nd=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},id=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); var coeffs: vec4; coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } `,Uo=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; } `,od=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)); `} } `,ad=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); }`:""} `,$i=(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[${gr}] = batch; indices[${Or}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${an}] = u32(r); indices[${Hr}] = u32(c); } `;case"border":return` indices[${an}] = u32(clamp(r, 0, H - 1)); indices[${Hr}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${an}] = gs_reflect(r, border[1], border[3]); indices[${Hr}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,ld=(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[${gr}], indices[${Or}], 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[${gr}], indices[${Or}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${gr}], indices[${Or}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${gr}], indices[${Or}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${gr}], indices[${Or}], 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[${gr}], indices[${Or}], 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")}`,ud=(e,t)=>{let s=Be("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=Be("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]],[gr,Or,an,Hr]=[0,3,1,2]);let o=wt("output",e[0].dataType,a.length),d=s.type.value,p=Se.size(a),h=[{type:12,data:p},...vt(e[0].dims,n,a)],k=S=>` ${S.registerUniform("output_size","u32").declareVariables(s,i,o)} ${id} ${Uo(d)} ${od(t)} ${ad(t)} ${$i(s,d,t)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${an}]); let W_in = i32(uniforms.x_shape[${Hr}]); ${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[${gr}], indices[${an}], indices[${Hr}]); let nxy = ${i.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${ld(o,d,t)} }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:S=>{let u=Se.size(a);return{outputs:[{dims:a,dataType:S[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}},getShaderSource:k}},dd=(e,t)=>{nd(e.inputs),e.compute(ud(e.inputs,t))},cd=e=>ot({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Gs,ep,hd,Vo,Go,Un,md,Ko=w(()=>{zt(),Bt(),Pt(),bn(),di(),Qt(),Vr(),Gs=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,ep=(e,t)=>{let s=e[0],n=Gs(e,1),i=Gs(e,2),a=Gs(e,3),o=Gs(e,4),d=Gs(e,5),p=Gs(e,6),h=Gs(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=s.dims[0],S=s.dims[1],u=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],B=S,R=0,U=0,Z=Math.floor(u/t.numHeads);if(p&&h&&Se.size(p.dims)&&Se.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');R=p.dims[2],U=p.dims[2]}else if(p&&Se.size(p.dims)||h&&Se.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let se;if(n&&Se.size(n.dims)>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');se=2,B=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');se=5,B=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');se=0,B=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');se=3}if(a&&Se.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let X=R+B,_e=0;if(o&&Se.size(o.dims)>0){_e=8;let Ae=o.dims;throw Ae.length===1?Ae[0]===k?_e=1:Ae[0]===3*k+2&&(_e=3):Ae.length===2&&Ae[0]===k&&Ae[1]===X&&(_e=5),_e===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let me=!1,Me=u;if(i&&Se.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(B!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Me=i.dims[2]}else{if(B!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Me=i.dims[1]*i.dims[3],me=!0}}let $e=!1;if(o&&Se.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(d&&Se.size(d.dims)>0){if(d.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(d.dims[0]!==k||d.dims[1]!==t.numHeads||d.dims[2]!==S||d.dims[3]!==X)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:S,pastSequenceLength:R,kvSequenceLength:B,totalSequenceLength:X,maxSequenceLength:U,inputHiddenSize:0,hiddenSize:u,vHiddenSize:Me,headSize:Z,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:_e,scale:t.scale,broadcastResPosBias:$e,passPastInKv:me,qkvFormat:se}},hd=e=>ot({...e}),Vo=ot({perm:[0,2,1,3]}),Go=(e,t,s,n,i,a,o)=>{let d=[n,i,a],p=Se.size(d),h=[{type:12,data:p},{type:12,data:o},{type:12,data:a}],k=S=>{let u=wt("qkv_with_bias",t.dataType,d),B=Be("qkv",t.dataType,d),R=Be("bias",s.dataType,d),U=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${S.registerUniforms(U).declareVariables(B,R,u)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},Un=(e,t,s,n,i,a,o,d)=>{let p=a;if(o&&Se.size(o.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=Go(e,a,o,t,n,s*i,d),p=p.reshape([t,n,s,i]),s===1||n===1?p:e.compute(sr(p,Vo.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(sr(p,Vo.perm),{inputs:[p],outputs:[-1]})[0]},md=(e,t)=>{let s=ep(e.inputs,t),n=e.inputs[0],i=Gs(e.inputs,1),a=Gs(e.inputs,2),o=Gs(e.inputs,3),d=Gs(e.inputs,4),p=Gs(e.inputs,5),h=Gs(e.inputs,6),k=Gs(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let S=i&&a&&i.dims.length===4&&a.dims.length===4,u=Un(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,o,0);if(S)return xn(e,u,i,a,d,void 0,h,k,p,s);if(!i||!a)throw new Error("key and value must be provided");let B=Un(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,i,o,s.hiddenSize),R=Un(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,o,2*s.hiddenSize);xn(e,u,B,R,d,void 0,h,k,p,s)}}),_d,fd,Ho,tp,gd,qo,Xo,wd=w(()=>{zt(),Bt(),Pt(),Qt(),_d=e=>{if(!e||e.length<1)throw new Error("too few inputs")},fd=(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),ot({numOutputs:n,axis:t.axis,splitSizes:s})},Ho=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Mt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,tp=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=Se.size(s),i=e[0].dataType,a=Se.normalizeAxis(t.axis,s.length),o=new Array(t.numOutputs),d=Be("input",i,s.length),p=new Array(t.numOutputs),h=[],k=[],S=0,u=[{type:12,data:n}];for(let R=0;R` ${R.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(d,...o)} ${Ho(p.length)} ${tp(o)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${d.offsetToIndices("global_idx")}; var index = ${d.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Mt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; ${d.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},qo=(e,t)=>{_d(e.inputs);let s=e.inputs.length===1?t:fd(e.inputs,t);e.compute(gd(e.inputs,s),{inputs:[0]})},Xo=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 ot({axis:t,numOutputs:n,splitSizes:s})}}),yd,Qo,Yo,Md,bd=w(()=>{Pt(),di(),Ko(),wd(),Vr(),yd=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?d?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],S=h,u=0,B=!n||n.dims.length===0,R=Math.floor(B?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);B&&(k=R*t.numHeads);let U=a&&a.dims.length!==0,Z=o&&o.dims.length!==0;if(U&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===R)throw new Error("BSNH pastKey/pastValue is not supported");if(U&&Z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=a.dims[2]}else if(U||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let se=1;if(n&&n.dims.length>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');S=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');S=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');S=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');se=3}let X=0,_e=!1,me=t.kvNumHeads?R*t.kvNumHeads:k;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(S!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=i.dims[2]}else{if(S!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=i.dims[1]*i.dims[3],_e=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:u,kvSequenceLength:S,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:me,headSize:R,vHeadSize:Math.floor(me/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_e,qkvFormat:se}},Qo=ot({perm:[0,2,1,3]}),Yo=(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(sr(n,Qo.perm),{inputs:[n],outputs:[-1]})[0]),n},Md=(e,t)=>{var Z;let s=yd(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,d=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=s.kvNumHeads?s.kvNumHeads:s.numHeads,S=ot({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[u,B,R]=!i&&!a?e.compute(gd([n],S),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],U=Un(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,void 0,0);xn(e,U,Yo(e,B,s),Yo(e,R,s),void 0,void 0,o,d,void 0,s,p,h)}}),Jo,vd,Zo,Td,sp=w(()=>{zt(),Bt(),Vr(),Qt(),Jo=(e,t,s,n,i,a,o,d)=>{let p=ys(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,S=i*o,u=64;S===1&&(u=256);let B=[i,o,a/p],R=[i,o,2],U=["rank","type","type"],Z=[];Z.push(...vt(B,R));let se=X=>{let _e=Be("x",t.dataType,3,p),me=Be("scale",s.dataType,s.dims),Me=Be("bias",n.dataType,n.dims),$e=wt("output",1,3,2),Ae=[_e,me,Me,$e];return` var workgroup_shared : array<${k}, ${u}>; const workgroup_size = ${u}u; ${X.declareVariables(...Ae)} ${X.mainStart(u)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${h}(0); var squared_sum = ${h}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${h}(${_e.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 = ${Hs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); let squared_sum_final = ${Hs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${d})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${d};${u}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:R,dataType:1}],dispatchGroup:{x:S},programUniforms:Z}),getShaderSource:se},{inputs:[t,s,n],outputs:[-1]})[0]},vd=(e,t,s)=>{let n=t[0].dims,i=n,a=2,o=n[0],d=n[1],p=Se.sizeFromDimension(n,a),h=ys(p),k=Se.size(i)/h,S=Jo(e,t[0],t[1],t[2],o,p,d,s.epsilon),u=[o,d,p/h],B=[o,d],R=["type","none"],U=Z=>{let se=Be("x",t[0].dataType,u.length,h),X=Be("scale_shift",1,B.length,2),_e=wt("output",t[0].dataType,u.length,h),me=[se,X,_e];return` ${Z.registerUniform("output_size","u32").declareVariables(...me)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${_e.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${X.getByIndices("vec2(batch, channel)")}; let value = ${se.getByOffset("global_idx")} * ${_e.type.value}(scale_shift.x) + ${_e.type.value}(scale_shift.y); ${_e.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...vt(u,B,u)]}),getShaderSource:U},{inputs:[t[0],S]})},Zo=(e,t,s)=>{let n=t[0].dims,i=n,a=n[0],o=n[n.length-1],d=Se.sizeFromDimension(n,1)/o,p=ys(o),h=Se.size(i)/p,k=[{type:12,data:d},{type:12,data:Math.floor(o/p)}],S=["type","type"],u=!1,B=[0,n.length-1];for(let se=0;sen[B[X]])),U=Jo(e,R,t[1],t[2],a,d,o,s.epsilon),Z=se=>{let X=es(t[0].dataType),_e=p===1?"vec2f":`mat${p}x2f`,me=Ae=>{let Ge=Ae===0?"x":"y",ut=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${X}(${ut}(scale.${Ge}))`;case 2:return`vec2<${X}>(${ut}(scale[0].${Ge}, scale[1].${Ge}))`;case 4:return`vec4<${X}>(${ut}(scale[0].${Ge}, scale[1].${Ge}, scale[2].${Ge}, scale[3].${Ge}))`;default:throw new Error(`Not supported compoents ${p}`)}},Me=Be("input",t[0].dataType,t[0].dims,p),$e=wt("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<${_e}>; @group(0) @binding(2) var output : array<${$e.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${se.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${me(0)}, ${me(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],U]})},Td=(e,t)=>{t.format==="NHWC"?Zo(e,e.inputs,t):vd(e,e.inputs,t)}}),xd,Ed,Pd,rp=w(()=>{zt(),Bt(),Qt(),xd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Ed=(e,t,s)=>{let n=t.simplified,i=e[0].dims,a=e[1],o=!n&&e[2],d=i,p=Se.normalizeAxis(t.axis,i.length),h=Se.sizeToDimension(i,p),k=Se.sizeFromDimension(i,p),S=Se.size(a.dims),u=o?Se.size(o.dims):0;if(S!==k||o&&u!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. Size of scale and bias (if provided) must match this. Got scale size of ${S} and bias size of ${u}`);let B=[];for(let Me=0;Me1,X=s>2,_e=Me=>{let $e=es(e[0].dataType),Ae=[Be("x",e[0].dataType,e[0].dims,R),Be("scale",a.dataType,a.dims,R)];o&&Ae.push(Be("bias",o.dataType,o.dims,R)),Ae.push(wt("output",e[0].dataType,d,R)),se&&Ae.push(wt("mean_data_output",1,B)),X&&Ae.push(wt("inv_std_output",1,B));let Ge=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${Me.registerUniforms(Ge).declareVariables(...Ae)} ${Me.mainStart()} ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Pr("f32",R)}; var mean_square_vector = ${Pr("f32",R)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Ds($e,R,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Hs("mean_vector",R)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Hs("mean_square_vector",R)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Ds($e,R,"x[j + offset]")}; let f32scale = ${Ds($e,R,"scale[j]")}; output[j + offset] = ${Ae[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${o?`+ ${Ds($e,R,"bias[j]")}`:""} ); } ${se?"mean_data_output[global_idx] = mean":""}; ${X?"inv_std_output[global_idx] = inv_std_dev":""}; }`},me=[{dims:d,dataType:e[0].dataType}];return se&&me.push({dims:B,dataType:1}),X&&me.push({dims:B,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${R};${s};${n}`,inputDependencies:U},getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:_e}},Pd=(e,t)=>{xd(e.inputs),e.compute(Ed(e.inputs,t,e.outputCount))}}),Cd,kd,np=w(()=>{Bt(),$o(),wi(),Cd=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.")},kd=e=>{Cd(e.inputs);let t=ss.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(mi(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=Se.size(e.inputs[0].dims.slice(0,-2)),o=Se.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let d=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],k=[d,p];e.compute(gi(k,{activation:""},t,h),{inputs:k})}else e.compute(gi(e.inputs,{activation:""},t))}}}),ea,Sd,$d,ta,Ad,ip=w(()=>{zt(),Bt(),Pt(),Qt(),ea=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,o=e[1];if(!Se.areEqual(o.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(Se.size(d)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(Se.size(p)!==h)throw new Error("zeroPoints input size error.")}},Sd=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,d=s.slice(0,n-2),p=Se.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=ys(t.k),u=ys(h),B=ys(o),R=d.concat([i,o]),U=i>1&&o/B%2===0?2:1,Z=Se.size(R)/B/U,se=64,X=[],_e=[p,i,a/S],me=Se.convertShape(e[1].dims).slice();me.splice(-1,1,h/u),X.push(...vt(_e)),X.push(...vt(me)),X.push(...vt(e[2].dims)),e.length===4&&X.push(...vt(Se.convertShape(e[3].dims)));let Me=[p,i,o/B];X.push(...vt(Me));let $e=Ae=>{let Ge=_e.length,ut=Be("a",e[0].dataType,Ge,S),xt=Be("b",12,me.length,u),Kt=Be("scales",e[2].dataType,e[2].dims.length),Yt=[ut,xt,Kt],Ct=e.length===4?Be("zero_points",12,e[3].dims.length):void 0;Ct&&Yt.push(Ct);let Jt=Me.length,$t=wt("output",e[0].dataType,Jt,B),jt=es(e[0].dataType),vs=(()=>{switch(S){case 1:return`array<${jt}, 8>`;case 2:return`mat4x2<${jt}>`;case 4:return`mat2x4<${jt}>`;default:throw new Error(`${S}-component is not supported.`)}})(),Ht=()=>{let it=` // reuse a data var input_offset = ${ut.indicesToOffset(`${ut.type.indices}(batch, row, word_offset)`)}; var a_data: ${vs}; for (var j: u32 = 0; j < ${8/S}; j++) { a_data[j] = ${ut.getByOffset("input_offset")}; input_offset++; } `;for(let Et=0;Et> 4) & b_mask); b_quantized_values = ${vs}(${Array.from({length:4},(cs,Ls)=>`${jt}(b_value_lower[${Ls}]), ${jt}(b_value_upper[${Ls}])`).join(", ")}); b_dequantized_values = ${S===1?`${vs}(${Array.from({length:8},(cs,Ls)=>`(b_quantized_values[${Ls}] - ${Ct?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${vs}(${Array(8).fill(`${Ct?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; workgroup_shared[local_id.x * ${U} + ${Math.floor(Et/B)}]${B>1?`[${Et%B}]`:""} += ${Array.from({length:8/S},(cs,Ls)=>`${S===1?`a_data[${Ls}] * b_dequantized_values[${Ls}]`:`dot(a_data[${Ls}], b_dequantized_values[${Ls}])`}`).join(" + ")}; `;return it},Gt=()=>{let it=` var col_index = col * ${B}; ${Ct?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${jt}(8);`} `;for(let Et=0;Et> 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 = ${Ct.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${Et} = ${jt}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return it},Ps=()=>{let it=`col_index = col * ${B};`;for(let Et=0;Et; var b_value_upper: vec4; var b_quantized_values: ${vs}; var b_dequantized_values: ${vs};`,it};return` var workgroup_shared: array<${$t.type.value}, ${U*se}>; ${Ae.declareVariables(...Yt,$t)} ${Ae.mainStart([se,1,1])} let output_indices = ${$t.offsetToIndices(`(global_idx / ${se}) * ${U}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${se}) { //process one block var word_offset: u32 = block * ${t.blockSize/S}; ${Gt()} for (var word: u32 = 0; word < ${h}; word += ${u}) { ${Ps()} for (var i: u32 = 0; i < ${u}; i++) { ${Ht()} word_offset += ${8/S}; } } } workgroupBarrier(); if (local_id.x < ${U}) { var output_value: ${$t.type.value} = ${$t.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${se}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${U}; } ${$t.setByIndices(`${$t.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${S};${u};${B};${U};${se}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:R,dataType:k}],dispatchGroup:{x:Z},programUniforms:X}),getShaderSource:$e}},$d=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,d=s.slice(0,n-2),p=Se.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=ys(t.k),u=ys(h),B=d.concat([i,o]),R=128,U=o%8===0?8:o%4===0?4:1,Z=R/U,se=Z*u*8,X=se/S,_e=se/t.blockSize,me=Se.size(B)/U,Me=[],$e=[p,i,a/S],Ae=Se.convertShape(e[1].dims).slice();Ae.splice(-1,1,h/u),Me.push(...vt($e)),Me.push(...vt(Ae)),Me.push(...vt(e[2].dims)),e.length===4&&Me.push(...vt(Se.convertShape(e[3].dims)));let Ge=[p,i,o];Me.push(...vt(Ge));let ut=xt=>{let Kt=$e.length,Yt=Be("a",e[0].dataType,Kt,S),Ct=Be("b",12,Ae.length,u),Jt=Be("scales",e[2].dataType,e[2].dims.length),$t=[Yt,Ct,Jt],jt=e.length===4?Be("zero_points",12,e[3].dims.length):void 0;jt&&$t.push(jt);let vs=Ge.length,Ht=wt("output",e[0].dataType,vs),Gt=es(e[0].dataType),Ps=()=>{switch(S){case 1:return` let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Gt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Gt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${S}-component is not supported.`)}};return` var sub_a: array<${Yt.type.value}, ${X}>; var inter_results: array, ${U}>; ${xt.declareVariables(...$t,Ht)} ${xt.mainStart([Z,U,1])} let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${U}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${_e} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${X}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${X}; a_offset += ${R}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${Yt.getByIndices(`${Yt.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${Yt.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${_e} + local_id.x; ${jt?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${jt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Gt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Gt}(8);`} let scale = ${Jt.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${Ct.getByIndices(`${Ct.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/S}; for (var i: u32 = 0; i < ${u}; i++) { ${Ps()} let b_value = ${u===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Gt}>(${Array.from({length:4},(it,Et)=>`${Gt}(b_value_lower[${Et}]), ${Gt}(b_value_upper[${Et}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Gt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(it,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; word_offset += ${8/S}; } workgroupBarrier(); } if (local_idx < ${U}) { var output_value: ${Ht.type.value} = ${Ht.type.value}(0); for (var b = 0u; b < ${Z}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Ht.setByIndices(`${Ht.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${S};${u};${Z};${U}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:me},programUniforms:Me}),getShaderSource:ut}},ta=(e,t)=>{ea(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute($d(e.inputs,t)):e.compute(Sd(e.inputs,t))},Ad=e=>ot(e)}),fs,op,ap,lp,sa,Id,Od,Fd,Dd,Ld=w(()=>{zt(),Bt(),Qt(),fs=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].")}},op=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { break; } if (k >= i32(${Mt("uniforms.x_shape",i,t)})) { break; } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},ap=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Mt("uniforms.x_shape",i,t)}) - 1); k = k % _2n_1; if(k >= i32(${Mt("uniforms.x_shape",i,t)})) { k = _2n_1 - k; } } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},lp=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { k = 0; } if (k >= i32(${Mt("uniforms.x_shape",i,t)})) { k = i32(${Mt("uniforms.x_shape",i,t)}) - 1; } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},sa=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` k = i32(${e.indicesGet("indices",i)}) - ${Mt("uniforms.pads",i,s)}; if (k < 0) { k += i32(${Mt("uniforms.x_shape",i,t)}]); } if (k >= i32(${Mt("uniforms.x_shape",i,t)})) { k -= i32(${Mt("uniforms.x_shape",i,t)}); } offset += k * i32(${Mt("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},Id=(e,t,s)=>{switch(s.mode){case 0:return op(e,t,s.pads.length);case 1:return ap(e,t,s.pads.length);case 2:return lp(e,t,s.pads.length);case 3:return sa(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Od=(e,t)=>{let s=Se.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=Se.size(s),a=[{type:12,data:i},{type:6,data:t.pads}],o=e.length>=3&&e[2].data;t.mode===0&&a.push({type:o?e[2].dataType:1,data:t.value}),a.push(...vt(e[0].dims,s));let d=["rank"],p=h=>{let k=wt("output",e[0].dataType,s.length),S=Be("x",e[0].dataType,n.length),u=S.type.value,B=Id(k,n.length,t),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&R.push({name:"constant_value",type:o?u:"f32"}),` ${h.registerUniforms(R).declareVariables(S,k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${k.offsetToIndices("global_idx")}; var value = ${u}(0); ${B} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(s)/64)},programUniforms:a}),getShaderSource:p}},Fd=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(d));let o=[];return a.forEach(d=>o.push(d)),{mode:t.mode,value:n,pads:o}}else return t},Dd=(e,t)=>{fs(e.inputs);let s=Fd(e.inputs,t);e.compute(Od(e.inputs,s),{inputs:[0]})}}),Cn,zd,ra,na,Ai,up,dp,ia,oa,Bd,Rd,aa,Nd,jd,la,Wd,Ud,Vd,Gd,Bp=w(()=>{Qe(),zt(),Bt(),Qt(),Cn=e=>{if(T.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},zd=(e,t,s)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),o=t.kernelShape.slice(),d=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();ws.adjustPoolAttributes(s,i,o,d,p,h);let k=ws.computePoolOutputShape(s,i,d,p,o,h,t.autoPad),S=Object.assign({},t);a?Object.assign(S,{kernelShape:o,strides:d,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(S,{kernelShape:o,strides:d,pads:h,cacheKey:t.cacheKey});let u=k.slice();return u.push(u.splice(1,1)[0]),[S,n?u:k]},ra=(e,t)=>{let s=t.format==="NHWC",n=Se.size(e),i=Se.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],S=!!(h+k);a.push({type:12,data:d},{type:12,data:p},{type:12,data:h},{type:12,data:k}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(t.kernelShape.length===2){let B=t.kernelShape[t.kernelShape.length-2],R=t.strides[t.strides.length-2],U=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];u=!!(U+Z),a.push({type:12,data:B},{type:12,data:R},{type:12,data:U},{type:12,data:Z}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,o,!0,S,u]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=Se.computeStrides(t.kernelShape);a.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[a,o,!!p,!1,!1]}},na=(e,t,s,n,i,a,o,d,p,h,k,S)=>{let u=i.format==="NHWC",B=t.type.value,R=wt("output",t.type.tensor,n);if(i.kernelShape.length<=2){let U="",Z="",se="",X=s-(u?2:1);if(k?U=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${X}] < 0 || xIndices[${X}] >= uniforms.x_shape[${X}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:U=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,i.kernelShape.length===2){let _e=s-(u?3:2);S?Z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${_e}] < 0 || xIndices[${_e}] >= uniforms.x_shape[${_e}]) { pad += i32(uniforms.kw); continue; } `:Z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; `,se=` } `}return` ${e.registerUniforms(p).declareVariables(t,R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var value = ${B}(${d}); var pad = 0; ${Z} ${U} ${se} ${o} output[global_idx] = value; }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let U=i.kernelShape.length,Z=i.pads.length,se="";return h?se=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:se=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(p).declareVariables(t,R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var offsets: array; var value = ${B}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${U-1}u; j++) { offsets[j] = offset / ${Mt("uniforms.kernelStrides","j",U)}; offset -= offsets[j] * ${Mt("uniforms.kernelStrides","j",U)}; } offsets[${U-1}] = offset; isPad = false; for (var j = ${s-U}u; j < ${s}u; j++) { xIndices[j] = indices[j] * ${Mt("uniforms.strides",`j - ${s-U}u`,U)} + offsets[j - ${s-U}u] - ${Mt("uniforms.pads","j - 2u",Z)}; ${se} } ${o} output[global_idx] = value; }`}},Ai=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,up=e=>`${Ai(e)};${e.countIncludePad}`,dp=e=>`${Ai(e)};${e.storageOrder};${e.dilations}`,ia=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}),oa=(e,t,s,n)=>{let[i,a]=zd(t,n,s),o=Be("x",t.dataType,t.dims.length),d=o.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[k,S,u,B,R]=ra(a,i);k.push(...vt(t.dims,a));let U=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:k}),getShaderSource:Z=>na(Z,o,t.dims.length,a.length,i,p,h,0,S,u,B,R)}},Bd=e=>{let t=e.count_include_pad!==0,s=ia(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:up(n)}},Rd=(e,t)=>{Cn(e.inputs),e.compute(oa("AveragePool",e.inputs[0],!1,t))},aa={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Nd=e=>{let t=e.format;return{format:t,...aa,cacheKey:t}},jd=(e,t)=>{Cn(e.inputs),e.compute(oa("GlobalAveragePool",e.inputs[0],!0,t))},la=(e,t,s,n)=>{let[i,a]=zd(t,n,s),o=` value = max(x_val, value); `,d="",p=Be("x",t.dataType,t.dims.length),h=["rank"],[k,S,u,B,R]=ra(a,i);return k.push(...vt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:k}),getShaderSource:U=>na(U,p,t.dims.length,a.length,i,o,d,t.dataType===10?-65504:-1e5,S,u,B,R)}},Wd=(e,t)=>{Cn(e.inputs),e.compute(la("MaxPool",e.inputs[0],!1,t))},Ud=e=>{let t=e.storage_order,s=e.dilations,n=ia(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:dp(i)}},Vd=e=>{let t=e.format;return{format:t,...aa,cacheKey:t}},Gd=(e,t)=>{Cn(e.inputs),e.compute(la("GlobalMaxPool",e.inputs[0],!0,t))}}),Kd,Hd,qd,Xd,cp=w(()=>{zt(),Bt(),Pt(),Qt(),Kd=(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)].")}},Hd=(e,t)=>{let s=Se.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,o=e[1].dataType,d=Se.size(a),p=n===3||n===2,h=p?[Math.ceil(Se.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,S=e.length>2?e[2]:void 0,u=S?p?[Math.ceil(Se.size(S.dims)/4)]:S.dims:void 0,B=k.length===0||k.length===1&&k[0]===1,R=B===!1&&k.length===1,U=ys(d),Z=B&&(!p||U===4),se=Z?U:1,X=Z&&!p?U:1,_e=Be("input",p?12:n,h.length,X),me=Be("scale",o,k.length),Me=S?Be("zero_point",p?12:n,u.length):void 0,$e=wt("output",o,a.length,se),Ae=[_e,me];Me&&Ae.push(Me);let Ge=[h,k];S&&Ge.push(u);let ut=[{type:12,data:d/se},{type:12,data:s},{type:12,data:t.blockSize},...vt(...Ge,a)],xt=Kt=>{let Yt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Kt.registerUniforms(Yt).declareVariables(...Ae,$e)} ${Kt.mainStart()} ${Kt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${$e.offsetToIndices("global_idx")}; // Set input x ${p?` let input = ${_e.getByOffset("global_idx / 4")}; let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${se===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${_e.getByOffset("global_idx")};`}; // Set scale input ${B?`let scale_value= ${me.getByOffset("0")}`:R?` let scale_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${me.getByOffset("scale_index")};`:` var scale_indices: ${me.type.indices} = output_indices; let index = ${me.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${me.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${me.getByIndices("scale_indices")};`}; // Set zero-point input ${Me?B?p?` let zero_point_input = ${Me.getByOffset("0")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Me.getByOffset("0")}`:R?p?` let zero_point_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${Me.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${Me.getByOffset("zero_point_index")};`:p?` let zero_point_offset = ${me.indicesToOffset("scale_indices")}; let zero_point_input = ${Me.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Me.getByIndices("scale_indices")};`:`let zero_point_value = ${p?i?"i32":"u32":_e.type.value}(0);`}; // Compute and write output ${$e.setByOffset("global_idx",`${$e.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:xt,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(d/se/64),y:1,z:1},programUniforms:ut})}},qd=(e,t)=>{Kd(e.inputs,t),e.compute(Hd(e.inputs,t))},Xd=e=>ot({axis:e.axis,blockSize:e.blockSize})}),Qd,pp,ua,hp=w(()=>{Qe(),zt(),Qt(),Qd=(e,t,s)=>{let n=e===t,i=et&&s>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},pp=(e,t,s,n)=>{let i=Math.abs(Math.ceil((t-e)/s)),a=[i],o=i,d=[{type:12,data:o},{type:n,data:e},{type:n,data:s},...vt(a)],p=h=>{let k=wt("output",n,a.length),S=k.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:S},{name:"delta",type:S}];return` ${h.registerUniforms(u).declareVariables(k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${S}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d})}},ua=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),T.webgpu.validateInputContent&&Qd(t,s,n),e.compute(pp(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Yd,Jd,Zd,ec,mp=w(()=>{zt(),Bt(),Pt(),Qt(),Yd=(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.`)}},Jd=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s,a=1,o=Math.ceil(Se.size(n)/a),d=n[n.length-1],p=Se.sizeFromDimension(s,d),h=[{type:12,data:o},{type:12,data:d},{type:12,data:p},...vt(e[1].dims,e[2].dims,i)],k=S=>{let u=Be("indices",e[1].dataType,e[1].dims.length),B=Be("updates",e[2].dataType,e[2].dims.length,a),R=t.reduction!=="none"&&t.reduction!==""?tr("output",e[0].dataType,i.length):wt("output",e[0].dataType,i.length,a);return` ${S.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(u,B,R)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var data_offset = 0u; let indices_start = uniforms.last_index_dimension * global_idx; let indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${e[0].dims.length===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[i - indices_start]; let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim)); } for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; ${Yd(t.reduction,"output[data_offset + i]","value",R.type.value)} } }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:h}),getShaderSource:k}},Zd=e=>ot({reduction:e.reduction}),ec=(e,t)=>{e.compute(Jd(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),tc,sc,rc,nc,ic,oc,ac,lc,uc,dc,cc,da,pc,hc,mc,_c,fc,gc,wc,_p=w(()=>{zt(),Bt(),Pt(),Qt(),tc=(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")}},sc=(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},rc=(e,t,s,n,i,a)=>{let[o,d,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(k=>a.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0){if(e[d].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&s>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");tc(n,t),t.axes.length>0&&sc(n,t.axes,h).forEach((k,S)=>n[S]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>i.push(Number(k))),i.length!==0&&i.length!==h&&s>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof i<"u"&&n.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},nc=(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`)}})()+"}",ic=(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`)}})()+"}",oc=(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},ac=(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},lc=(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},uc=(e,t,s,n,i)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { var original_indices: array<${e.type.value}, ${s.length}>; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Mt("uniforms.scales","i",n)}; var roi_low = ${Mt("uniforms.roi","i",i)}; var roi_hi = ${Mt("uniforms.roi",`i + ${t.length}`,i)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Mt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Mt("uniforms.output_shape","i",s.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,dc=(e,t,s,n,i,a,o)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Mt("uniforms.scales","i",i)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Mt("uniforms.roi","i",a)}; var roi_hi = ${Mt("uniforms.roi",`i + ${s.length}`,a)}; var input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; var output_shape_i = ${Mt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${o} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,cc=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Mt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,da=(e,t,s,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",s,"batch")}; `:"",pc=(e,t,s,n,i)=>{let[a,o,d,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(row, ${s[o]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(col, ${s[d]} - 1))`)}; ${da(e,p,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${o}]; var col:${h} = originalIndices[${d}]; ${n?`if (row < 0 || row > (${s[o]} - 1) || col < 0 || col > (${s[d]} - 1)) { return ${i}; }`:""}; row = max(0, min(row, ${s[o]} - 1)); col = max(0, min(col, ${s[d]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${s.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},hc=(e,t,s,n,i,a,o,d,p,h)=>{let k=s.length===2,[S,u]=k?[0,1]:[2,3],B=e.type.value,R=U=>{let Z=U===S?"row":"col";return` fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { var output_index = ${t.indicesGet("output_indices",U)}; var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[U]}, ${n[U]}, ${s[U]}, ${a[U]}, ${a[U]} + ${s.length}); var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${s[U]} - 1))) { return ${p}; } var data: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${Z}: ${B} = originalIdx + ${B}(i); if (${Z} < 0 || ${Z} >= ${s[U]}) { ${h?`coefs[i + 1] = 0.0; continue;`:d?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[U]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",U,`u32(${Z})`)}; data[i + 1] = ${U===S?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${R(S)}; ${R(u)}; fn getCubicInterpolationCoefs(s: ${B}) -> array<${B}, 4> { var absS = abs(s); var coeffs: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${B} = 1.0 - absS; var twoMinusAbsS: ${B} = 2.0 - absS; var onePlusAbsS: ${B} = 1.0 + absS; coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; return coeffs; } fn cubicInterpolation1D(x: array<${B}, 4>, coefs: array<${B}, 4>) -> ${B} { var coefsSum: ${B} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${B} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},mc=(e,t,s,n,i)=>{let[a,o,d,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(depth, ${s[o]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(height, ${s[d]} - 1))`)}; ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; ${da(e,h,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${k} = originalIndices[${o}]; var height:${k} = originalIndices[${d}]; var width:${k} = originalIndices[${p}]; ${n?`if (depth < 0 || depth > (${s[o]} - 1) || height < 0 || height > (${s[d]} - 1) || width < 0 || (width > ${s[p]} - 1)) { return ${i}; }`:""}; depth = max(0, min(depth, ${s[o]} - 1)); height = max(0, min(height, ${s[d]} - 1)); width = max(0, min(width, ${s[p]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; var batch: u32 = ${s.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${k} = abs(depth - ${k}(depth1)); var dx2: ${k} = abs(${k}(depth2) - depth); var dy1: ${k} = abs(height - ${k}(height1)); var dy2: ${k} = abs(${k}(height2) - height); var dz1: ${k} = abs(width - ${k}(width1)); var dz2: ${k} = abs(${k}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},_c=(e,t,s,n,i,a)=>{let o=e.dims,d=oc(a,t.axes,o.length),p=ac(o,n,i,t.axes),h=n.slice();n.length===0&&(h=o.map((X,_e)=>X===0?1:p[_e]/X),t.keepAspectRatioPolicy!=="stretch"&&(p=lc(o,h,t)));let k=wt("output",e.dataType,p.length),S=Be("input",e.dataType,o.length),u=Se.size(p),B=o.length===p.length&&o.every((X,_e)=>X===p[_e]),R=t.coordinateTransformMode==="tf_crop_and_resize",U=t.extrapolationValue,Z=S.type.value,se=X=>` ${B?"":` ${nc(t.coordinateTransformMode,Z)}; ${(()=>{switch(t.mode){case"nearest":return` ${cc(S,o)}; ${ic(t.nearestMode,s,Z)}; ${dc(S,k,o,p,h.length,d.length,R)}; `;case"linear":return` ${uc(k,o,p,h.length,d.length)}; ${(()=>{if(o.length===2||o.length===4)return`${pc(S,k,o,R,U)}`;if(o.length===3||o.length===5)return`${mc(S,k,o,R,U)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(o.length===2||o.length===4)return`${hc(S,k,o,p,h,d,t.cubicCoeffA,R,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${X.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(S,k)} ${X.mainStart()} ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${B?"output[global_idx] = input[global_idx];":` let output_indices = ${k.offsetToIndices("global_idx")}; var input_indices: ${S.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${S.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${o.length===2||o.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${h.length>0?h:""}|${i.length>0?i:""}|${d.length>0?d:""}|${B}|${o}`,inputDependencies:["rank"]},getShaderSource:se,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:h},{type:1,data:d},...vt(o,p)]})}},fc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},gc=(e,t)=>{let s=[],n=[],i=[],a=fc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");rc(e.inputs,t,a,s,n,i),e.compute(_c(e.inputs[0],t,a,s,n,i),{inputs:[0]})},wc=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,d=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return ot({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:d,mode:p,nearestMode:h})}}),yc,Mc,fp,Xt=w(()=>{zt(),Bt(),Pt(),Qt(),yc=(e,t)=>{let[s,n,i,a]=e,{numHeads:o,rotaryEmbeddingDim:d}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!Se.areEqual(n.dims,[])&&!Se.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Se.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=s.dims[0],h=s.dims[s.dims.length-2],k=i.dims[0],S=Se.sizeFromDimension(s.dims,1)/h,u=d===0?i.dims[1]*2:S/o;if(d>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(u/2!==i.dims[1]&&d/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Mc=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],d=Se.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=d/p,k=e[2].dims[1],S=i===0?k*2:h/n,u=new Array(o,p,h/S,S-k),B=Se.computeStrides(u),R=[{type:1,data:a},{type:12,data:u},{type:12,data:B},...e[0].dims.length===3?new Array({type:12,data:[d,h,S,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,S,p*S,1]}):[],...vt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],U=Z=>{let se=Be("input",e[0].dataType,e[0].dims.length),X=Be("position_ids",e[1].dataType,e[1].dims.length),_e=Be("cos_cache",e[2].dataType,e[2].dims.length),me=Be("sin_cache",e[3].dataType,e[3].dims.length),Me=wt("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:B.length},{name:"input_output_strides",type:"u32",length:B.length}]),` ${Z.declareVariables(se,X,_e,me,Me)} ${Z.mainStart(Ns)} let half_rotary_emb_dim = uniforms.${_e.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 = ${X.broadcastedIndicesToOffset("bsnh.xy",wt("",X.type.tensor,2))}; let position_id = u32(${X.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 = ${se.getByOffset("i")} * ${_e.get("position_id","bsnh[3]")} - ${se.getByOffset("j")} * ${me.get("position_id","bsnh[3]")}; ${Me.setByOffset("i","re")} let im = ${se.getByOffset("i")} * ${me.get("position_id","bsnh[3]")} + ${se.getByOffset("j")} * ${_e.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",se.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:ot({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:U,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(u)/Ns)},programUniforms:R})}},fp=(e,t)=>{yc(e.inputs,t),e.compute(Mc(e.inputs,t))}}),bc,js,Us,Zs=w(()=>{zt(),Bt(),Qt(),bc=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")}},js=(e,t,s,n)=>{let i=t.simplified,a=e[0].dims,o=Se.size(a),d=a,p=o,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],S=!i&&e.length>3,u=e.length>4,B=n&&s>1,R=n&&s>2,U=s>3,Z=64,se=ys(h),X=[{type:12,data:p},{type:12,data:se},{type:12,data:h},{type:1,data:t.epsilon}],_e=Me=>{let $e=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ae=[Be("x",e[0].dataType,e[0].dims,se),Be("skip",e[1].dataType,e[1].dims,se),Be("gamma",e[2].dataType,e[2].dims,se)];S&&Ae.push(Be("beta",e[3].dataType,e[3].dims,se)),u&&Ae.push(Be("bias",e[4].dataType,e[4].dims,se)),Ae.push(wt("output",e[0].dataType,d,se)),B&&Ae.push(wt("mean_output",1,k)),R&&Ae.push(wt("inv_std_output",1,k)),U&&Ae.push(wt("input_skip_bias_sum",e[0].dataType,d,se));let Ge=es(e[0].dataType),ut=es(1,se);return` ${Me.registerUniforms($e).declareVariables(...Ae)} var sum_shared : array<${ut}, ${Z}>; var sum_squared_shared : array<${ut}, ${Z}>; ${Me.mainStart([Z,1,1])} let ix = local_id.x; let iy = global_id.x / ${Z}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${Z}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${Z-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${u?"bias[offset1d + i]":Ge+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${U?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Ds(Ge,se,"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 = ${Hs("sum",se)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Hs("square_sum",se)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); ${B?"mean_output[global_idx] = mean;":""} ${R?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${i?"":`- ${Ge}(mean)`}) * ${Ge}(inv_std_dev) * gamma[offset1d + i] ${S?"+ beta[offset1d + i]":""}; } }`},me=[{dims:d,dataType:e[0].dataType}];return s>1&&me.push({dims:k,dataType:1}),s>2&&me.push({dims:k,dataType:1}),s>3&&me.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${se};${B};${R};${U}`,inputDependencies:e.map((Me,$e)=>"type")},getShaderSource:_e,getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:X})}},Us=(e,t)=>{bc(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(js(e.inputs,t,e.outputCount,!1),{outputs:s})}}),ln,Ii,vc,ca,_,x,N,ye,Oe=w(()=>{zt(),Bt(),Pt(),Qt(),ln=(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`)})},Ii=(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},vc=(e,t)=>{if(e.length>1){let s=Ii(e,1),n=Ii(e,2),i=Ii(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),ot({starts:s,ends:n,axes:i})}else return t},ca=(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]]))},_=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${s.length}; i >= 0; i--) { let input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; let steps_i = ${Mt("uniforms.steps","i",s.length)}; let signs_i = ${Mt("uniforms.signs","i",s.length)}; let starts_i = ${Mt("uniforms.starts","i",s.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,x=(e,t)=>{let s=e[0].dims,n=Se.size(s),i=t.axes.length>0?Se.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=Ii(e,4);a.forEach(se=>se!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((se,X)=>ca(se,X,s,i,a)),d=t.ends.map((se,X)=>ca(se,X,s,i,a));if(i.length!==o.length||i.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==s.length)for(let se=0;seMath.sign(se));a.forEach((se,X,_e)=>{if(se<0){let me=(d[X]-o[X])/se,Me=o[X],$e=Me+me*a[X];o[X]=$e,d[X]=Me,_e[X]=-se}});let h=s.slice(0);i.forEach((se,X)=>{h[se]=Math.ceil((d[se]-o[se])/a[se])});let k={dims:h,dataType:e[0].dataType},S=wt("output",e[0].dataType,h.length),u=Be("input",e[0].dataType,e[0].dims.length),B=Se.size(h),R=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],U=[{type:12,data:B},{type:12,data:o},{type:6,data:p},{type:12,data:a},...vt(e[0].dims,h)],Z=se=>` ${se.registerUniforms(R).declareVariables(u,S)} ${_(u,S,s)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${S.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${S.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${o.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:U})}},N=(e,t)=>{ln(e.inputs,t);let s=vc(e.inputs,t);e.compute(x(e.inputs,s),{inputs:[0]})},ye=e=>{let t=e.starts,s=e.ends,n=e.axes;return ot({starts:t,ends:s,axes:n})}}),ke,Ye,tt,_t,Tt=w(()=>{zt(),Bt(),Pt(),Vr(),Qt(),ke=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ye=(e,t)=>{let s=e.inputs[0],n=s.dims,i=Se.size(n),a=n.length,o=Se.normalizeAxis(t.axis,a),d=oGe),h[o]=a-1,h[a-1]=o,p=e.compute(sr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,S=k[a-1],u=i/S,B=ys(S),R=S/B,U=64;u===1&&(U=256);let Z=(Ae,Ge)=>Ge===4?`max(max(${Ae}.x, ${Ae}.y), max(${Ae}.z, ${Ae}.w))`:Ge===2?`max(${Ae}.x, ${Ae}.y)`:Ge===3?`max(max(${Ae}.x, ${Ae}.y), ${Ae}.z)`:Ae,se=Be("x",p.dataType,p.dims,B),X=wt("result",p.dataType,p.dims,B),_e=se.type.value,me=es(p.dataType)==="f32"?`var threadMax = ${_e}(-3.402823e+38f);`:`var threadMax = ${_e}(-65504.0h);`,Me=Ae=>` var rowMaxShared : ${_e}; var rowSumShared : ${_e}; var threadShared : array<${_e}, ${U}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${_e} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${_e}) { let index = row * row_stride + col; result[index] = value; } ${Ae.registerUniform("packedCols","i32").declareVariables(se,X)} ${Ae.mainStart(U)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${U}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${me} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${_e}(${Z("threadShared[0]",B)}); } workgroupBarrier(); // find the rows sum var threadSum = ${_e}(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 = ${_e}(${Hs("threadShared[0]",B)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`,$e=e.compute({name:"Softmax",shaderCache:{hint:`${B};${U}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:R}]}),getShaderSource:Me},{inputs:[p],outputs:[d?-1:0]})[0];d&&e.compute(sr($e,h),{inputs:[$e]})},tt=(e,t)=>{ke(e.inputs),Ye(e,t)},_t=e=>ot({axis:e.axis})}),Lt,Wt,Dt,Vt,Zt,rs=w(()=>{zt(),Bt(),Qt(),Lt=e=>Array.from(e.getBigInt64Array(),Number),Wt=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(Lt(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")},Dt=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Lt(e[1]),i=Dt(s,n),a=Se.size(i),o=e[0].dataType,d=Be("input",o,s.length),p=wt("output",o,i.length),h=k=>` const inputShape = ${d.indices(...s)}; ${k.registerUniform("output_size","u32").declareVariables(d,p)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${d.type.indices}; for (var i = 0; i < ${s.length}; i++) { let input_dim_i = ${d.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; ${d.indicesSet("input_indices","i","input_dim_value")} } ${p.setByOffset("global_idx",d.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...vt(e[0].dims,i)]}),getShaderSource:h}},Zt=e=>{Wt(e.inputs),e.compute(Vt(e.inputs),{inputs:[0]})}}),qt,is,Cs,Es=w(()=>{zt(),Bt(),Qt(),qt=(e,t,s,n,i)=>{let a=wt("output_data",i,s.length,4),o=Be("a_data",t[1].dataType,t[1].dims.length,4),d=Be("b_data",t[2].dataType,t[2].dims.length,4),p=Be("c_data",t[0].dataType,t[0].dims.length,4),h,k=(S,u,B)=>`select(${u}, ${S}, ${B})`;if(!n)h=a.setByOffset("global_idx",k(o.getByOffset("global_idx"),d.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let S=(u,B,R="")=>{let U=`a_data[index_a${B}][component_a${B}]`,Z=`b_data[index_b${B}][component_b${B}]`,se=`bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`;return` let output_indices${B} = ${a.offsetToIndices(`global_idx * 4u + ${B}u`)}; let offset_a${B} = ${o.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let offset_b${B} = ${d.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let index_a${B} = offset_a${B} / 4u; let index_b${B} = offset_b${B} / 4u; let index_c${B} = offset_c${B} / 4u; let component_a${B} = offset_a${B} % 4u; let component_b${B} = offset_b${B} % 4u; let component_c${B} = offset_c${B} % 4u; ${u}[${B}] = ${R}(${k(U,Z,se)}); `};i===9?h=` var data = vec4(0); ${S("data",0,"u32")} ${S("data",1,"u32")} ${S("data",2,"u32")} ${S("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` ${S("output_data[global_idx]",0)} ${S("output_data[global_idx]",1)} ${S("output_data[global_idx]",2)} ${S("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(p,o,d,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`},is=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(Se.areEqual(t,s)&&Se.areEqual(s,n)),o=t,d=Se.size(t);if(a){let h=ss.calcShape(ss.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");o=h,d=Se.size(o)}let p=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>qt(h,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:p},...vt(n,t,s,o)]})}},Cs=e=>{e.compute(is(e.inputs))}}),ds,ks=w(()=>{Za(),di(),zc(),dl(),Bc(),Ql(),Rc(),Uc(),Eu(),Gc(),Ou(),Kc(),Hc(),qc(),Xc(),Yc(),Jc(),zp(),Zc(),pd(),bd(),sp(),rp(),np(),ip(),Ko(),Ld(),Bp(),cp(),hp(),mp(),to(),_p(),Xt(),Zs(),Oe(),Tt(),wd(),rs(),Vr(),To(),Es(),ds=new Map([["Abs",[lo]],["Acos",[pl]],["Acosh",[hl]],["Add",[Wl]],["ArgMax",[Ja,no]],["ArgMin",[ro,no]],["Asin",[uo]],["Asinh",[ml]],["Atan",[_l]],["Atanh",[co]],["Attention",[nl]],["AveragePool",[Rd,Bd]],["BatchNormalization",[al]],["BiasAdd",[ul]],["BiasSplitGelu",[Rl]],["Cast",[gl,fl]],["Ceil",[yl]],["Clip",[wl]],["Concat",[eu,ko]],["Conv",[zo,vi]],["ConvTranspose",[xu,bu]],["Cos",[ho]],["Cosh",[Ml]],["CumSum",[Cu,Ro]],["DepthToSpace",[Au,Iu]],["DequantizeLinear",[qd,Xd]],["Div",[Ul]],["Einsum",[Bu,jo]],["Elu",[bl,Rn]],["Equal",[Vl]],["Erf",[mo]],["Exp",[vl]],["Expand",[ju]],["FastGelu",[Wn]],["Floor",[Tl]],["FusedConv",[zo,vi]],["Gather",[ki,Gu]],["GatherElements",[Si,Zu]],["GatherBlockQuantized",[Pn,Qu]],["GatherND",[Hu,Qc]],["Gelu",[_o]],["Gemm",[rd,sd]],["GlobalAveragePool",[jd,Nd]],["GlobalMaxPool",[Gd,Vd]],["Greater",[Hl]],["GreaterOrEqual",[ql]],["GridSample",[dd,cd]],["GroupQueryAttention",[Md]],["HardSigmoid",[Sl,kl]],["InstanceNormalization",[Td]],["LayerNormalization",[Pd]],["LeakyRelu",[xl,Rn]],["Less",[Po]],["LessOrEqual",[Xl]],["Log",[Dl]],["MatMul",[kd]],["MatMulNBits",[ta,Ad]],["MaxPool",[Wd,Ud]],["Mul",[Gl]],["MultiHeadAttention",[md,hd]],["Neg",[fo]],["Not",[El]],["Pad",[Dd]],["Pow",[Eo]],["QuickGelu",[zl,Rn]],["Range",[ua]],["Reciprocal",[Pl]],["ReduceMin",[Xa]],["ReduceMean",[Yi]],["ReduceMax",[qa]],["ReduceSum",[Qa]],["ReduceProd",[Zi]],["ReduceL1",[Ka]],["ReduceL2",[Ha]],["ReduceLogSum",[eo]],["ReduceLogSumExp",[Ji]],["ReduceSumSquare",[Ya]],["Relu",[Cl]],["Resize",[gc,wc]],["RotaryEmbedding",[fp]],["ScatterND",[ec,Zd]],["Sigmoid",[go]],["Sin",[wo]],["Sinh",[$l]],["Slice",[N,ye]],["SkipLayerNormalization",[Us]],["Split",[qo,Xo]],["Sqrt",[Al]],["Softmax",[tt,_t]],["Sub",[Kl]],["Tan",[yo]],["Tanh",[Il]],["ThresholdedRelu",[Fl,Rn]],["Tile",[Zt]],["Transpose",[Ui,Pa]],["Where",[Cs]]])}),$s,qs=w(()=>{Qe(),Qs(),Qt(),$s=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,n,i){Ve(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let h of t)d.push({binding:d.length,resource:{buffer:h.buffer}});for(let h of s)d.push({binding:d.length,resource:{buffer:h.buffer}});i&&d.push({binding:d.length,resource:i});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}o.setPipeline(e.computePipeline),o.setBindGroup(0,p),o.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ne(e.programInfo.name)}dispose(){}build(e,t){Ve(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let i=Tn(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${n.join(` `)} ${i.additionalImplementations} ${a}`,d=s.createShaderModule({code:o,label:e.name});os("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let p=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ne(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&s<=i&&n<=i)return[t,s,n];let a=t*s*n,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),Ws,wr,kn,pa,rr,Fr=w(()=>{Qe(),zt(),Qs(),Bn(),yt(),ks(),qs(),Ws=(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+`:${Ws(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},kn=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},pa=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]}},rr=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 pa(this.device),this.adapterInfo=new kn(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ct(this),this.programManager=new $s(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,yn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ve(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=B);let U=Number(B-this.queryTimeBase),Z=Number(R-this.queryTimeBase);if(!Number.isSafeInteger(U)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:S.map(se=>({dims:se.dims,dataType:xr(se.dataType)})),outputsMetadata:u.map(se=>({dims:se.dims,dataType:xr(se.dataType)})),kernelId:o,kernelType:p,kernelName:h,programName:k,startTime:U,endTime:Z});else{let se="";S.forEach((_e,me)=>{se+=`input[${me}]: [${_e.dims}] | ${xr(_e.dataType)}, `});let X="";u.forEach((_e,me)=>{X+=`output[${me}]: [${_e.dims}] | ${xr(_e.dataType)}, `}),console.log(`[profiling] kernel "${o}|${p}|${h}|${k}" ${se}${X}execution time: ${Z-U} ns`)}Re("GPU",`${k}::${B}::${R}`)}e.unmap(),this.pendingQueries.delete(e)}),Ne()}run(e,t,s,n,i,a){Ve(e.name);let o=[];for(let X=0;X_e):s;if(k.length!==d.length)throw new Error(`Output size ${k.length} must be equal to ${d.length}.`);let S=[],u=[];for(let X=0;X=a)throw new Error(`Invalid output index: ${k[X]}`);if(k[X]===-3)continue;let _e=k[X]===-1,me=k[X]===-2,Me=_e||me?i(d[X].dataType,d[X].dims):n(k[X],d[X].dataType,d[X].dims);if(S.push(Me),Me.data===0)continue;let $e=this.gpuDataManager.get(Me.data);if(!$e)throw new Error(`no GPU data for output: ${Me.data}`);if(_e&&this.temporaryData.push($e),me){let Ae=this.kernelPersistentData.get(this.currentKernelId);Ae||(Ae=[],this.kernelPersistentData.set(this.currentKernelId,Ae)),Ae.push($e)}u.push($e)}if(o.length!==t.length||u.length!==S.length){if(u.length===0)return Ne(e.name),S;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let B;if(h){let X=0,_e=[];h.forEach(Ae=>{let Ge=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ge.length===0)return;let ut=Ae.type===10?2:4,xt,Kt;Ae.type===10?(Kt=Ge.length>4?16:Ge.length>2?8:Ge.length*ut,xt=Ge.length>4?16:ut*Ge.length):(Kt=Ge.length<=2?Ge.length*ut:16,xt=16),X=Math.ceil(X/Kt)*Kt,_e.push(X);let Yt=Ae.type===10?8:4;X+=Ge.length>4?Math.ceil(Ge.length/Yt)*xt:Ge.length*ut});let me=16;X=Math.ceil(X/me)*me;let Me=new ArrayBuffer(X);h.forEach((Ae,Ge)=>{let ut=_e[Ge],xt=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ae.type===6)new Int32Array(Me,ut,xt.length).set(xt);else if(Ae.type===12)new Uint32Array(Me,ut,xt.length).set(xt);else if(Ae.type===10)new Uint16Array(Me,ut,xt.length).set(xt);else if(Ae.type===1)new Float32Array(Me,ut,xt.length).set(xt);else throw new Error(`Unsupported uniform type: ${xr(Ae.type)}`)});let $e=this.gpuDataManager.create(X,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer($e.buffer,0,Me,0,X),this.gpuDataManager.release($e.id),B={offset:0,size:X,buffer:$e.buffer}}let R=this.programManager.normalizeDispatchGroupSize(p),U=R[1]===1&&R[2]===1,Z=wr(e,t,U),se=this.programManager.getArtifact(Z);if(se||(se=this.programManager.build(e,R),this.programManager.setArtifact(Z,se),os("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&se.uniformVariablesInfo){if(h.length!==se.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${se.uniformVariablesInfo.length}, got ${h.length} in program "${se.programInfo.name}".`);for(let X=0;X`[ProgramManager] run "${e.name}" (key=${Z}) with ${R[0]}x${R[1]}x${R[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let X={kernelId:this.currentKernelId,programName:se.programInfo.name,inputTensorViews:t,outputTensorViews:S};this.pendingKernels.push(X),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(X)}return this.programManager.run(se,o,u,R,B),Ne(e.name),S}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let i=ds.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],s]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,a=n.kernelName,o=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),os("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),o(t,d[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${i}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(s,n,a);return i.set(t,[o,s]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await Ce(this,e,t);return Mn(n.buffer,s)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){os("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(){os("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){os("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()}}}),ha,Vn,Oi,Gn,Ts,Is,qr,un,Kn=w(()=>{Qs(),ha=1,Vn=()=>ha++,Oi=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Gn=(e,t)=>{let s=Oi.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},Ts=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 Gn(this.dataType,this.tensorShape)}destroy(){os("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}},Is=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Gn(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else os("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()}},qr=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Vn();return this.tensorTrackersById.set(e,new Is(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){os("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){os("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=Vn(),a=new Ts({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(i,new Is(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,s,n,i){let a=this.backend.currentSessionId;for(let[p,h]of this.freeTensors.entries())if(h.sameTypeAndShape(e,t)){os("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}let o=this.backend.currentContext;os("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let d=await o.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:i});return new Ts({sessionId:a,context:o,tensor:d,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},un=(...e)=>new qr(...e)}),Hn,ma,_a,Tc=w(()=>{zt(),Ot(),Bn(),Kn(),Qs(),Hn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),ma=(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])},_a=class{constructor(e){this.tensorManager=un(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],yn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>ma(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){os("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let i=Hn.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,s,n)}uploadTensor(e,t){if(!gt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");os("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return Mn(s,t)}}registerMLTensor(e,t,s){let n=Hn.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,s);return os("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,s,n,i,a){if(!a)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let d=a.get(o);if(!d)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+s>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=d.slice(t,t+s).buffer,h;switch(i.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return os("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,h)}flush(){}}}),gp={};v(gp,{init:()=>fa});var qn,Fi,fa,wp=w(()=>{zt(),Fr(),Qs(),Bt(),Tc(),qn=class Ym{constructor(t,s,n,i){this.module=t,this.dataType=s,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Se.size(t)!==Se.size(this.dims))throw new Error("Invalid new shape");return new Ym(this.module,this.dataType,this.data,t)}},Fi=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,i=s/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*i++,a));let o=Number(e.getValue(n*i++,a));this.outputCount=Number(e.getValue(n*i++,a)),this.customDataOffset=Number(e.getValue(n*i++,"*")),this.customDataSize=Number(e.getValue(n*i++,a));let d=[];for(let p=0;ptypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(d,p,h)=>new qn(this.module,p,this.output(d,h),h),a=(d,p)=>{let h=lr(d,p);if(!h)throw new Error(`Unsupported data type: ${d}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new qn(this.module,d,k,p)};return this.backend.run(e,s,n,i,a,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,i=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,i);for(let o=0;o{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new rr;await a.initialize(s,n),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,d,p,h=!1)=>{if(h)os("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(d)}, size=${Number(p)}`),a.memcpy(Number(o),Number(d));else{os("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(d)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(p));a.upload(Number(d),k)}},async(o,d,p)=>{os("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${d}, size=${p}`),await a.download(Number(o),()=>t.HEAPU8.subarray(Number(d)>>>0,Number(d+p)>>>0))},(o,d,p)=>a.createKernel(o,Number(d),p,t.UTF8ToString(t._JsepGetNodeName(Number(d)))),o=>a.releaseKernel(o),(o,d,p,h)=>{os("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${o}, contextDataOffset=${d}`);let k=new Fi(t,a,Number(d));return a.computeKernel(Number(o),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new _a(s);i("webnn",[a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,d,p,h)=>a.ensureTensor(o,d,p,h),(o,d)=>{a.uploadTensor(o,d)},async(o,d)=>a.downloadTensor(o,d)])}}}),ga,Xn,xc,dn,yp,Dr,cr,Rp,Np,jp,Wp,Up,gh=w(()=>{Zr(),ni(),zt(),Ot(),er(),On(),ga=(e,t)=>{gt()._OrtInit(e,t)!==0&&ts("Can't initialize onnxruntime.")},Xn=async e=>{ga(e.wasm.numThreads,en(e.logLevel))},xc=async(e,t)=>{{let s=(wp(),M(gp)).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",gt(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",gt(),e)}}},dn=new Map,yp=e=>{let t=gt(),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=gt(),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]},cr=async(e,t)=>{var S,u,B;let s,n,i=gt();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,d=0,p=[],h=[],k=[];try{if([o,p]=In(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let Me=[];for(let $e of t.externalData){let Ae=typeof $e=="string"?$e:$e.path;Me.push(wn(typeof $e=="string"?$e:$e.data).then(Ge=>{i.mountExternalData(Ae,Ge)}))}await Promise.all(Me)}for(let Me of(t==null?void 0:t.executionProviders)??[])if((typeof Me=="string"?Me:Me.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof Me!="string"){let $e=Me,Ae=$e==null?void 0:$e.context,Ge=$e==null?void 0:$e.gpuDevice,ut=$e==null?void 0:$e.deviceType,xt=$e==null?void 0:$e.powerPreference;Ae?i.currentContext=Ae:Ge?i.currentContext=await i.jsepCreateMLContext(Ge):i.currentContext=await i.jsepCreateMLContext({deviceType:ut,powerPreference:xt})}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(s,n,o),a===0&&ts("Can't create a session."),(S=i.jsepOnCreateSession)==null||S.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[R,U]=yp(a),Z=!!(t!=null&&t.enableGraphCapture),se=[],X=[],_e=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(d=i._OrtCreateBinding(a),d===0&&ts("Can't create IO binding."),me={handle:d,outputPreferredLocations:_e,outputPreferredLocationsEncoded:_e.map(Me=>Er(Me))}),dn.set(a,[a,h,k,me,Z,!1]),[a,se,X]}catch(R){throw h.forEach(U=>i._OrtFree(U)),k.forEach(U=>i._OrtFree(U)),d!==0&&i._OrtReleaseBinding(d)!==0&&ts("Can't release IO binding."),a!==0&&i._OrtReleaseSession(a)!==0&&ts("Can't release session."),R}finally{i._free(s),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ts("Can't release session options."),p.forEach(R=>i._free(R)),(B=i.unmountExternalData)==null||B.call(i)}},Rp=e=>{var p;let t=gt(),s=dn.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,o,d]=s;o&&(d&&t._OrtClearBoundOutputs(o.handle)!==0&&ts("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ts("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),i.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&ts("Can't release session."),dn.delete(e)},Np=(e,t,s,n,i,a=!1)=>{if(!e){t.push(0);return}let o=gt(),d=o.PTR_SIZE,p=e[0],h=e[1],k=e[3],S,u;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let U=e[2].gpuBuffer;u=lr(Wr(p),h);let Z=o.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');S=Z(n,i,U,u)}else if(k==="ml-tensor"){let U=e[2].mlTensor;u=lr(Wr(p),h);let Z=o.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');S=Z(U,Wr(p),h)}else{let U=e[2];if(Array.isArray(U)){u=d*U.length,S=o._malloc(u),s.push(S);for(let Z=0;Zo.setValue(R+se*d,Z,d===4?"i32":"i64"));let U=o._OrtCreateTensor(Wr(p),S,u,R,h.length,Er(k));U===0&&ts(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(U)}finally{o.stackRestore(B)}},jp=async(e,t,s,n,i,a)=>{var Kt,Yt;let o=gt(),d=o.PTR_SIZE,p=dn.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],S=p[2],u=p[3],B=p[4],R=p[5],U=t.length,Z=n.length,se=0,X=[],_e=[],me=[],Me=[],$e=o.stackSave(),Ae=o.stackAlloc(U*d),Ge=o.stackAlloc(U*d),ut=o.stackAlloc(Z*d),xt=o.stackAlloc(Z*d);try{(Kt=o.jsepOnRunStart)==null||Kt.call(o,h),[se,X]=Rr(a);for(let $t=0;$tOs*xs,1);Ps=xr(cs);let zi=u==null?void 0:u.outputPreferredLocations[n[$t]];if(Ps==="string"){if(zi==="gpu-buffer"||zi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Os=[];for(let xs=0;xs0){let Os=o.jsepGetBuffer;if(!Os)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xs=Os(it),Yn=lr(cs,cn);if(Yn===void 0||!gn(Ps))throw new Error(`Unsupported data type: ${Ps}`);Gt=!0,Jt.push([Ps,Ks,{gpuBuffer:xs,download:o.jsepCreateDownloader(xs,Yn,Ps),dispose:()=>{o._OrtReleaseTensor(jt)!==0&&ts("Can't release tensor.")}},"gpu-buffer"])}else if(zi==="ml-tensor"&&cn>0){let Os=o.jsepEnsureTensor;if(!Os)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(lr(cs,cn)===void 0||!tn(Ps))throw new Error(`Unsupported data type: ${Ps}`);let xs=await Os(it,cs,Ks,!1);Gt=!0,Jt.push([Ps,Ks,{mlTensor:xs,download:o.jsepCreateMLTensorDownloader(it,Ps),dispose:()=>{o.jsepReleaseTensorId(it),o._OrtReleaseTensor(jt)}},"ml-tensor"])}else{let Os=fn(Ps),xs=new Os(cn);new Uint8Array(xs.buffer,xs.byteOffset,xs.byteLength).set(o.HEAPU8.subarray(it,it+xs.byteLength)),Jt.push([Ps,Ks,xs,"cpu"])}}finally{o.stackRestore(vs),Ps==="string"&&it&&o._free(it),Gt||o._OrtReleaseTensor(jt)}}return u&&!B&&(o._OrtClearBoundOutputs(u.handle)!==0&&ts("Can't clear bound outputs."),dn.set(e,[h,k,S,u,B,!1])),Jt}finally{o.stackRestore($e),_e.forEach(Ct=>o._OrtReleaseTensor(Ct)),me.forEach(Ct=>o._OrtReleaseTensor(Ct)),Me.forEach(Ct=>o._free(Ct)),se!==0&&o._OrtReleaseRunOptions(se),X.forEach(Ct=>o._free(Ct))}},Wp=e=>{let t=gt(),s=dn.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)},Up=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,yr,wa,Ec,Pc,Mp,Vp,bp,Di,Li,wh,yh,Mh,bh,vh,Th,xh,Eh,Ph=w(()=>{Qe(),gh(),Ot(),Sr(),Qn=()=>!!T.wasm.proxy&&typeof document<"u",wa=!1,Ec=!1,Pc=!1,bp=new Map,Di=(e,t)=>{let s=bp.get(e);s?s.push(t):bp.set(e,[t])},Li=()=>{if(wa||!Ec||Pc||!yr)throw new Error("worker not ready")},wh=e=>{switch(e.data.type){case"init-wasm":wa=!1,e.data.err?(Pc=!0,Vp[1](e.data.err)):(Ec=!0,Vp[0]()),Mp&&(URL.revokeObjectURL(Mp),Mp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=bp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},yh=async()=>{if(!Ec){if(wa)throw new Error("multiple calls to 'initWasm()' detected.");if(Pc)throw new Error("previous call to 'initWasm()' failed.");if(wa=!0,Qn())return new Promise((e,t)=>{yr==null||yr.terminate(),Yr().then(([s,n])=>{try{yr=n,yr.onerror=a=>t(a),yr.onmessage=wh,Vp=[e,t];let i={type:"init-wasm",in:T};yr.postMessage(i),Mp=s}catch(i){t(i)}},t)});try{await nt(T.wasm),await Xn(T),Ec=!0}catch(e){throw Pc=!0,e}finally{wa=!1}}},Mh=async e=>{if(Qn())return Li(),new Promise((t,s)=>{Di("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:T}};yr.postMessage(n)});await xc(T,e)},bh=async e=>Qn()?(Li(),new Promise((t,s)=>{Di("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};yr.postMessage(n,[e.buffer])})):Dr(e),vh=async(e,t)=>{if(Qn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Li(),new Promise((s,n)=>{Di("create",[s,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),yr.postMessage(i,a)})}else return cr(e,t)},Th=async e=>{if(Qn())return Li(),new Promise((t,s)=>{Di("release",[t,s]);let n={type:"release",in:e};yr.postMessage(n)});Rp(e)},xh=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 Li(),new Promise((o,d)=>{Di("run",[o,d]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};yr.postMessage(h,Up(p))})}else return jp(e,t,s,n,i,a)},Eh=async e=>{if(Qn())return Li(),new Promise((t,s)=>{Di("end-profiling",[t,s]);let n={type:"end-profiling",in:e};yr.postMessage(n)});Wp(e)}}),Gp,Ch,kh,i_=w(()=>{Qe(),Ph(),zt(),rt(),On(),Gp=(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()}`)}},Ch=e=>{switch(e[3]){case"cpu":return new pe(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!gn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:i}=e[2];return pe.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!tn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:i}=e[2];return pe.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},kh=class{async fetchModelAndCopyToWasmMemory(e){return bh(await wn(e))}async loadModel(e,t){Ve();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await vh(s,t),Ne()}async dispose(){return Th(this.sessionId)}async run(e,t,s){Ve();let n=[],i=[];Object.entries(e).forEach(S=>{let u=S[0],B=S[1],R=this.inputNames.indexOf(u);if(R===-1)throw new Error(`invalid input '${u}'`);n.push(B),i.push(R)});let a=[],o=[];Object.entries(t).forEach(S=>{let u=S[0],B=S[1],R=this.outputNames.indexOf(u);if(R===-1)throw new Error(`invalid output '${u}'`);a.push(B),o.push(R)});let d=n.map((S,u)=>Gp(S,()=>`input "${this.inputNames[i[u]]}"`)),p=a.map((S,u)=>S?Gp(S,()=>`output "${this.outputNames[o[u]]}"`):null),h=await xh(this.sessionId,i,d,o,p,s),k={};for(let S=0;SHp,initializeFlags:()=>Kp,wasmBackend:()=>$h});var Kp,Hp,$h,o_=w(()=>{Qe(),Ph(),i_(),Sr(),Kp=()=>{if((typeof T.wasm.initTimeout!="number"||T.wasm.initTimeout<0)&&(T.wasm.initTimeout=0),T.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof T.wasm.proxy!="boolean"&&(T.wasm.proxy=!1),typeof T.wasm.trace!="boolean"&&(T.wasm.trace=!1),typeof T.wasm.numThreads!="number"||!Number.isInteger(T.wasm.numThreads)||T.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)T.wasm.numThreads=1;else{let e=typeof navigator>"u"?W("node:os").cpus().length:navigator.hardwareConcurrency;T.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Hp=class{async init(e){Kp(),await yh(),await Mh(e)}async createInferenceSessionHandler(e,t){let s=new kh;return await s.loadModel(e,t),Promise.resolve(s)}},$h=new Hp});Qe(),Qe(),Qe();var a_="1.21.0-dev.20241205-d27fecd3d3",l_=Ie;{let e=(o_(),M(Sh)).wasmBackend;H("webgpu",e,5),H("webnn",e,5),H("cpu",e,10),H("wasm",e,10)}Object.defineProperty(T.versions,"web",{value:a_,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":(De,A,r)=>{var f;r.r(A),r.d(A,{Tensor:()=>W.Tensor,createInferenceSession:()=>ie,deviceToExecutionProviders:()=>H,isONNXProxy:()=>Q,isONNXTensor:()=>z});var L=r("./src/env.js"),j=r("?2ce3"),J=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"),W=r("./node_modules/onnxruntime-common/dist/esm/index.js");const w=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"}}),v=[];let y,M;const b=Symbol.for("onnxruntime");if(b in globalThis)M=globalThis[b];else if(L.apis.IS_NODE_ENV){switch(M=j??(f||(f=r.t(j,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),y=["cpu"]}else M=J,L.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),L.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),y=["wasm"];const D=M.InferenceSession;function H(F=null){if(!F)return y;switch(F){case"auto":return v;case"gpu":return v.filter($=>["webgpu","cuda","dml","webnn-gpu"].includes($))}if(v.includes(F))return[w[F]??F];throw new Error(`Unsupported device: "${F}". Should be one of: ${v.join(", ")}.`)}let re=null;async function ie(F,$,g){re&&await re;const C=D.create(F,$);re??(re=C);const T=await C;return T.config=g,T}function z(F){return F instanceof M.Tensor}const V=M==null?void 0:M.env;V!=null&&V.wasm&&(V.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${L.env.version}/dist/`,V.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(V.wasm.numThreads=1)),V!=null&&V.webgpu&&(V.webgpu.powerPreference="high-performance");function Q(){var F;return(F=V==null?void 0:V.wasm)==null?void 0:F.proxy}L.env.backends.onnx=V},"./src/base/feature_extraction_utils.js":(De,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>J,validate_audio_inputs:()=>W});var f=r("./src/utils/constants.js"),L=r("./src/utils/generic.js"),j=r("./src/utils/hub.js");class J extends L.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,y){const M=await(0,j.getModelJSON)(v,f.FEATURE_EXTRACTOR_NAME,!0,y);return new this(M)}}function W(w,v){var y;if(!(w instanceof Float32Array||w instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((y=w==null?void 0:w.constructor)==null?void 0:y.name)??typeof w} 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":(De,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>F,post_process_instance_segmentation:()=>Q,post_process_object_detection:()=>b,post_process_panoptic_segmentation:()=>V,post_process_semantic_segmentation:()=>D});var f=r("./src/utils/generic.js"),L=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");r("./src/utils/image.js");var J=r("./src/utils/core.js"),W=r("./src/utils/hub.js"),w=r("./src/utils/constants.js");function v($,g,C=0,T=null){const ee=$/g;let Y=(0,j.bankers_round)(ee)*g;return T!==null&&Y>T&&(Y=Math.floor(ee)*g),Yg&&he.push(ze)}else{let ze=(0,j.max)(te.data)[1];if(ze===fe-1||(Te=(0,j.softmax)(te.data),Te[ze]Xe*Le[(oe+1)%2])),qe.boxes.push(et),qe.classes.push(ze),qe.scores.push(Te[ze])}}Pe.push(qe)}return Pe}function D($,g=null){const C=$.logits,T=C.dims[0];if(g!==null&&g.length!==T)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ee=[];for(let Y=0;YLe[he]&&(Le[he]=te[he],qe[he]=ue)}const je=new Array(de.dims[0]);for(let ue=0;ueue!==void 0);ee.push({segmentation:xe,labels:dt})}return ee}function H($,g,C,T){const ee=[],Y=[],le=[];for(let de=0;de<$.dims[0];++de){const fe=$[de],Pe=g[de],xe=(0,j.max)(fe.data)[1];if(xe===T)continue;const qe=(0,j.softmax)(fe.data)[xe];qe>C&&(ee.push(Pe),Y.push(qe),le.push(xe))}return[ee,Y,le]}function re($,g,C,T=.5,ee=.8){const Y=[];let le=0,de=0;const fe=g[C].data;for(let xe=0;xe<$.length;++xe)$[xe]===C&&(Y.push(xe),++le),fe[xe]>=T&&++de;let Pe=le>0&&de>0;return Pe&&(Pe=le/de>ee),[Pe,Y]}function ie($,g,C,T,ee,Y=null,le=null){const[de,fe]=le??$[0].dims,Pe=new L.Tensor("int32",new Int32Array(de*fe),[de,fe]),xe=[];if(le!==null)for(let ue=0;ue<$.length;++ue)$[ue]=(0,L.interpolate)($[ue],le,"bilinear",!1);const Le=new Int32Array($[0].data.length),qe=new Float32Array($[0].data.length);for(let ue=0;ue<$.length;++ue){let te=g[ue];const he=$[ue].data;for(let Te=0;Teqe[Te]&&(Le[Te]=ue,qe[Te]=he[Te])}let je=0;const dt=Pe.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max($,g)/Math.min($,g)}`);let Y=Math.round($/C)*C,le=Math.round(g/C)*C;if(Y*le>ee){const de=Math.sqrt($*g/ee);Y=Math.floor($/de/C)*C,le=Math.floor(g/de/C)*C}else if(Y*leY?Pe=Math.floor(Y*fe/ee):Y>ee&&(fe=Math.floor(ee*Pe/Y)),await g.resize(Pe,fe,{resample:T}))}async crop_margin(g,C=200){const T=g.clone().grayscale(),ee=(0,j.min)(T.data)[0],le=(0,j.max)(T.data)[0]-ee;if(le===0)return g;const de=C/255;let fe=T.width,Pe=T.height,xe=0,Le=0;const qe=T.data;for(let je=0;jethis.preprocess(Y)));return{pixel_values:(0,L.stack)(T.map(Y=>Y.pixel_values),0),original_sizes:T.map(Y=>Y.original_size),reshaped_input_sizes:T.map(Y=>Y.reshaped_input_size)}}static async from_pretrained(g,C){const T=await(0,W.getModelJSON)(g,w.IMAGE_PROCESSOR_NAME,!0,C);return new this(T)}}},"./src/base/processing_utils.js":(De,A,r)=>{r.r(A),r.d(A,{Processor:()=>J});var f=r("./src/utils/constants.js"),L=r("./src/utils/generic.js"),j=r("./src/utils/hub.js");class J extends L.Callable{constructor(w,v){super(),this.config=w,this.components=v}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(w,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(w,{tokenize:!1,...v})}batch_decode(...w){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...w)}async _call(w,...v){for(const y of[this.image_processor,this.feature_extractor,this.tokenizer])if(y)return y(w,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(w,v){const[y,M]=await Promise.all([this.uses_processor_config?(0,j.getModelJSON)(w,f.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(b=>b in this).map(async b=>{const D=await this[b].from_pretrained(w,v);return[b.replace(/_class$/,""),D]})).then(Object.fromEntries)]);return new this(y,M)}}ge(J,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),ge(J,"uses_processor_config",!1)},"./src/configs.js":(De,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>v,PretrainedConfig:()=>w,getKeyValueShapes:()=>W});var f=r("./src/utils/core.js"),L=r("./src/utils/hub.js");async function j(y,M){return await(0,L.getModelJSON)(y,"config.json",!0,M)}function J(y){const M={};let b={};switch(y.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":b=J(y.text_config);break;case"moondream1":b=J(y.phi_config);break;case"musicgen":b=J(y.decoder);break;case"multi_modality":b=J(y.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":M.num_heads="num_attention_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size",M.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.dim_kv="head_dim";break;case"openelm":M.num_heads="num_kv_heads",M.num_layers="num_transformer_layers",M.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":M.num_heads="num_heads",M.num_layers="num_layers",M.hidden_size="hidden_size";break;case"bloom":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="hidden_size";break;case"mpt":M.num_heads="n_heads",M.num_layers="n_layers",M.hidden_size="d_model";break;case"exaone":M.num_heads="num_key_value_heads",M.num_layers="num_layers",M.dim_kv="head_dim",M.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":M.num_decoder_layers="num_decoder_layers",M.num_decoder_heads="num_heads",M.decoder_dim_kv="d_kv",M.num_encoder_layers="num_layers",M.num_encoder_heads="num_heads",M.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="d_model",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="d_model";break;case"speecht5":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="hidden_size",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="hidden_size";break;case"trocr":M.num_encoder_layers=M.num_decoder_layers="decoder_layers",M.num_encoder_heads=M.num_decoder_heads="decoder_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":M.num_encoder_layers=M.num_decoder_layers="num_hidden_layers",M.num_encoder_heads=M.num_decoder_heads="num_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const H=J(y.decoder),re="num_decoder_layers"in H,ie=(0,f.pick)(y,["model_type","is_encoder_decoder"]);return re?(ie.num_decoder_layers=H.num_decoder_layers,ie.num_decoder_heads=H.num_decoder_heads,ie.decoder_hidden_size=H.decoder_hidden_size,ie.num_encoder_layers=H.num_encoder_layers,ie.num_encoder_heads=H.num_encoder_heads,ie.encoder_hidden_size=H.encoder_hidden_size):(ie.num_layers=H.num_layers,ie.num_heads=H.num_heads,ie.hidden_size=H.hidden_size),ie}const D={...b,...(0,f.pick)(y,["model_type","multi_query","is_encoder_decoder"])};for(const H in M)D[H]=y[M[H]];return D}function W(y,{prefix:M="past_key_values",batch_size:b=1}={}){const D={},H=y.normalized_config;if(H.is_encoder_decoder&&"num_encoder_heads"in H&&"num_decoder_heads"in H){const re=H.encoder_dim_kv??H.encoder_hidden_size/H.num_encoder_heads,ie=H.decoder_dim_kv??H.decoder_hidden_size/H.num_decoder_heads,z=[b,H.num_encoder_heads,0,re],V=[b,H.num_decoder_heads,0,ie];for(let Q=0;Q{var T,ee;r.r(A),r.d(A,{apis:()=>ie,env:()=>g});var f=r("?569f"),L=r("?3f59"),j=r("?154a");const J="3.2.4",W=typeof window<"u"&&typeof window.document<"u",w=typeof self<"u"&&((T=self.constructor)==null?void 0:T.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,y=typeof navigator<"u"&&"gpu"in navigator,M=typeof navigator<"u"&&"ml"in navigator,b=typeof process<"u",D=b&&((ee=process==null?void 0:process.release)==null?void 0:ee.name)==="node",H=!C(f),re=!C(L),ie=Object.freeze({IS_BROWSER_ENV:W,IS_WEBWORKER_ENV:w,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:y,IS_WEBNN_AVAILABLE:M,IS_PROCESS_AVAILABLE:b,IS_NODE_ENV:D,IS_FS_AVAILABLE:H,IS_PATH_AVAILABLE:re}),z=H&&re;let V="./";if(z){const Y=Object({url:self.location.href}).url;Y?V=L.dirname(L.dirname(j.fileURLToPath(Y))):typeof __dirname<"u"&&(V=L.dirname(__dirname))}const Q=z?L.join(V,"/.cache/"):null,F="/models/",$=z?L.join(V,F):F,g={version:J,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(W||w),localModelPath:$,useFS:H,useBrowserCache:v,useFSCache:H,cacheDir:Q,useCustomCache:!1,customCache:null};function C(Y){return Object.keys(Y).length===0}},"./src/generation/configuration_utils.js":(De,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>L});var f=r("./src/utils/core.js");class L{constructor(J){ge(this,"max_length",20);ge(this,"max_new_tokens",null);ge(this,"min_length",0);ge(this,"min_new_tokens",null);ge(this,"early_stopping",!1);ge(this,"max_time",null);ge(this,"do_sample",!1);ge(this,"num_beams",1);ge(this,"num_beam_groups",1);ge(this,"penalty_alpha",null);ge(this,"use_cache",!0);ge(this,"temperature",1);ge(this,"top_k",50);ge(this,"top_p",1);ge(this,"typical_p",1);ge(this,"epsilon_cutoff",0);ge(this,"eta_cutoff",0);ge(this,"diversity_penalty",0);ge(this,"repetition_penalty",1);ge(this,"encoder_repetition_penalty",1);ge(this,"length_penalty",1);ge(this,"no_repeat_ngram_size",0);ge(this,"bad_words_ids",null);ge(this,"force_words_ids",null);ge(this,"renormalize_logits",!1);ge(this,"constraints",null);ge(this,"forced_bos_token_id",null);ge(this,"forced_eos_token_id",null);ge(this,"remove_invalid_values",!1);ge(this,"exponential_decay_length_penalty",null);ge(this,"suppress_tokens",null);ge(this,"streamer",null);ge(this,"begin_suppress_tokens",null);ge(this,"forced_decoder_ids",null);ge(this,"guidance_scale",null);ge(this,"num_return_sequences",1);ge(this,"output_attentions",!1);ge(this,"output_hidden_states",!1);ge(this,"output_scores",!1);ge(this,"return_dict_in_generate",!1);ge(this,"pad_token_id",null);ge(this,"bos_token_id",null);ge(this,"eos_token_id",null);ge(this,"encoder_no_repeat_ngram_size",0);ge(this,"decoder_start_token_id",null);ge(this,"generation_kwargs",{});Object.assign(this,(0,f.pick)(J,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(De,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>z,ForcedBOSTokenLogitsProcessor:()=>w,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>j,LogitsProcessorList:()=>W,LogitsWarper:()=>J,MinLengthLogitsProcessor:()=>H,MinNewTokensLengthLogitsProcessor:()=>re,NoBadWordsLogitsProcessor:()=>ie,NoRepeatNGramLogitsProcessor:()=>b,RepetitionPenaltyLogitsProcessor:()=>D,SuppressTokensAtBeginLogitsProcessor:()=>y,TemperatureLogitsWarper:()=>V,TopKLogitsWarper:()=>F,TopPLogitsWarper:()=>Q,WhisperTimeStampLogitsProcessor:()=>M});var f=r("./src/utils/generic.js");r("./src/utils/tensor.js");var L=r("./src/utils/maths.js");class j extends f.Callable{_call(g,C){throw Error("`_call` should be implemented in a subclass")}}class J extends f.Callable{_call(g,C){throw Error("`_call` should be implemented in a subclass")}}class W extends f.Callable{constructor(){super(),this.processors=[]}push(g){this.processors.push(g)}extend(g){this.processors.push(...g)}_call(g,C){let T=C;for(const ee of this.processors)T=ee(g,T);return T}[Symbol.iterator](){return this.processors.values()}}class w extends j{constructor(g){super(),this.bos_token_id=g}_call(g,C){for(let T=0;T=1&&Y[Y.length-1]>=this.timestamp_begin,de=Y.length<2||Y[Y.length-2]>=this.timestamp_begin;if(le&&(de?ee.subarray(this.timestamp_begin).fill(-1/0):ee.subarray(0,this.eos_token_id).fill(-1/0)),g[T].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Le=this.timestamp_begin+this.max_initial_timestamp_index;ee.subarray(Le+1).fill(-1/0)}const fe=(0,L.log_softmax)(ee),Pe=Math.log(fe.subarray(this.timestamp_begin).map(Math.exp).reduce((Le,qe)=>Le+qe)),xe=(0,L.max)(fe.subarray(0,this.timestamp_begin))[0];Pe>xe&&ee.subarray(0,this.timestamp_begin).fill(-1/0)}return C}}class b extends j{constructor(g){super(),this.no_repeat_ngram_size=g}getNgrams(g){const C=g.length,T=[];for(let Y=0;Y1 to use the classifier free guidance processor, got guidance scale ${g}.`);this.guidance_scale=g}_call(g,C){if(C.dims[0]!==2*g.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${C.dims[0]} for the logits and ${g.length} for the input ids.`);const T=g.length,ee=C.slice([0,T],null),Y=C.slice([T,C.dims[0]],null);for(let le=0;le1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${g}`);if(!Number.isInteger(T)||T<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${T}`);this.top_p=g,this.filter_value=C,this.min_tokens_to_keep=T}}class F extends J{constructor(g,{filter_value:C=-1/0,min_tokens_to_keep:T=1}={}){if(super(),!Number.isInteger(g)||g<0)throw new Error(`\`top_k\` must be a positive integer, but is ${g}`);this.top_k=Math.max(g,T),this.filter_value=C}}},"./src/generation/logits_sampler.js":(De,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>J});var f=r("./src/utils/generic.js"),L=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class J extends f.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,b){let D=M.dims.at(-1),H=M.data;if(b===-1)H=H.slice(-D);else{let re=b*D;H=H.slice(re,re+D)}return H}randomSelect(M){let b=0;for(let H=0;H1)return new v(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 W(M)}}class W extends J{async sample(M){const b=(0,j.max)(M.data)[1];return[[BigInt(b),0]]}}class w extends J{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[D,H]=await(0,L.topk)(M,b),re=(0,j.softmax)(D.data);return Array.from({length:this.generation_config.num_beams},()=>{const ie=this.randomSelect(re);return[H.data[ie],Math.log(re[ie])]})}}class v extends J{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[D,H]=await(0,L.topk)(M,b),re=(0,j.softmax)(D.data);return Array.from({length:this.generation_config.num_beams},(ie,z)=>[H.data[z],Math.log(re[z])])}}},"./src/generation/stopping_criteria.js":(De,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>W,InterruptableStoppingCriteria:()=>w,MaxLengthCriteria:()=>J,StoppingCriteria:()=>L,StoppingCriteriaList:()=>j});var f=r("./src/utils/generic.js");class L extends f.Callable{_call(y,M){throw Error("StoppingCriteria needs to be subclassed")}}class j extends f.Callable{constructor(){super(),this.criteria=[]}push(y){this.criteria.push(y)}extend(y){y instanceof j?y=y.criteria:y instanceof L&&(y=[y]),this.criteria.push(...y)}_call(y,M){const b=new Array(y.length).fill(!1);for(const D of this.criteria){const H=D(y,M);for(let re=0;reM.length>=this.max_length)}}class W extends L{constructor(y){super(),Array.isArray(y)||(y=[y]),this.eos_token_id=y}_call(y,M){return y.map(b=>{const D=b.at(-1);return this.eos_token_id.some(H=>D==H)})}}class w extends L{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":(De,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>J,TextStreamer:()=>w,WhisperTextStreamer:()=>v});var f=r("./src/utils/core.js"),L=r("./src/tokenizers.js"),j=r("./src/env.js");class J{put(M){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const W=j.apis.IS_PROCESS_AVAILABLE?y=>process.stdout.write(y):y=>console.log(y);class w extends J{constructor(M,{skip_prompt:b=!1,callback_function:D=null,token_callback_function:H=null,decode_kwargs:re={},...ie}={}){super(),this.tokenizer=M,this.skip_prompt=b,this.callback_function=D??W,this.token_callback_function=H,this.decode_kwargs={...re,...ie},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(M){var re;if(M.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const b=M[0];(re=this.token_callback_function)==null||re.call(this,b),this.token_cache=(0,f.mergeArrays)(this.token_cache,b);const D=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let H;D.endsWith(` `)?(H=D.slice(this.print_len),this.token_cache=[],this.print_len=0):D.length>0&&(0,L.is_chinese_char)(D.charCodeAt(D.length-1))?(H=D.slice(this.print_len),this.print_len+=H.length):(H=D.slice(this.print_len,D.lastIndexOf(" ")+1),this.print_len+=H.length),this.on_finalized_text(H,!1)}end(){let M;this.token_cache.length>0?(M=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):M="",this.next_tokens_are_prompt=!0,this.on_finalized_text(M,!0)}on_finalized_text(M,b){var D,H;M.length>0&&((D=this.callback_function)==null||D.call(this,M)),b&&this.callback_function===W&&j.apis.IS_PROCESS_AVAILABLE&&((H=this.callback_function)==null||H.call(this,` `))}}class v extends w{constructor(M,{skip_prompt:b=!1,callback_function:D=null,token_callback_function:H=null,on_chunk_start:re=null,on_chunk_end:ie=null,on_finalize:z=null,time_precision:V=.02,skip_special_tokens:Q=!0,decode_kwargs:F={}}={}){super(M,{skip_prompt:b,callback_function:D,token_callback_function:H,decode_kwargs:{skip_special_tokens:Q,...F}}),this.timestamp_begin=M.timestamp_begin,this.on_chunk_start=re,this.on_chunk_end=ie,this.on_finalize=z,this.time_precision=V,this.waiting_for_timestamp=!1}put(M){var D,H;if(M.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const b=M[0];if(b.length===1){const re=Number(b[0])-this.timestamp_begin;if(re>=0){const ie=re*this.time_precision;this.waiting_for_timestamp?(D=this.on_chunk_end)==null||D.call(this,ie):(H=this.on_chunk_start)==null||H.call(this,ie),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":(De,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>sr,ASTModel:()=>Ea,ASTPreTrainedModel:()=>Wi,AlbertForMaskedLM:()=>vn,AlbertForQuestionAnswering:()=>bn,AlbertForSequenceClassification:()=>Bn,AlbertModel:()=>Mn,AlbertPreTrainedModel:()=>Qs,AutoModel:()=>ua,AutoModelForAudioClassification:()=>pc,AutoModelForAudioFrameClassification:()=>mc,AutoModelForCTC:()=>da,AutoModelForCausalLM:()=>tc,AutoModelForDepthEstimation:()=>wc,AutoModelForDocumentQuestionAnswering:()=>_c,AutoModelForImageClassification:()=>ic,AutoModelForImageFeatureExtraction:()=>Mc,AutoModelForImageMatting:()=>fc,AutoModelForImageSegmentation:()=>oc,AutoModelForImageToImage:()=>gc,AutoModelForMaskGeneration:()=>cc,AutoModelForMaskedLM:()=>sc,AutoModelForNormalEstimation:()=>_p,AutoModelForObjectDetection:()=>uc,AutoModelForPoseEstimation:()=>yc,AutoModelForQuestionAnswering:()=>rc,AutoModelForSemanticSegmentation:()=>ac,AutoModelForSeq2SeqLM:()=>Jd,AutoModelForSequenceClassification:()=>hp,AutoModelForSpeechSeq2Seq:()=>Zd,AutoModelForTextToSpectrogram:()=>ec,AutoModelForTextToWaveform:()=>mp,AutoModelForTokenClassification:()=>Yd,AutoModelForUniversalSegmentation:()=>lc,AutoModelForVision2Seq:()=>nc,AutoModelForXVector:()=>hc,AutoModelForZeroShotObjectDetection:()=>dc,BartForConditionalGeneration:()=>Pt,BartForSequenceClassification:()=>hs,BartModel:()=>ot,BartPretrainedModel:()=>mt,BaseModelOutput:()=>Fe,BeitForImageClassification:()=>nn,BeitModel:()=>Rc,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>Ne,BertForSequenceClassification:()=>We,BertForTokenClassification:()=>Ve,BertModel:()=>ve,BertPreTrainedModel:()=>pe,BlenderbotForConditionalGeneration:()=>Ns,BlenderbotModel:()=>Bt,BlenderbotPreTrainedModel:()=>Js,BlenderbotSmallForConditionalGeneration:()=>_s,BlenderbotSmallModel:()=>es,BlenderbotSmallPreTrainedModel:()=>hr,BloomForCausalLM:()=>Cl,BloomModel:()=>Pl,BloomPreTrainedModel:()=>fo,CLIPModel:()=>La,CLIPPreTrainedModel:()=>rn,CLIPSegForImageSegmentation:()=>Va,CLIPSegModel:()=>Ua,CLIPSegPreTrainedModel:()=>Xi,CLIPTextModel:()=>Fc,CLIPTextModelWithProjection:()=>za,CLIPVisionModel:()=>Dc,CLIPVisionModelWithProjection:()=>Lc,CamembertForMaskedLM:()=>Yr,CamembertForQuestionAnswering:()=>Sr,CamembertForSequenceClassification:()=>kr,CamembertForTokenClassification:()=>Br,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>br,CausalLMOutput:()=>ln,CausalLMOutputWithPast:()=>Ii,ChineseCLIPModel:()=>Ra,ChineseCLIPPreTrainedModel:()=>_r,ClapAudioModelWithProjection:()=>dd,ClapModel:()=>ld,ClapPreTrainedModel:()=>$i,ClapTextModelWithProjection:()=>ud,CodeGenForCausalLM:()=>ui,CodeGenModel:()=>el,CodeGenPreTrainedModel:()=>Za,CohereForCausalLM:()=>hl,CohereModel:()=>pl,CoherePreTrainedModel:()=>lo,ConvBertForMaskedLM:()=>Ft,ConvBertForQuestionAnswering:()=>gs,ConvBertForSequenceClassification:()=>At,ConvBertForTokenClassification:()=>ns,ConvBertModel:()=>St,ConvBertPreTrainedModel:()=>It,ConvNextForImageClassification:()=>Mu,ConvNextModel:()=>yu,ConvNextPreTrainedModel:()=>Bo,ConvNextV2ForImageClassification:()=>vu,ConvNextV2Model:()=>bu,ConvNextV2PreTrainedModel:()=>Ti,DPTForDepthEstimation:()=>hu,DPTModel:()=>pu,DPTPreTrainedModel:()=>Fo,DebertaForMaskedLM:()=>pr,DebertaForQuestionAnswering:()=>ar,DebertaForSequenceClassification:()=>Ar,DebertaForTokenClassification:()=>Jr,DebertaModel:()=>$r,DebertaPreTrainedModel:()=>or,DebertaV2ForMaskedLM:()=>Ot,DebertaV2ForQuestionAnswering:()=>ts,DebertaV2ForSequenceClassification:()=>ls,DebertaV2ForTokenClassification:()=>vr,DebertaV2Model:()=>gt,DebertaV2PreTrainedModel:()=>nt,DecisionTransformerModel:()=>Ed,DecisionTransformerPreTrainedModel:()=>xd,DeiTForImageClassification:()=>iu,DeiTModel:()=>Ao,DeiTPreTrainedModel:()=>_i,DepthAnythingForDepthEstimation:()=>mu,DepthAnythingPreTrainedModel:()=>jc,DepthProForDepthEstimation:()=>bi,DepthProPreTrainedModel:()=>fu,DetrForObjectDetection:()=>So,DetrForSegmentation:()=>Gr,DetrModel:()=>on,DetrObjectDetectionOutput:()=>Vs,DetrPreTrainedModel:()=>Ir,DetrSegmentationOutput:()=>tu,Dinov2ForImageClassification:()=>xu,Dinov2Model:()=>Tu,Dinov2PreTrainedModel:()=>xi,Dinov2WithRegistersForImageClassification:()=>Cu,Dinov2WithRegistersModel:()=>Pu,Dinov2WithRegistersPreTrainedModel:()=>Eu,DistilBertForMaskedLM:()=>An,DistilBertForQuestionAnswering:()=>Tr,DistilBertForSequenceClassification:()=>Zr,DistilBertForTokenClassification:()=>Nr,DistilBertModel:()=>Rr,DistilBertPreTrainedModel:()=>er,DonutSwinModel:()=>Vc,DonutSwinPreTrainedModel:()=>wu,EfficientNetForImageClassification:()=>fd,EfficientNetModel:()=>_d,EfficientNetPreTrainedModel:()=>Ko,ElectraForMaskedLM:()=>Xs,ElectraForQuestionAnswering:()=>zr,ElectraForSequenceClassification:()=>ir,ElectraForTokenClassification:()=>Qr,ElectraModel:()=>As,ElectraPreTrainedModel:()=>Ss,EsmForMaskedLM:()=>ni,EsmForSequenceClassification:()=>Wr,EsmForTokenClassification:()=>xr,EsmModel:()=>In,EsmPreTrainedModel:()=>jr,ExaoneForCausalLM:()=>nl,ExaoneModel:()=>rl,ExaonePreTrainedModel:()=>xn,FalconForCausalLM:()=>ad,FalconModel:()=>od,FalconPreTrainedModel:()=>Uo,FastViTForImageClassification:()=>Ul,FastViTModel:()=>Wl,FastViTPreTrainedModel:()=>dr,Florence2ForConditionalGeneration:()=>Ia,Florence2PreTrainedModel:()=>Aa,GLPNForDepthEstimation:()=>Uc,GLPNModel:()=>zo,GLPNPreTrainedModel:()=>Lo,GPT2LMHeadModel:()=>fr,GPT2Model:()=>Ga,GPT2PreTrainedModel:()=>Qi,GPTBigCodeForCausalLM:()=>no,GPTBigCodeModel:()=>Ja,GPTBigCodePreTrainedModel:()=>ro,GPTJForCausalLM:()=>so,GPTJModel:()=>to,GPTJPreTrainedModel:()=>eo,GPTNeoForCausalLM:()=>Xa,GPTNeoModel:()=>qa,GPTNeoPreTrainedModel:()=>Ji,GPTNeoXForCausalLM:()=>Ya,GPTNeoXModel:()=>Qa,GPTNeoXPreTrainedModel:()=>Zi,Gemma2ForCausalLM:()=>gl,Gemma2Model:()=>fl,Gemma2PreTrainedModel:()=>co,GemmaForCausalLM:()=>_l,GemmaModel:()=>ml,GemmaPreTrainedModel:()=>uo,GraniteForCausalLM:()=>us,GraniteModel:()=>cl,GranitePreTrainedModel:()=>dl,GroupViTModel:()=>jl,GroupViTPreTrainedModel:()=>Nl,HieraForImageClassification:()=>gi,HieraModel:()=>ou,HieraPreTrainedModel:()=>fi,HubertForCTC:()=>qu,HubertForSequenceClassification:()=>Xu,HubertModel:()=>Yc,HubertPreTrainedModel:()=>Qc,IJepaForImageClassification:()=>Ol,IJepaModel:()=>bo,IJepaPreTrainedModel:()=>pi,Idefics3ForConditionalGeneration:()=>Ki,Idefics3PreTrainedModel:()=>Fa,ImageMattingOutput:()=>vc,JAISLMHeadModel:()=>Ha,JAISModel:()=>Ka,JAISPreTrainedModel:()=>Yi,JinaCLIPModel:()=>Na,JinaCLIPPreTrainedModel:()=>li,JinaCLIPTextModel:()=>ja,JinaCLIPVisionModel:()=>Wa,LlamaForCausalLM:()=>sl,LlamaModel:()=>tl,LlamaPreTrainedModel:()=>io,LlavaForConditionalGeneration:()=>oi,LlavaOnevisionForConditionalGeneration:()=>Sa,LlavaPreTrainedModel:()=>ka,LongT5ForConditionalGeneration:()=>Ce,LongT5Model:()=>be,LongT5PreTrainedModel:()=>ae,M2M100ForConditionalGeneration:()=>Du,M2M100Model:()=>Fu,M2M100PreTrainedModel:()=>Pi,MBartForCausalLM:()=>Ys,MBartForConditionalGeneration:()=>ws,MBartForSequenceClassification:()=>Rs,MBartModel:()=>Se,MBartPreTrainedModel:()=>ss,MPNetForMaskedLM:()=>wn,MPNetForQuestionAnswering:()=>Dn,MPNetForSequenceClassification:()=>On,MPNetForTokenClassification:()=>Fn,MPNetModel:()=>zt,MPNetPreTrainedModel:()=>Er,MT5ForConditionalGeneration:()=>yt,MT5Model:()=>ct,MT5PreTrainedModel:()=>He,MarianMTModel:()=>jn,MarianModel:()=>Ei,MarianPreTrainedModel:()=>Ou,MaskFormerForInstanceSegmentation:()=>gu,MaskFormerModel:()=>Do,MaskFormerPreTrainedModel:()=>vi,MaskedLMOutput:()=>Us,MgpstrForSceneTextRecognition:()=>np,MgpstrModelOutput:()=>Cd,MgpstrPreTrainedModel:()=>kd,MistralForCausalLM:()=>an,MistralModel:()=>Or,MistralPreTrainedModel:()=>gr,MobileBertForMaskedLM:()=>en,MobileBertForQuestionAnswering:()=>tn,MobileBertForSequenceClassification:()=>gn,MobileBertModel:()=>fn,MobileBertPreTrainedModel:()=>lr,MobileLLMForCausalLM:()=>ol,MobileLLMModel:()=>il,MobileLLMPreTrainedModel:()=>di,MobileNetV1ForImageClassification:()=>yd,MobileNetV1Model:()=>wd,MobileNetV1PreTrainedModel:()=>Xo,MobileNetV2ForImageClassification:()=>Md,MobileNetV2Model:()=>Yo,MobileNetV2PreTrainedModel:()=>Qo,MobileNetV3ForImageClassification:()=>vd,MobileNetV3Model:()=>Jo,MobileNetV3PreTrainedModel:()=>bd,MobileNetV4ForImageClassification:()=>sp,MobileNetV4Model:()=>Td,MobileNetV4PreTrainedModel:()=>Zo,MobileViTForImageClassification:()=>Hl,MobileViTModel:()=>Kl,MobileViTPreTrainedModel:()=>Eo,MobileViTV2ForImageClassification:()=>Xl,MobileViTV2Model:()=>ql,MobileViTV2PreTrainedModel:()=>Po,ModelOutput:()=>Je,ModernBertForMaskedLM:()=>ft,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>at,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>$a,MoonshineForConditionalGeneration:()=>Ca,MoonshineModel:()=>Oc,MoonshinePreTrainedModel:()=>Vi,MptForCausalLM:()=>Sl,MptModel:()=>kl,MptPreTrainedModel:()=>go,MultiModalityCausalLM:()=>rp,MultiModalityPreTrainedModel:()=>Pd,MusicgenForCausalLM:()=>gd,MusicgenForConditionalGeneration:()=>qo,MusicgenModel:()=>tp,MusicgenPreTrainedModel:()=>Ho,NomicBertModel:()=>ne,NomicBertPreTrainedModel:()=>I,OPTForCausalLM:()=>Al,OPTModel:()=>$l,OPTPreTrainedModel:()=>wo,Olmo2ForCausalLM:()=>ul,Olmo2Model:()=>ll,Olmo2PreTrainedModel:()=>ao,OlmoForCausalLM:()=>zc,OlmoModel:()=>al,OlmoPreTrainedModel:()=>oo,OpenELMForCausalLM:()=>yl,OpenELMModel:()=>wl,OpenELMPreTrainedModel:()=>po,OwlViTForObjectDetection:()=>Jl,OwlViTModel:()=>Yl,OwlViTPreTrainedModel:()=>Ql,Owlv2ForObjectDetection:()=>eu,Owlv2Model:()=>Zl,Owlv2PreTrainedModel:()=>Co,PaliGemmaForConditionalGeneration:()=>Oa,PaliGemmaPreTrainedModel:()=>mr,PatchTSMixerForPrediction:()=>ip,PatchTSMixerModel:()=>Ad,PatchTSMixerPreTrainedModel:()=>ta,PatchTSTForPrediction:()=>$d,PatchTSTModel:()=>Sd,PatchTSTPreTrainedModel:()=>ea,Phi3ForCausalLM:()=>El,Phi3Model:()=>xl,Phi3PreTrainedModel:()=>_o,Phi3VForCausalLM:()=>Hi,Phi3VPreTrainedModel:()=>Da,PhiForCausalLM:()=>Tl,PhiModel:()=>vl,PhiPreTrainedModel:()=>mo,PreTrainedModel:()=>oe,PretrainedMixin:()=>fs,PvtForImageClassification:()=>zl,PvtModel:()=>Ll,PvtPreTrainedModel:()=>vo,PyAnnoteForAudioFrameClassification:()=>Ru,PyAnnoteModel:()=>Kc,PyAnnotePreTrainedModel:()=>jo,QuestionAnsweringModelOutput:()=>Zs,Qwen2ForCausalLM:()=>Rn,Qwen2Model:()=>Ml,Qwen2PreTrainedModel:()=>ho,Qwen2VLForConditionalGeneration:()=>ci,Qwen2VLPreTrainedModel:()=>bl,RTDetrForObjectDetection:()=>Nc,RTDetrModel:()=>su,RTDetrObjectDetectionOutput:()=>Nn,RTDetrPreTrainedModel:()=>hi,ResNetForImageClassification:()=>lu,ResNetModel:()=>au,ResNetPreTrainedModel:()=>wi,RoFormerForMaskedLM:()=>Ie,RoFormerForQuestionAnswering:()=>pt,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>rt,RoFormerModel:()=>ce,RoFormerPreTrainedModel:()=>K,RobertaForMaskedLM:()=>Pr,RobertaForQuestionAnswering:()=>Mt,RobertaForSequenceClassification:()=>Ds,RobertaForTokenClassification:()=>Hs,RobertaModel:()=>ys,RobertaPreTrainedModel:()=>vt,SamImageSegmentationOutput:()=>Iu,SamModel:()=>Au,SamPreTrainedModel:()=>$u,SapiensForDepthEstimation:()=>_u,SapiensForNormalEstimation:()=>Mi,SapiensForSemanticSegmentation:()=>Wc,SapiensPreTrainedModel:()=>yi,SegformerForImageClassification:()=>hd,SegformerForSemanticSegmentation:()=>Vo,SegformerModel:()=>ep,SegformerPreTrainedModel:()=>Gs,Seq2SeqLMOutput:()=>fp,SequenceClassifierOutput:()=>Xt,SiglipModel:()=>Ba,SiglipPreTrainedModel:()=>ur,SiglipTextModel:()=>ai,SiglipVisionModel:()=>qi,SpeechT5ForSpeechToText:()=>ed,SpeechT5ForTextToSpeech:()=>td,SpeechT5HifiGan:()=>sd,SpeechT5Model:()=>zp,SpeechT5PreTrainedModel:()=>Si,SqueezeBertForMaskedLM:()=>yn,SqueezeBertForQuestionAnswering:()=>os,SqueezeBertForSequenceClassification:()=>zn,SqueezeBertModel:()=>Ln,SqueezeBertPreTrainedModel:()=>Ur,StableLmForCausalLM:()=>md,StableLmModel:()=>Un,StableLmPreTrainedModel:()=>Go,Starcoder2ForCausalLM:()=>id,Starcoder2Model:()=>nd,Starcoder2PreTrainedModel:()=>Hr,Swin2SRForImageSuperResolution:()=>Oo,Swin2SRModel:()=>cu,Swin2SRPreTrainedModel:()=>En,SwinForImageClassification:()=>Io,SwinModel:()=>du,SwinPreTrainedModel:()=>uu,T5ForConditionalGeneration:()=>q,T5Model:()=>P,T5PreTrainedModel:()=>Ee,TableTransformerForObjectDetection:()=>ru,TableTransformerModel:()=>$o,TableTransformerObjectDetectionOutput:()=>nu,TableTransformerPreTrainedModel:()=>mi,TokenClassifierOutput:()=>js,TrOCRForCausalLM:()=>Zc,TrOCRPreTrainedModel:()=>rd,UniSpeechForCTC:()=>Hc,UniSpeechForSequenceClassification:()=>Wu,UniSpeechModel:()=>ju,UniSpeechPreTrainedModel:()=>Ci,UniSpeechSatForAudioFrameClassification:()=>Gu,UniSpeechSatForCTC:()=>Uu,UniSpeechSatForSequenceClassification:()=>Vu,UniSpeechSatModel:()=>qc,UniSpeechSatPreTrainedModel:()=>Wn,ViTForImageClassification:()=>Il,ViTMAEModel:()=>Bl,ViTMAEPreTrainedModel:()=>To,ViTMSNForImageClassification:()=>Bc,ViTMSNModel:()=>Rl,ViTMSNPreTrainedModel:()=>xo,ViTModel:()=>Mo,ViTPreTrainedModel:()=>yo,VisionEncoderDecoderModel:()=>Gi,VitMatteForImageMatting:()=>Gl,VitMattePreTrainedModel:()=>Vl,VitPoseForPoseEstimation:()=>Dl,VitPosePreTrainedModel:()=>Fl,VitsModel:()=>pd,VitsModelOutput:()=>ca,VitsPreTrainedModel:()=>cd,Wav2Vec2BertForCTC:()=>Ku,Wav2Vec2BertForSequenceClassification:()=>Hu,Wav2Vec2BertModel:()=>Xc,Wav2Vec2BertPreTrainedModel:()=>ki,Wav2Vec2ForAudioFrameClassification:()=>Bu,Wav2Vec2ForCTC:()=>No,Wav2Vec2ForSequenceClassification:()=>zu,Wav2Vec2Model:()=>Lu,Wav2Vec2PreTrainedModel:()=>Kr,WavLMForAudioFrameClassification:()=>Zu,WavLMForCTC:()=>Jc,WavLMForSequenceClassification:()=>Yu,WavLMForXVector:()=>Ju,WavLMModel:()=>Qu,WavLMPreTrainedModel:()=>Pn,WeSpeakerResNetModel:()=>Nu,WeSpeakerResNetPreTrainedModel:()=>Wo,WhisperForConditionalGeneration:()=>Vr,WhisperModel:()=>Pa,WhisperPreTrainedModel:()=>Ui,XLMForQuestionAnswering:()=>ii,XLMForSequenceClassification:()=>tr,XLMForTokenClassification:()=>sn,XLMModel:()=>Be,XLMPreTrainedModel:()=>bs,XLMRobertaForMaskedLM:()=>va,XLMRobertaForQuestionAnswering:()=>xa,XLMRobertaForSequenceClassification:()=>ji,XLMRobertaForTokenClassification:()=>Ta,XLMRobertaModel:()=>Qt,XLMRobertaPreTrainedModel:()=>Tn,XLMWithLMHeadModel:()=>wt,XVectorOutput:()=>bc,YolosForObjectDetection:()=>ku,YolosModel:()=>Gc,YolosObjectDetectionOutput:()=>Su,YolosPreTrainedModel:()=>Ro});var f=r("./src/configs.js"),L=r("./src/backends/onnx.js"),j=r("./src/utils/dtypes.js"),J=r("./src/utils/generic.js"),W=r("./src/utils/core.js"),w=r("./src/utils/hub.js"),v=r("./src/utils/constants.js"),y=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),b=r("./src/utils/tensor.js"),D=r("./src/utils/image.js"),H=r("./src/utils/maths.js"),re=r("./src/generation/stopping_criteria.js"),ie=r("./src/generation/logits_sampler.js"),z=r("./src/env.js"),V=r("./src/models/whisper/generation_whisper.js"),Q=r("./src/models/whisper/common_whisper.js");const F={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},$=new Map,g=new Map,C=new Map;async function T(_,x,N){var Es;const ye=((Es=N.config)==null?void 0:Es["transformers.js_config"])??{};let Oe=N.device??ye.device;Oe&&typeof Oe!="string"&&(Oe.hasOwnProperty(x)?Oe=Oe[x]:(console.warn(`device not specified for "${x}". Using the default device.`),Oe=null));const ke=Oe??(z.apis.IS_NODE_ENV?"cpu":"wasm"),Ye=(0,L.deviceToExecutionProviders)(ke);let tt=N.dtype??ye.dtype;if(typeof tt!="string"&&(tt&&tt.hasOwnProperty(x)?tt=tt[x]:(tt=j.DEFAULT_DEVICE_DTYPE_MAPPING[ke]??j.DATA_TYPES.fp32,console.warn(`dtype not specified for "${x}". Using the default dtype (${tt}) for this device (${ke}).`))),tt===j.DATA_TYPES.auto){let ds=ye.dtype;typeof ds!="string"&&(ds=ds[x]),ds&&ds!==j.DATA_TYPES.auto&&j.DATA_TYPES.hasOwnProperty(ds)?tt=ds:tt=j.DEFAULT_DEVICE_DTYPE_MAPPING[ke]??j.DATA_TYPES.fp32}const _t=tt;if(j.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(_t)){if(_t===j.DATA_TYPES.fp16&&ke==="webgpu"&&!await(0,j.isWebGpuFp16Supported)())throw new Error(`The device (${ke}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_t}. Should be one of: ${Object.keys(j.DATA_TYPES).join(", ")}`);const Tt=ye.kv_cache_dtype?typeof ye.kv_cache_dtype=="string"?ye.kv_cache_dtype:ye.kv_cache_dtype[_t]??"float32":void 0;if(Tt&&!["float32","float16"].includes(Tt))throw new Error(`Invalid kv_cache_dtype: ${Tt}. Should be one of: float32, float16`);const Lt={dtype:_t,kv_cache_dtype:Tt},Wt=j.DEFAULT_DTYPE_SUFFIX_MAPPING[_t],Dt=`${N.subfolder??""}/${x}${Wt}.onnx`,Vt={...N.session_options};Vt.executionProviders??(Vt.executionProviders=Ye);const Zt=ye.free_dimension_overrides;Zt?Vt.freeDimensionOverrides??(Vt.freeDimensionOverrides=Zt):ke.startsWith("webnn")&&!Vt.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const rs=(0,w.getModelFile)(_,Dt,!0,N),qt=N.use_external_data_format??ye.use_external_data_format;let is=[];if(qt&&(qt===!0||typeof qt=="object"&&qt.hasOwnProperty(x)&&qt[x]===!0)){if(z.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const ds=`${x}${Wt}.onnx_data`,ks=`${N.subfolder??""}/${ds}`;is.push(new Promise(async($s,qs)=>{const Ws=await(0,w.getModelFile)(_,ks,!0,N);$s({path:ds,data:Ws})}))}else Vt.externalData!==void 0&&(is=Vt.externalData.map(async ds=>{if(typeof ds.data=="string"){const ks=await(0,w.getModelFile)(_,ds.data,!0,N);return{...ds,data:ks}}return ds}));if(is.length>0&&(Vt.externalData=await Promise.all(is)),ke==="webgpu"){const ds=(0,f.getKeyValueShapes)(N.config,{prefix:"present"});if(Object.keys(ds).length>0&&!(0,L.isONNXProxy)()){const ks={};for(const $s in ds)ks[$s]="gpu-buffer";Vt.preferredOutputLocation=ks}}return{buffer:await rs,session_options:Vt,session_config:Lt}}async function ee(_,x,N){return Object.fromEntries(await Promise.all(Object.keys(x).map(async ye=>{const{buffer:Oe,session_options:ke,session_config:Ye}=await T(_,x[ye],N),tt=await(0,L.createInferenceSession)(Oe,ke,Ye);return[ye,tt]})))}async function Y(_,x,N){return Object.fromEntries(await Promise.all(Object.keys(x).map(async ye=>{const Oe=await(0,w.getModelJSON)(_,x[ye],!1,N);return[ye,Oe]})))}function le(_,x){const N=Object.create(null),ye=[];for(const Ye of _.inputNames){const tt=x[Ye];if(!(tt instanceof b.Tensor)){ye.push(Ye);continue}N[Ye]=(0,L.isONNXProxy)()?tt.clone():tt}if(ye.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ye.join(", ")}.`);const Oe=Object.keys(x).length,ke=_.inputNames.length;if(Oe>ke){let Ye=Object.keys(x).filter(tt=>!_.inputNames.includes(tt));console.warn(`WARNING: Too many inputs were provided (${Oe} > ${ke}). The following inputs will be ignored: "${Ye.join(", ")}".`)}return N}async function de(_,x){const N=le(_,x);try{const ye=Object.fromEntries(Object.entries(N).map(([ke,Ye])=>[ke,Ye.ort_tensor]));let Oe=await _.run(ye);return Oe=fe(Oe),Oe}catch(ye){const Oe=Object.fromEntries(Object.entries(N).map(([ke,{type:Ye,dims:tt,data:_t}])=>[ke,{type:Ye,dims:tt,data:_t}]));throw console.error(`An error occurred during model execution: "${ye}".`),console.error("Inputs given to model:",Oe),ye}}function fe(_){for(let x in _)(0,L.isONNXTensor)(_[x])?_[x]=new b.Tensor(_[x]):typeof _[x]=="object"&&fe(_[x]);return _}function Pe(_){if(_ instanceof b.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(x=>x.length!==_[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 b.Tensor("int64",BigInt64Array.from(_.flat().map(x=>BigInt(x))),[_.length,_[0].length])}else return new b.Tensor("int64",BigInt64Array.from(_.map(x=>BigInt(x))),[1,_.length])}function xe(_){return new b.Tensor("bool",[_],[1])}async function Le(_,x){let{encoder_outputs:N,input_ids:ye,decoder_input_ids:Oe,...ke}=x;if(!N){const tt=(0,W.pick)(x,_.sessions.model.inputNames);N=(await qe(_,tt)).last_hidden_state}return ke.input_ids=Oe,ke.encoder_hidden_states=N,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ke.encoder_attention_mask=x.attention_mask),await je(_,ke,!0)}async function qe(_,x){const N=_.sessions.model,ye=(0,W.pick)(x,N.inputNames);if(N.inputNames.includes("inputs_embeds")&&!ye.inputs_embeds){if(!x.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ye.inputs_embeds=await _.encode_text({input_ids:x.input_ids})}return N.inputNames.includes("token_type_ids")&&!ye.token_type_ids&&(ye.token_type_ids=new b.Tensor("int64",new BigInt64Array(ye.input_ids.data.length),ye.input_ids.dims)),await de(N,ye)}async function je(_,x,N=!1){const ye=_.sessions[N?"decoder_model_merged":"model"],{past_key_values:Oe,...ke}=x;if(ye.inputNames.includes("use_cache_branch")&&(ke.use_cache_branch=xe(!!Oe)),ye.inputNames.includes("position_ids")&&ke.attention_mask&&!ke.position_ids){const tt=_.config.model_type==="paligemma"?1:0;ke.position_ids=he(ke,Oe,tt)}_.addPastKeyValues(ke,Oe);const Ye=(0,W.pick)(ke,ye.inputNames);return await de(ye,Ye)}function dt({image_token_id:_,inputs_embeds:x,image_features:N,input_ids:ye,attention_mask:Oe}){const ke=ye.tolist().map(Tt=>Tt.reduce((Lt,Wt,Dt)=>(Wt==_&&Lt.push(Dt),Lt),[])),Ye=ke.reduce((Tt,Lt)=>Tt+Lt.length,0),tt=N.dims[0];if(Ye!==tt)throw new Error(`Image features and image tokens do not match: tokens: ${Ye}, features ${tt}`);let _t=0;for(let Tt=0;Ttke.dims[1])){if(Oett==_.config.image_token_index)){const tt=_.config.num_image_tokens;if(!tt)throw new Error("`num_image_tokens` is missing in the model configuration.");const _t=ke.dims[1]-(Oe-tt);N.input_ids=ke.slice(null,[-_t,null]),N.attention_mask=(0,b.ones)([1,Oe+_t])}}}return N}function ze(_,x,N,ye){return N.past_key_values&&(x=x.map(Oe=>[Oe.at(-1)])),{...N,decoder_input_ids:Pe(x)}}function et(_,...x){return _.config.is_encoder_decoder?ze(_,...x):Te(_,...x)}function Xe(_,x,N,ye){const Oe=!!N.past_key_values;return ye.guidance_scale!==null&&ye.guidance_scale>1&&(Oe?N.input_ids=(0,b.cat)([N.input_ids,N.input_ids],0):(N.input_ids=(0,b.cat)([N.input_ids,(0,b.full_like)(N.input_ids,BigInt(ye.pad_token_id))],0),N.attention_mask=(0,b.cat)([N.attention_mask,(0,b.full_like)(N.attention_mask,0n)],0))),(Oe||!N.pixel_values)&&(N.pixel_values=(0,b.full)([0,0,3,384,384],1)),Oe&&(N.images_seq_mask=new b.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),N.images_emb_mask=new b.Tensor("bool",new Array(0).fill(!1),[1,1,0])),N}class oe extends J.Callable{constructor(N,ye,Oe){super();ge(this,"main_input_name","input_ids");ge(this,"forward_params",["input_ids","attention_mask"]);this.config=N,this.sessions=ye,this.configs=Oe;const ke=C.get(this.constructor),Ye=$.get(ke);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ye){case F.DecoderOnly:this.can_generate=!0,this._forward=je,this._prepare_inputs_for_generation=Te;break;case F.Seq2Seq:case F.Vision2Seq:case F.Musicgen:this.can_generate=!0,this._forward=Le,this._prepare_inputs_for_generation=ze;break;case F.EncoderDecoder:this._forward=Le;break;case F.ImageTextToText:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=et;break;case F.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=et;break;case F.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Xe;break;default:this._forward=qe;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ye;const N=[];for(const Oe of Object.values(this.sessions))(ye=Oe==null?void 0:Oe.handler)!=null&&ye.dispose&&N.push(Oe.handler.dispose());return await Promise.all(N)}static async from_pretrained(N,{progress_callback:ye=null,config:Oe=null,cache_dir:ke=null,local_files_only:Ye=!1,revision:tt="main",model_file_name:_t=null,subfolder:Tt="onnx",device:Lt=null,dtype:Wt=null,use_external_data_format:Dt=null,session_options:Vt={}}={}){let Zt={progress_callback:ye,config:Oe,cache_dir:ke,local_files_only:Ye,revision:tt,model_file_name:_t,subfolder:Tt,device:Lt,dtype:Wt,use_external_data_format:Dt,session_options:Vt};const rs=C.get(this),qt=$.get(rs);Oe=Zt.config=await f.AutoConfig.from_pretrained(N,Zt);let is;if(qt===F.DecoderOnly)is=await Promise.all([ee(N,{model:Zt.model_file_name??"model"},Zt),Y(N,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.Seq2Seq||qt===F.Vision2Seq)is=await Promise.all([ee(N,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt),Y(N,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.MaskGeneration)is=await Promise.all([ee(N,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Zt)]);else if(qt===F.EncoderDecoder)is=await Promise.all([ee(N,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt)]);else if(qt===F.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"),is=await Promise.all([ee(N,Cs,Zt),Y(N,{generation_config:"generation_config.json"},Zt)])}else if(qt===F.Musicgen)is=await Promise.all([ee(N,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Zt),Y(N,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.MultiModality)is=await Promise.all([ee(N,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},Zt),Y(N,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.Phi3V)is=await Promise.all([ee(N,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},Zt),Y(N,{generation_config:"generation_config.json"},Zt)]);else{if(qt!==F.EncoderOnly){const Cs=rs??(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 ${v.GITHUB_ISSUE_URL}.`)}is=await Promise.all([ee(N,{model:Zt.model_file_name??"model"},Zt)])}return new this(Oe,...is)}async _call(N){return await this.forward(N)}async forward(N){return await this._forward(this,N)}get generation_config(){var N;return((N=this.configs)==null?void 0:N.generation_config)??null}_get_logits_warper(N){const ye=new y.LogitsProcessorList;return N.temperature!==null&&N.temperature!==1&&ye.push(new y.TemperatureLogitsWarper(N.temperature)),N.top_k!==null&&N.top_k!==0&&ye.push(new y.TopKLogitsWarper(N.top_k)),N.top_p!==null&&N.top_p<1&&ye.push(new y.TopPLogitsWarper(N.top_p)),ye}_get_logits_processor(N,ye,Oe=null){const ke=new y.LogitsProcessorList;if(N.repetition_penalty!==null&&N.repetition_penalty!==1&&ke.push(new y.RepetitionPenaltyLogitsProcessor(N.repetition_penalty)),N.no_repeat_ngram_size!==null&&N.no_repeat_ngram_size>0&&ke.push(new y.NoRepeatNGramLogitsProcessor(N.no_repeat_ngram_size)),N.bad_words_ids!==null&&ke.push(new y.NoBadWordsLogitsProcessor(N.bad_words_ids,N.eos_token_id)),N.min_length!==null&&N.eos_token_id!==null&&N.min_length>0&&ke.push(new y.MinLengthLogitsProcessor(N.min_length,N.eos_token_id)),N.min_new_tokens!==null&&N.eos_token_id!==null&&N.min_new_tokens>0&&ke.push(new y.MinNewTokensLengthLogitsProcessor(ye,N.min_new_tokens,N.eos_token_id)),N.forced_bos_token_id!==null&&ke.push(new y.ForcedBOSTokenLogitsProcessor(N.forced_bos_token_id)),N.forced_eos_token_id!==null&&ke.push(new y.ForcedEOSTokenLogitsProcessor(N.max_length,N.forced_eos_token_id)),N.begin_suppress_tokens!==null){const Ye=ye>1||N.forced_bos_token_id===null?ye:ye+1;ke.push(new y.SuppressTokensAtBeginLogitsProcessor(N.begin_suppress_tokens,Ye))}return N.guidance_scale!==null&&N.guidance_scale>1&&ke.push(new y.ClassifierFreeGuidanceLogitsProcessor(N.guidance_scale)),Oe!==null&&ke.extend(Oe),ke}_prepare_generation_config(N,ye,Oe=M.GenerationConfig){const ke={...this.config};for(const tt of["decoder","generator","text_config"])tt in ke&&Object.assign(ke,ke[tt]);const Ye=new Oe(ke);return Object.assign(Ye,this.generation_config??{}),N&&Object.assign(Ye,N),ye&&Object.assign(Ye,(0,W.pick)(ye,Object.getOwnPropertyNames(Ye))),Ye}_get_stopping_criteria(N,ye=null){const Oe=new re.StoppingCriteriaList;return N.max_length!==null&&Oe.push(new re.MaxLengthCriteria(N.max_length,this.config.max_position_embeddings??null)),N.eos_token_id!==null&&Oe.push(new re.EosTokenCriteria(N.eos_token_id)),ye&&Oe.extend(ye),Oe}_validate_model_class(){if(!this.can_generate){const N=[Cn,Ai,Ld,sa],ye=C.get(this.constructor),Oe=new Set,ke=this.config.model_type;for(const tt of N){const _t=tt.get(ke);_t&&Oe.add(_t[0])}let Ye=`The current model class (${ye}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Oe.size>0&&(Ye+=` Please use the following class instead: ${[...Oe].join(", ")}`),Error(Ye)}}prepare_inputs_for_generation(...N){return this._prepare_inputs_for_generation(this,...N)}_update_model_kwargs_for_generation({generated_input_ids:N,outputs:ye,model_inputs:Oe,is_encoder_decoder:ke}){return Oe.past_key_values=this.getPastKeyValues(ye,Oe.past_key_values),Oe.input_ids=new b.Tensor("int64",N.flat(),[N.length,1]),ke||(Oe.attention_mask=(0,b.cat)([Oe.attention_mask,(0,b.ones)([Oe.attention_mask.dims[0],1])],1)),Oe.position_ids=null,Oe}_prepare_model_inputs({inputs:N,bos_token_id:ye,model_kwargs:Oe}){const ke=(0,W.pick)(Oe,this.forward_params),Ye=this.main_input_name;if(Ye in ke){if(N)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ke[Ye]=N;return{inputs_tensor:ke[Ye],model_inputs:ke,model_input_name:Ye}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:N,model_inputs:ye,model_input_name:Oe,generation_config:ke}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ye.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:tt,pixel_values:_t,attention_mask:Tt,...Lt}=ye,Wt=await this._prepare_inputs_embeds(ye);ye={...Lt,...(0,W.pick)(Wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ye}=await qe(this,ye);if(ke.guidance_scale!==null&&ke.guidance_scale>1)Ye=(0,b.cat)([Ye,(0,b.full_like)(Ye,0)],0),"attention_mask"in ye&&(ye.attention_mask=(0,b.cat)([ye.attention_mask,(0,b.zeros_like)(ye.attention_mask)],0));else if(ye.decoder_input_ids){const tt=Pe(ye.decoder_input_ids).dims[0];if(tt!==Ye.dims[0]){if(Ye.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ye.dims[0]}) than the decoder inputs (${tt}).`);Ye=(0,b.cat)(Array.from({length:tt},()=>Ye),0)}}return ye.encoder_outputs=Ye,ye}_prepare_decoder_input_ids_for_generation({batch_size:N,model_input_name:ye,model_kwargs:Oe,decoder_start_token_id:ke,bos_token_id:Ye,generation_config:tt}){let{decoder_input_ids:_t,...Tt}=Oe;if(!(_t instanceof b.Tensor)){if(_t)Array.isArray(_t[0])||(_t=Array.from({length:N},()=>_t));else if(ke??(ke=Ye),this.config.model_type==="musicgen")_t=Array.from({length:N*this.config.decoder.num_codebooks},()=>[ke]);else if(Array.isArray(ke)){if(ke.length!==N)throw new Error(`\`decoder_start_token_id\` expcted to have length ${N} but got ${ke.length}`);_t=ke}else _t=Array.from({length:N},()=>[ke]);_t=Pe(_t)}return Oe.decoder_attention_mask=(0,b.ones_like)(_t),{input_ids:_t,model_inputs:Tt}}async generate({inputs:N=null,generation_config:ye=null,logits_processor:Oe=null,stopping_criteria:ke=null,streamer:Ye=null,...tt}){this._validate_model_class(),ye=this._prepare_generation_config(ye,tt);let{inputs_tensor:_t,model_inputs:Tt,model_input_name:Lt}=this._prepare_model_inputs({inputs:N,model_kwargs:tt});const Wt=this.config.is_encoder_decoder;Wt&&("encoder_outputs"in Tt||(Tt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:_t,model_inputs:Tt,model_input_name:Lt,generation_config:ye})));let Dt;Wt?{input_ids:Dt,model_inputs:Tt}=this._prepare_decoder_input_ids_for_generation({batch_size:Tt[Lt].dims.at(0),model_input_name:Lt,model_kwargs:Tt,decoder_start_token_id:ye.decoder_start_token_id,bos_token_id:ye.bos_token_id,generation_config:ye}):Dt=Tt[Lt];let Vt=Dt.dims.at(-1);ye.max_new_tokens!==null&&(ye.max_length=Vt+ye.max_new_tokens);const Zt=this._get_logits_processor(ye,Vt,Oe),rs=this._get_stopping_criteria(ye,ke),qt=Tt[Lt].dims.at(0),is=ie.LogitsSampler.getSampler(ye),Cs=new Array(qt).fill(0),Es=Dt.tolist();Ye&&Ye.put(Es);let ds,ks={};for(;;){if(Tt=this.prepare_inputs_for_generation(Es,Tt,ye),ds=await this.forward(Tt),ye.output_attentions&&ye.return_dict_in_generate){const rr=this.getAttentions(ds);for(const Fr in rr)Fr in ks||(ks[Fr]=[]),ks[Fr].push(rr[Fr])}const Ws=ds.logits.slice(null,-1,null),wr=Zt(Es,Ws),kn=[];for(let rr=0;rrrr))break;Tt=this._update_model_kwargs_for_generation({generated_input_ids:kn,outputs:ds,model_inputs:Tt,is_encoder_decoder:Wt})}Ye&&Ye.end();const $s=this.getPastKeyValues(ds,Tt.past_key_values,!0),qs=new b.Tensor("int64",Es.flat(),[Es.length,Es[0].length]);if(ye.return_dict_in_generate)return{sequences:qs,past_key_values:$s,...ks};for(const Ws of Object.values(ds))Ws.location==="gpu-buffer"&&Ws.dispose();return qs}getPastKeyValues(N,ye,Oe=!1){const ke=Object.create(null);for(const Ye in N)if(Ye.startsWith("present")){const tt=Ye.replace("present","past_key_values"),_t=Ye.includes("encoder");if(_t&&ye?ke[tt]=ye[tt]:ke[tt]=N[Ye],ye&&(!_t||Oe)){const Tt=ye[tt];Tt.location==="gpu-buffer"&&Tt.dispose()}}return ke}getAttentions(N){const ye={};for(const Oe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const ke in N)ke.startsWith(Oe)&&(Oe in ye||(ye[Oe]=[]),ye[Oe].push(N[ke]));return ye}addPastKeyValues(N,ye){var Oe,ke,Ye;if(ye)Object.assign(N,ye);else{const tt=this.sessions.decoder_model_merged??this.sessions.model,_t=((Oe=tt==null?void 0:tt.config)==null?void 0:Oe.kv_cache_dtype)??"float32",Tt=_t==="float16"?new Uint16Array:[],Lt=((Ye=(ke=N[this.main_input_name]??N.attention_mask)==null?void 0:ke.dims)==null?void 0:Ye[0])??1,Wt=(0,f.getKeyValueShapes)(this.config,{batch_size:Lt});for(const Dt in Wt)N[Dt]=new b.Tensor(_t,Tt,Wt[Dt])}}async encode_image({pixel_values:N}){const ye=(await de(this.sessions.vision_encoder,{pixel_values:N})).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 (${ye.dims[1]}).`),this.config.num_image_tokens=ye.dims[1]),ye}async encode_text({input_ids:N}){return(await de(this.sessions.embed_tokens,{input_ids:N})).inputs_embeds}}class Je{}class Fe extends Je{constructor({last_hidden_state:x,hidden_states:N=null,attentions:ye=null}){super(),this.last_hidden_state=x,this.hidden_states=N,this.attentions=ye}}class pe extends oe{}class ve extends pe{}class Re extends pe{async _call(x){return new Us(await super._call(x))}}class We extends pe{async _call(x){return new Xt(await super._call(x))}}class Ve extends pe{async _call(x){return new js(await super._call(x))}}class Ne extends pe{async _call(x){return new Zs(await super._call(x))}}class Ze extends oe{}class at extends Ze{}class ft extends Ze{async _call(x){return new Us(await super._call(x))}}class lt extends Ze{async _call(x){return new Xt(await super._call(x))}}class ht extends Ze{async _call(x){return new js(await super._call(x))}}class I extends oe{}class ne extends I{}class K extends oe{}class ce extends K{}class Ie extends K{async _call(x){return new Us(await super._call(x))}}class Qe extends K{async _call(x){return new Xt(await super._call(x))}}class rt extends K{async _call(x){return new js(await super._call(x))}}class pt extends K{async _call(x){return new Zs(await super._call(x))}}class It extends oe{}class St extends It{}class Ft extends It{async _call(x){return new Us(await super._call(x))}}class At extends It{async _call(x){return new Xt(await super._call(x))}}class ns extends It{async _call(x){return new js(await super._call(x))}}class gs extends It{async _call(x){return new Zs(await super._call(x))}}class Ss extends oe{}class As extends Ss{}class Xs extends Ss{async _call(x){return new Us(await super._call(x))}}class ir extends Ss{async _call(x){return new Xt(await super._call(x))}}class Qr extends Ss{async _call(x){return new js(await super._call(x))}}class zr extends Ss{async _call(x){return new Zs(await super._call(x))}}class br extends oe{}class Nt extends br{}class Yr extends br{async _call(x){return new Us(await super._call(x))}}class kr extends br{async _call(x){return new Xt(await super._call(x))}}class Br extends br{async _call(x){return new js(await super._call(x))}}class Sr extends br{async _call(x){return new Zs(await super._call(x))}}class or extends oe{}class $r extends or{}class pr extends or{async _call(x){return new Us(await super._call(x))}}class Ar extends or{async _call(x){return new Xt(await super._call(x))}}class Jr extends or{async _call(x){return new js(await super._call(x))}}class ar extends or{async _call(x){return new Zs(await super._call(x))}}class nt extends oe{}class gt extends nt{}class Ot extends nt{async _call(x){return new Us(await super._call(x))}}class ls extends nt{async _call(x){return new Xt(await super._call(x))}}class vr extends nt{async _call(x){return new js(await super._call(x))}}class ts extends nt{async _call(x){return new Zs(await super._call(x))}}class er extends oe{}class Rr extends er{}class Zr extends er{async _call(x){return new Xt(await super._call(x))}}class Nr extends er{async _call(x){return new js(await super._call(x))}}class Tr extends er{async _call(x){return new Zs(await super._call(x))}}class An extends er{async _call(x){return new Us(await super._call(x))}}class jr extends oe{}class In extends jr{}class ni extends jr{async _call(x){return new Us(await super._call(x))}}class Wr extends jr{async _call(x){return new Xt(await super._call(x))}}class xr extends jr{async _call(x){return new js(await super._call(x))}}class lr extends oe{}class fn extends lr{}class en extends lr{async _call(x){return new Us(await super._call(x))}}class gn extends lr{async _call(x){return new Xt(await super._call(x))}}class tn extends lr{async _call(x){return new Zs(await super._call(x))}}class Er extends oe{}class zt extends Er{}class wn extends Er{async _call(x){return new Us(await super._call(x))}}class On extends Er{async _call(x){return new Xt(await super._call(x))}}class Fn extends Er{async _call(x){return new js(await super._call(x))}}class Dn extends Er{async _call(x){return new Zs(await super._call(x))}}class Ur extends oe{}class Ln extends Ur{}class yn extends Ur{async _call(x){return new Us(await super._call(x))}}class zn extends Ur{async _call(x){return new Xt(await super._call(x))}}class os extends Ur{async _call(x){return new Zs(await super._call(x))}}class Qs extends oe{}class Mn extends Qs{}class Bn extends Qs{async _call(x){return new Xt(await super._call(x))}}class bn extends Qs{async _call(x){return new Zs(await super._call(x))}}class vn extends Qs{async _call(x){return new Us(await super._call(x))}}class Ee extends oe{constructor(){super(...arguments);ge(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class P extends Ee{}class q extends Ee{}class ae extends oe{}class be extends ae{}class Ce extends ae{}class He extends oe{}class ct extends He{}class yt extends He{}class mt extends oe{}class ot extends mt{}class Pt extends mt{}class hs extends mt{async _call(x){return new Xt(await super._call(x))}}class ss extends oe{}class Se extends ss{}class ws extends ss{}class Rs extends ss{async _call(x){return new Xt(await super._call(x))}}class Ys extends ss{}class Js extends oe{}class Bt extends Js{}class Ns extends Js{}class hr extends oe{}class es extends hr{}class _s extends hr{}class vt extends oe{}class ys extends vt{}class Pr extends vt{async _call(x){return new Us(await super._call(x))}}class Ds extends vt{async _call(x){return new Xt(await super._call(x))}}class Hs extends vt{async _call(x){return new js(await super._call(x))}}class Mt extends vt{async _call(x){return new Zs(await super._call(x))}}class bs extends oe{}class Be extends bs{}class wt extends bs{async _call(x){return new Us(await super._call(x))}}class tr extends bs{async _call(x){return new Xt(await super._call(x))}}class sn extends bs{async _call(x){return new js(await super._call(x))}}class ii extends bs{async _call(x){return new Zs(await super._call(x))}}class Tn extends oe{}class Qt extends Tn{}class va extends Tn{async _call(x){return new Us(await super._call(x))}}class ji extends Tn{async _call(x){return new Xt(await super._call(x))}}class Ta extends Tn{async _call(x){return new js(await super._call(x))}}class xa extends Tn{async _call(x){return new Zs(await super._call(x))}}class Wi extends oe{}class Ea extends Wi{}class sr extends Wi{}class Ui extends oe{constructor(){super(...arguments);ge(this,"requires_attention_mask",!1);ge(this,"main_input_name","input_features");ge(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Pa extends Ui{}class Vr extends Ui{_prepare_generation_config(x,N){return super._prepare_generation_config(x,N,V.WhisperGenerationConfig)}_retrieve_init_tokens(x){const N=[x.decoder_start_token_id];let ye=x.language;const Oe=x.task;if(x.is_multilingual){ye||(console.warn("No language specified - defaulting to English (en)."),ye="en");const Ye=`<|${(0,Q.whisper_language_to_code)(ye)}|>`;N.push(x.lang_to_id[Ye]),N.push(x.task_to_id[Oe??"transcribe"])}else if(ye||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!x.return_timestamps&&x.no_timestamps_token_id&&N.at(-1)!==x.no_timestamps_token_id?N.push(x.no_timestamps_token_id):x.return_timestamps&&N.at(-1)===x.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),N.pop()),N.filter(ke=>ke!=null)}async generate({inputs:x=null,generation_config:N=null,logits_processor:ye=null,stopping_criteria:Oe=null,...ke}){N=this._prepare_generation_config(N,ke);const Ye=ke.decoder_input_ids??this._retrieve_init_tokens(N);if(N.return_timestamps&&(ye??(ye=new y.LogitsProcessorList),ye.push(new y.WhisperTimeStampLogitsProcessor(N,Ye))),N.begin_suppress_tokens&&(ye??(ye=new y.LogitsProcessorList),ye.push(new y.SuppressTokensAtBeginLogitsProcessor(N.begin_suppress_tokens,Ye.length))),N.return_token_timestamps){if(!N.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.");N.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),N.output_attentions=!0,N.return_dict_in_generate=!0}const tt=await super.generate({inputs:x,generation_config:N,logits_processor:ye,decoder_input_ids:Ye,...ke});return N.return_token_timestamps&&(tt.token_timestamps=this._extract_token_timestamps(tt,N.alignment_heads,N.num_frames)),tt}_extract_token_timestamps(x,N,ye=null,Oe=.02){if(!x.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`.");ye==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let ke=this.config.median_filter_width;ke===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ke=7);const Ye=x.cross_attentions,tt=Array.from({length:this.config.decoder_layers},(rs,qt)=>(0,b.cat)(Ye.map(is=>is[qt]),2)),_t=(0,b.stack)(N.map(([rs,qt])=>{if(rs>=tt.length)throw new Error(`Layer index ${rs} is out of bounds for cross attentions (length ${tt.length}).`);return ye?tt[rs].slice(null,qt,null,[0,ye]):tt[rs].slice(null,qt)})).transpose(1,0,2,3),[Tt,Lt]=(0,b.std_mean)(_t,-2,0,!0),Wt=_t.clone();for(let rs=0;rsis[qs+1]-is[qs]),ds=(0,W.mergeArrays)([1],Es).map($s=>!!$s),ks=[];for(let $s=0;$sDt.findIndex(Vt=>Vt==ke)),_t=tt.every(Dt=>Dt===-1),Tt=tt.every(Dt=>Dt!==-1);if(!_t&&!Tt)throw new Error("Every input should contain either 0 or 1 image token.");if(_t)return{inputs_embeds:x,attention_mask:Oe};const Lt=[],Wt=[];for(let Dt=0;DtArray.from({length:x.dims[0]},Es=>Array.from({length:x.dims[1]},ds=>1))),Zt=N?N.tolist():[],rs=ye?ye.tolist():[];let qt=0,is=0;for(let Cs=0;CsDt[Cs][Is]==1),ks=Es.reduce((Ts,Is,qr)=>(Is==_t&&Ts.push(qr),Ts),[]).map(Ts=>Es[Ts+1]),$s=ks.filter(Ts=>Ts==Ye).length,qs=ks.filter(Ts=>Ts==tt).length;let Ws=[],wr=0,kn=$s,pa=qs;for(let Ts=0;Tscr>wr&&Dr==Ye),qr=Es.findIndex((Dr,cr)=>cr>wr&&Dr==tt),un=kn>0&&Is!==-1?Is:Es.length+1,Kn=pa>0&&qr!==-1?qr:Es.length+1;let Hn,ma,_a,Tc;un0?(0,H.max)(Ws.at(-1))[0]+1:0;Ws.push(Array.from({length:3*fa},(Dr,cr)=>wp+cr%fa));const ga=fa+wp,Xn=gp*qn*Fi,xc=Array.from({length:Xn},(Dr,cr)=>ga+Math.floor(cr/(qn*Fi))),dn=Array.from({length:Xn},(Dr,cr)=>ga+Math.floor(cr/Fi)%qn),yp=Array.from({length:Xn},(Dr,cr)=>ga+cr%Fi);Ws.push([xc,dn,yp].flat()),wr=Hn+Xn}if(wr0?(0,H.max)(Ws.at(-1))[0]+1:0,Is=Es.length-wr;Ws.push(Array.from({length:3*Is},(qr,un)=>Ts+un%Is))}const rr=Ws.reduce((Ts,Is)=>Ts+Is.length,0),Fr=new Array(rr);let ha=0;for(let Ts=0;Ts<3;++Ts)for(let Is=0;IsWt[qt%Wt.length]),Zt=Array.from({length:Dt[0]},(rs,qt)=>(0,H.max)(Wt.subarray(Dt[1]*qt,Dt[1]*(qt+1)))[0]+1n+BigInt(Dt[1]));return[new b.Tensor("int64",Vt,[3,...Dt]),new b.Tensor("int64",Zt,[Zt.length,1])]}else{const[Wt,Dt]=x.dims,Vt=BigInt64Array.from({length:3*Wt*Dt},(Zt,rs)=>BigInt(Math.floor(rs%Dt/Wt)));return[new b.Tensor("int64",Vt,[3,...x.dims]),(0,b.zeros)([Wt,1])]}}async encode_image({pixel_values:x,image_grid_thw:N}){return(await de(this.sessions.vision_encoder,{pixel_values:x,grid_thw:N})).image_features}_merge_input_ids_with_image_features(x){return dt({image_token_id:this.config.image_token_id,...x})}prepare_inputs_for_generation(x,N,ye){if(N.attention_mask&&!N.position_ids)if(!N.past_key_values)[N.position_ids,N.rope_deltas]=this.get_rope_index(N.input_ids,N.image_grid_thw,N.video_grid_thw,N.attention_mask);else{N.pixel_values=null;const Oe=BigInt(Object.values(N.past_key_values)[0].dims.at(-2)),ke=N.rope_deltas.map(Ye=>Oe+Ye);N.position_ids=(0,b.stack)([ke,ke,ke],0)}return N}}class mo extends oe{}class vl extends mo{}class Tl extends mo{}class _o extends oe{}class xl extends _o{}class El extends _o{}class fo extends oe{}class Pl extends fo{}class Cl extends fo{}class go extends oe{}class kl extends go{}class Sl extends go{}class wo extends oe{}class $l extends wo{}class Al extends wo{}class yo extends oe{}class Mo extends yo{}class Il extends yo{async _call(x){return new Xt(await super._call(x))}}class pi extends oe{}class bo extends pi{}class Ol extends pi{async _call(x){return new Xt(await super._call(x))}}class Fl extends oe{}class Dl extends Fl{}class vo extends oe{}class Ll extends vo{}class zl extends vo{async _call(x){return new Xt(await super._call(x))}}class To extends oe{}class Bl extends To{}class xo extends oe{}class Rl extends xo{}class Bc extends xo{async _call(x){return new Xt(await super._call(x))}}class Nl extends oe{}class jl extends Nl{}class dr extends oe{}class Wl extends dr{}class Ul extends dr{async _call(x){return new Xt(await super._call(x))}}class Vl extends oe{}class Gl extends Vl{async _call(x){return new vc(await super._call(x))}}class Eo extends oe{}class Kl extends Eo{}class Hl extends Eo{async _call(x){return new Xt(await super._call(x))}}class Po extends oe{}class ql extends Po{}class Xl extends Po{async _call(x){return new Xt(await super._call(x))}}class Ql extends oe{}class Yl extends Ql{}class Jl extends Ql{}class Co extends oe{}class Zl extends Co{}class eu extends Co{}class ko extends oe{}class Rc extends ko{}class nn extends ko{async _call(x){return new Xt(await super._call(x))}}class Ir extends oe{}class on extends Ir{}class So extends Ir{async _call(x){return new Vs(await super._call(x))}}class Gr extends Ir{async _call(x){return new tu(await super._call(x))}}class Vs extends Je{constructor({logits:x,pred_boxes:N}){super(),this.logits=x,this.pred_boxes=N}}class tu extends Je{constructor({logits:x,pred_boxes:N,pred_masks:ye}){super(),this.logits=x,this.pred_boxes=N,this.pred_masks=ye}}class hi extends oe{}class su extends hi{}class Nc extends hi{async _call(x){return new Nn(await super._call(x))}}class Nn extends Je{constructor({logits:x,pred_boxes:N}){super(),this.logits=x,this.pred_boxes=N}}class mi extends oe{}class $o extends mi{}class ru extends mi{async _call(x){return new nu(await super._call(x))}}class nu extends Vs{}class _i extends oe{}class Ao extends _i{}class iu extends _i{async _call(x){return new Xt(await super._call(x))}}class fi extends oe{}class ou extends fi{}class gi extends fi{async _call(x){return new Xt(await super._call(x))}}class wi extends oe{}class au extends wi{}class lu extends wi{async _call(x){return new Xt(await super._call(x))}}class uu extends oe{}class du extends uu{}class Io extends uu{async _call(x){return new Xt(await super._call(x))}}class En extends oe{}class cu extends En{}class Oo extends En{}class Fo extends oe{}class pu extends Fo{}class hu extends Fo{}class jc extends oe{}class mu extends jc{}class yi extends oe{}class Wc extends yi{}class _u extends yi{}class Mi extends yi{}class fu extends oe{}class bi extends fu{}class vi extends oe{}class Do extends vi{}class gu extends vi{}class Lo extends oe{}class zo extends Lo{}class Uc extends Lo{}class wu extends oe{}class Vc extends wu{}class Bo extends oe{}class yu extends Bo{}class Mu extends Bo{async _call(x){return new Xt(await super._call(x))}}class Ti extends oe{}class bu extends Ti{}class vu extends Ti{async _call(x){return new Xt(await super._call(x))}}class xi extends oe{}class Tu extends xi{}class xu extends xi{async _call(x){return new Xt(await super._call(x))}}class Eu extends oe{}class Pu extends Eu{}class Cu extends Eu{async _call(x){return new Xt(await super._call(x))}}class Ro extends oe{}class Gc extends Ro{}class ku extends Ro{async _call(x){return new Su(await super._call(x))}}class Su extends Je{constructor({logits:x,pred_boxes:N}){super(),this.logits=x,this.pred_boxes=N}}class $u extends oe{}class Au extends $u{async get_image_embeddings({pixel_values:x}){return await qe(this,{pixel_values:x})}async forward(x){if((!x.image_embeddings||!x.image_positional_embeddings)&&(x={...x,...await this.get_image_embeddings(x)}),!x.input_labels&&x.input_points){const ye=x.input_points.dims.slice(0,-1),Oe=ye.reduce((ke,Ye)=>ke*Ye,1);x.input_labels=new b.Tensor("int64",new BigInt64Array(Oe).fill(1n),ye)}const N={image_embeddings:x.image_embeddings,image_positional_embeddings:x.image_positional_embeddings};return x.input_points&&(N.input_points=x.input_points),x.input_labels&&(N.input_labels=x.input_labels),x.input_boxes&&(N.input_boxes=x.input_boxes),await de(this.sessions.prompt_encoder_mask_decoder,N)}async _call(x){return new Iu(await super._call(x))}}class Iu extends Je{constructor({iou_scores:x,pred_masks:N}){super(),this.iou_scores=x,this.pred_masks=N}}class Ou extends oe{}class Ei extends Ou{}class jn extends Ou{}class Pi extends oe{}class Fu extends Pi{}class Du extends Pi{}class Kr extends oe{}class Lu extends Kr{}class No extends Kr{async _call(x){return new ln(await super._call(x))}}class zu extends Kr{async _call(x){return new Xt(await super._call(x))}}class Bu extends Kr{async _call(x){return new js(await super._call(x))}}class jo extends oe{}class Kc extends jo{}class Ru extends jo{async _call(x){return new js(await super._call(x))}}class Wo extends oe{}class Nu extends Wo{}class Ci extends oe{}class ju extends Ci{}class Hc extends Ci{async _call(x){return new ln(await super._call(x))}}class Wu extends Ci{async _call(x){return new Xt(await super._call(x))}}class Wn extends oe{}class qc extends Wn{}class Uu extends Wn{async _call(x){return new ln(await super._call(x))}}class Vu extends Wn{async _call(x){return new Xt(await super._call(x))}}class Gu extends Wn{async _call(x){return new js(await super._call(x))}}class ki extends oe{}class Xc extends ki{}class Ku extends ki{async _call(x){return new ln(await super._call(x))}}class Hu extends ki{async _call(x){return new Xt(await super._call(x))}}class Qc extends oe{}class Yc extends Kr{}class qu extends Kr{async _call(x){return new ln(await super._call(x))}}class Xu extends Kr{async _call(x){return new Xt(await super._call(x))}}class Pn extends oe{}class Qu extends Pn{}class Jc extends Pn{async _call(x){return new ln(await super._call(x))}}class Yu extends Pn{async _call(x){return new Xt(await super._call(x))}}class Ju extends Pn{async _call(x){return new bc(await super._call(x))}}class Zu extends Pn{async _call(x){return new js(await super._call(x))}}class Si extends oe{}class zp extends Si{}class ed extends Si{}class td extends Si{async generate_speech(x,N,{threshold:ye=.5,minlenratio:Oe=0,maxlenratio:ke=20,vocoder:Ye=null}={}){const tt={input_ids:x},{encoder_outputs:_t,encoder_attention_mask:Tt}=await qe(this,tt),Lt=_t.dims[1]/this.config.reduction_factor,Wt=Math.floor(Lt*ke),Dt=Math.floor(Lt*Oe),Vt=this.config.num_mel_bins;let Zt=[],rs=null,qt=null,is=0;for(;;){++is;const ds=xe(!!qt);let ks;qt?ks=qt.output_sequence_out:ks=new b.Tensor("float32",new Float32Array(Vt),[1,1,Vt]);let $s={use_cache_branch:ds,output_sequence:ks,encoder_attention_mask:Tt,speaker_embeddings:N,encoder_hidden_states:_t};this.addPastKeyValues($s,rs),qt=await de(this.sessions.decoder_model_merged,$s),rs=this.getPastKeyValues(qt,rs);const{prob:qs,spectrum:Ws}=qt;if(Zt.push(Ws),is>=Dt&&(Array.from(qs.data).filter(wr=>wr>=ye).length>0||is>=Wt))break}const Cs=(0,b.cat)(Zt),{waveform:Es}=await de(Ye.sessions.model,{spectrogram:Cs});return{spectrogram:Cs,waveform:Es}}}class sd extends oe{constructor(){super(...arguments);ge(this,"main_input_name","spectrogram")}}class rd extends oe{}class Zc extends rd{}class gr extends oe{}class Or extends gr{}class an extends gr{}class Hr extends oe{}class nd extends Hr{}class id extends Hr{}class Uo extends oe{}class od extends Uo{}class ad extends Uo{}class $i extends oe{}class ld extends $i{}class ud extends $i{static async from_pretrained(x,N={}){return super.from_pretrained(x,{...N,model_file_name:N.model_file_name??"text_model"})}}class dd extends $i{static async from_pretrained(x,N={}){return super.from_pretrained(x,{...N,model_file_name:N.model_file_name??"audio_model"})}}class cd extends oe{}class pd extends cd{async _call(x){return new ca(await super._call(x))}}class Gs extends oe{}class ep extends Gs{}class hd extends Gs{}class Vo extends Gs{}class Go extends oe{}class Un extends Go{}class md extends Go{}class Ko extends oe{}class _d extends Ko{}class fd extends Ko{async _call(x){return new Xt(await super._call(x))}}class Ho extends oe{}class tp extends Ho{}class gd extends Ho{}class qo extends oe{constructor(){super(...arguments);ge(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(N){const[ye,Oe]=N.dims,ke=this.config.decoder.num_codebooks,Ye=Oe-ke;let tt=0;for(let Lt=0;Lt0&&Vt<=Ye&&(N.data[tt++]=N.data[Lt])}const _t=Math.floor(ye/ke),Tt=tt/(_t*ke);return new b.Tensor(N.type,N.data.slice(0,tt),[_t,ke,Tt])}prepare_inputs_for_generation(N,ye,Oe){let ke=structuredClone(N);for(let tt=0;tt=_t&&(ke[tt][_t]=BigInt(this.config.decoder.pad_token_id));return Oe.guidance_scale!==null&&Oe.guidance_scale>1&&(ke=ke.concat(ke)),super.prepare_inputs_for_generation(ke,ye,Oe)}async generate(N){const ye=await super.generate(N),Oe=this._apply_and_filter_by_delay_pattern_mask(ye).unsqueeze_(0),{audio_values:ke}=await de(this.sessions.encodec_decode,{audio_codes:Oe});return ke}}class Xo extends oe{}class wd extends Xo{}class yd extends Xo{async _call(x){return new Xt(await super._call(x))}}class Qo extends oe{}class Yo extends Qo{}class Md extends Qo{async _call(x){return new Xt(await super._call(x))}}class bd extends oe{}class Jo extends bd{}class vd extends bd{async _call(x){return new Xt(await super._call(x))}}class Zo extends oe{}class Td extends Zo{}class sp extends Zo{async _call(x){return new Xt(await super._call(x))}}class xd extends oe{}class Ed extends xd{}class Pd extends oe{}class rp extends Pd{constructor(...N){super(...N);ge(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(N){const ye=this._generation_mode??"text";let Oe;if(ye==="text"||!N.past_key_values){const Tt=this.sessions.prepare_inputs_embeds,Lt=(0,W.pick)(N,Tt.inputNames);Oe=await de(Tt,Lt)}else{const Tt=this.sessions.gen_img_embeds,Lt=(0,W.pick)({image_ids:N.input_ids},Tt.inputNames);Oe=await de(Tt,Lt)}const ke={...N,...Oe},Ye=await je(this,ke),tt=this.sessions[ye==="text"?"lm_head":"gen_head"];if(!tt)throw new Error(`Unable to find "${tt}" generation head`);const _t=await de(tt,(0,W.pick)(Ye,tt.inputNames));return{...Oe,...Ye,..._t}}async generate(N){return this._generation_mode="text",super.generate(N)}async generate_images(N){this._generation_mode="image";const ye=(N.inputs??N[this.main_input_name]).dims[1],ke=(await super.generate(N)).slice(null,[ye,null]),Ye=this.sessions.image_decode,{decoded_image:tt}=await de(Ye,{generated_tokens:ke}),_t=tt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Tt=[];for(const Lt of _t){const Wt=D.RawImage.fromTensor(Lt);Tt.push(Wt)}return Tt}}class Cd extends Je{constructor({char_logits:x,bpe_logits:N,wp_logits:ye}){super(),this.char_logits=x,this.bpe_logits=N,this.wp_logits=ye}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class kd extends oe{}class np extends kd{async _call(x){return new Cd(await super._call(x))}}class ea extends oe{}class Sd extends ea{}class $d extends ea{}class ta extends oe{}class Ad extends ta{}class ip extends ta{}class fs{static async from_pretrained(x,{progress_callback:N=null,config:ye=null,cache_dir:Oe=null,local_files_only:ke=!1,revision:Ye="main",model_file_name:tt=null,subfolder:_t="onnx",device:Tt=null,dtype:Lt=null,use_external_data_format:Wt=null,session_options:Dt={}}={}){const Vt={progress_callback:N,config:ye,cache_dir:Oe,local_files_only:ke,revision:Ye,model_file_name:tt,subfolder:_t,device:Tt,dtype:Lt,use_external_data_format:Wt,session_options:Dt};if(Vt.config=await f.AutoConfig.from_pretrained(x,Vt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Zt of this.MODEL_CLASS_MAPPINGS){const rs=Zt.get(Vt.config.model_type);if(rs)return await rs[1].from_pretrained(x,Vt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Vt.config.model_type}", attempting to construct from base class.`),await oe.from_pretrained(x,Vt);throw Error(`Unsupported model type: ${Vt.config.model_type}`)}}ge(fs,"MODEL_CLASS_MAPPINGS",null),ge(fs,"BASE_IF_FAIL",!1);const op=new Map([["bert",["BertModel",ve]],["modernbert",["ModernBertModel",at]],["nomic_bert",["NomicBertModel",ne]],["roformer",["RoFormerModel",ce]],["electra",["ElectraModel",As]],["esm",["EsmModel",In]],["convbert",["ConvBertModel",St]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",$r]],["deberta-v2",["DebertaV2Model",gt]],["mpnet",["MPNetModel",zt]],["albert",["AlbertModel",Mn]],["distilbert",["DistilBertModel",Rr]],["roberta",["RobertaModel",ys]],["xlm",["XLMModel",Be]],["xlm-roberta",["XLMRobertaModel",Qt]],["clap",["ClapModel",ld]],["clip",["CLIPModel",La]],["clipseg",["CLIPSegModel",Ua]],["chinese_clip",["ChineseCLIPModel",Ra]],["siglip",["SiglipModel",Ba]],["jina_clip",["JinaCLIPModel",Na]],["mobilebert",["MobileBertModel",fn]],["squeezebert",["SqueezeBertModel",Ln]],["wav2vec2",["Wav2Vec2Model",Lu]],["wav2vec2-bert",["Wav2Vec2BertModel",Xc]],["unispeech",["UniSpeechModel",ju]],["unispeech-sat",["UniSpeechSatModel",qc]],["hubert",["HubertModel",Yc]],["wavlm",["WavLMModel",Qu]],["audio-spectrogram-transformer",["ASTModel",Ea]],["vits",["VitsModel",pd]],["pyannote",["PyAnnoteModel",Kc]],["wespeaker-resnet",["WeSpeakerResNetModel",Nu]],["detr",["DetrModel",on]],["rt_detr",["RTDetrModel",su]],["table-transformer",["TableTransformerModel",$o]],["vit",["ViTModel",Mo]],["ijepa",["IJepaModel",bo]],["pvt",["PvtModel",Ll]],["vit_msn",["ViTMSNModel",Rl]],["vit_mae",["ViTMAEModel",Bl]],["groupvit",["GroupViTModel",jl]],["fastvit",["FastViTModel",Wl]],["mobilevit",["MobileViTModel",Kl]],["mobilevitv2",["MobileViTV2Model",ql]],["owlvit",["OwlViTModel",Yl]],["owlv2",["Owlv2Model",Zl]],["beit",["BeitModel",Rc]],["deit",["DeiTModel",Ao]],["hiera",["HieraModel",ou]],["convnext",["ConvNextModel",yu]],["convnextv2",["ConvNextV2Model",bu]],["dinov2",["Dinov2Model",Tu]],["dinov2_with_registers",["Dinov2WithRegistersModel",Pu]],["resnet",["ResNetModel",au]],["swin",["SwinModel",du]],["swin2sr",["Swin2SRModel",cu]],["donut-swin",["DonutSwinModel",Vc]],["yolos",["YolosModel",Gc]],["dpt",["DPTModel",pu]],["glpn",["GLPNModel",zo]],["hifigan",["SpeechT5HifiGan",sd]],["efficientnet",["EfficientNetModel",_d]],["decision_transformer",["DecisionTransformerModel",Ed]],["patchtst",["PatchTSTForPrediction",Sd]],["patchtsmixer",["PatchTSMixerForPrediction",Ad]],["mobilenet_v1",["MobileNetV1Model",wd]],["mobilenet_v2",["MobileNetV2Model",Yo]],["mobilenet_v3",["MobileNetV3Model",Jo]],["mobilenet_v4",["MobileNetV4Model",Td]],["maskformer",["MaskFormerModel",Do]],["mgp-str",["MgpstrForSceneTextRecognition",np]]]),ap=new Map([["t5",["T5Model",P]],["longt5",["LongT5Model",be]],["mt5",["MT5Model",ct]],["bart",["BartModel",ot]],["mbart",["MBartModel",Se]],["marian",["MarianModel",Ei]],["whisper",["WhisperModel",Pa]],["m2m_100",["M2M100Model",Fu]],["blenderbot",["BlenderbotModel",Bt]],["blenderbot-small",["BlenderbotSmallModel",es]]]),lp=new Map([["bloom",["BloomModel",Pl]],["jais",["JAISModel",Ka]],["gpt2",["GPT2Model",Ga]],["gptj",["GPTJModel",to]],["gpt_bigcode",["GPTBigCodeModel",Ja]],["gpt_neo",["GPTNeoModel",qa]],["gpt_neox",["GPTNeoXModel",Qa]],["codegen",["CodeGenModel",el]],["llama",["LlamaModel",tl]],["exaone",["ExaoneModel",rl]],["olmo",["OlmoModel",al]],["olmo2",["Olmo2Model",ll]],["mobilellm",["MobileLLMModel",il]],["granite",["GraniteModel",cl]],["cohere",["CohereModel",pl]],["gemma",["GemmaModel",ml]],["gemma2",["Gemma2Model",fl]],["openelm",["OpenELMModel",wl]],["qwen2",["Qwen2Model",Ml]],["phi",["PhiModel",vl]],["phi3",["Phi3Model",xl]],["mpt",["MptModel",kl]],["opt",["OPTModel",$l]],["mistral",["MistralModel",Or]],["starcoder2",["Starcoder2Model",nd]],["falcon",["FalconModel",od]],["stablelm",["StableLmModel",Un]]]),sa=new Map([["speecht5",["SpeechT5ForSpeechToText",ed]],["whisper",["WhisperForConditionalGeneration",Vr]],["moonshine",["MoonshineForConditionalGeneration",Ca]]]),Id=new Map([["speecht5",["SpeechT5ForTextToSpeech",td]]]),Od=new Map([["vits",["VitsModel",pd]],["musicgen",["MusicgenForConditionalGeneration",qo]]]),Fd=new Map([["bert",["BertForSequenceClassification",We]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",ir]],["esm",["EsmForSequenceClassification",Wr]],["convbert",["ConvBertForSequenceClassification",At]],["camembert",["CamembertForSequenceClassification",kr]],["deberta",["DebertaForSequenceClassification",Ar]],["deberta-v2",["DebertaV2ForSequenceClassification",ls]],["mpnet",["MPNetForSequenceClassification",On]],["albert",["AlbertForSequenceClassification",Bn]],["distilbert",["DistilBertForSequenceClassification",Zr]],["roberta",["RobertaForSequenceClassification",Ds]],["xlm",["XLMForSequenceClassification",tr]],["xlm-roberta",["XLMRobertaForSequenceClassification",ji]],["bart",["BartForSequenceClassification",hs]],["mbart",["MBartForSequenceClassification",Rs]],["mobilebert",["MobileBertForSequenceClassification",gn]],["squeezebert",["SqueezeBertForSequenceClassification",zn]]]),Dd=new Map([["bert",["BertForTokenClassification",Ve]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",rt]],["electra",["ElectraForTokenClassification",Qr]],["esm",["EsmForTokenClassification",xr]],["convbert",["ConvBertForTokenClassification",ns]],["camembert",["CamembertForTokenClassification",Br]],["deberta",["DebertaForTokenClassification",Jr]],["deberta-v2",["DebertaV2ForTokenClassification",vr]],["mpnet",["MPNetForTokenClassification",Fn]],["distilbert",["DistilBertForTokenClassification",Nr]],["roberta",["RobertaForTokenClassification",Hs]],["xlm",["XLMForTokenClassification",sn]],["xlm-roberta",["XLMRobertaForTokenClassification",Ta]]]),Ld=new Map([["t5",["T5ForConditionalGeneration",q]],["longt5",["LongT5ForConditionalGeneration",Ce]],["mt5",["MT5ForConditionalGeneration",yt]],["bart",["BartForConditionalGeneration",Pt]],["mbart",["MBartForConditionalGeneration",ws]],["marian",["MarianMTModel",jn]],["m2m_100",["M2M100ForConditionalGeneration",Du]],["blenderbot",["BlenderbotForConditionalGeneration",Ns]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",_s]]]),Cn=new Map([["bloom",["BloomForCausalLM",Cl]],["gpt2",["GPT2LMHeadModel",fr]],["jais",["JAISLMHeadModel",Ha]],["gptj",["GPTJForCausalLM",so]],["gpt_bigcode",["GPTBigCodeForCausalLM",no]],["gpt_neo",["GPTNeoForCausalLM",Xa]],["gpt_neox",["GPTNeoXForCausalLM",Ya]],["codegen",["CodeGenForCausalLM",ui]],["llama",["LlamaForCausalLM",sl]],["exaone",["ExaoneForCausalLM",nl]],["olmo",["OlmoForCausalLM",zc]],["olmo2",["Olmo2ForCausalLM",ul]],["mobilellm",["MobileLLMForCausalLM",ol]],["granite",["GraniteForCausalLM",us]],["cohere",["CohereForCausalLM",hl]],["gemma",["GemmaForCausalLM",_l]],["gemma2",["Gemma2ForCausalLM",gl]],["openelm",["OpenELMForCausalLM",yl]],["qwen2",["Qwen2ForCausalLM",Rn]],["phi",["PhiForCausalLM",Tl]],["phi3",["Phi3ForCausalLM",El]],["mpt",["MptForCausalLM",Sl]],["opt",["OPTForCausalLM",Al]],["mbart",["MBartForCausalLM",Ys]],["mistral",["MistralForCausalLM",an]],["starcoder2",["Starcoder2ForCausalLM",id]],["falcon",["FalconForCausalLM",ad]],["trocr",["TrOCRForCausalLM",Zc]],["stablelm",["StableLmForCausalLM",md]],["phi3_v",["Phi3VForCausalLM",Hi]]]),zd=new Map([["multi_modality",["MultiModalityCausalLM",rp]]]),ra=new Map([["bert",["BertForMaskedLM",Re]],["modernbert",["ModernBertForMaskedLM",ft]],["roformer",["RoFormerForMaskedLM",Ie]],["electra",["ElectraForMaskedLM",Xs]],["esm",["EsmForMaskedLM",ni]],["convbert",["ConvBertForMaskedLM",Ft]],["camembert",["CamembertForMaskedLM",Yr]],["deberta",["DebertaForMaskedLM",pr]],["deberta-v2",["DebertaV2ForMaskedLM",Ot]],["mpnet",["MPNetForMaskedLM",wn]],["albert",["AlbertForMaskedLM",vn]],["distilbert",["DistilBertForMaskedLM",An]],["roberta",["RobertaForMaskedLM",Pr]],["xlm",["XLMWithLMHeadModel",wt]],["xlm-roberta",["XLMRobertaForMaskedLM",va]],["mobilebert",["MobileBertForMaskedLM",en]],["squeezebert",["SqueezeBertForMaskedLM",yn]]]),na=new Map([["bert",["BertForQuestionAnswering",Ne]],["roformer",["RoFormerForQuestionAnswering",pt]],["electra",["ElectraForQuestionAnswering",zr]],["convbert",["ConvBertForQuestionAnswering",gs]],["camembert",["CamembertForQuestionAnswering",Sr]],["deberta",["DebertaForQuestionAnswering",ar]],["deberta-v2",["DebertaV2ForQuestionAnswering",ts]],["mpnet",["MPNetForQuestionAnswering",Dn]],["albert",["AlbertForQuestionAnswering",bn]],["distilbert",["DistilBertForQuestionAnswering",Tr]],["roberta",["RobertaForQuestionAnswering",Mt]],["xlm",["XLMForQuestionAnswering",ii]],["xlm-roberta",["XLMRobertaForQuestionAnswering",xa]],["mobilebert",["MobileBertForQuestionAnswering",tn]],["squeezebert",["SqueezeBertForQuestionAnswering",os]]]),Ai=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Gi]],["idefics3",["Idefics3ForConditionalGeneration",Ki]]]),up=new Map([["llava",["LlavaForConditionalGeneration",oi]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Sa]],["moondream1",["Moondream1ForConditionalGeneration",$a]],["florence2",["Florence2ForConditionalGeneration",Ia]],["qwen2-vl",["Qwen2VLForConditionalGeneration",ci]],["idefics3",["Idefics3ForConditionalGeneration",Ki]],["paligemma",["PaliGemmaForConditionalGeneration",Oa]]]),dp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Gi]]]),ia=new Map([["vit",["ViTForImageClassification",Il]],["ijepa",["IJepaForImageClassification",Ol]],["pvt",["PvtForImageClassification",zl]],["vit_msn",["ViTMSNForImageClassification",Bc]],["fastvit",["FastViTForImageClassification",Ul]],["mobilevit",["MobileViTForImageClassification",Hl]],["mobilevitv2",["MobileViTV2ForImageClassification",Xl]],["beit",["BeitForImageClassification",nn]],["deit",["DeiTForImageClassification",iu]],["hiera",["HieraForImageClassification",gi]],["convnext",["ConvNextForImageClassification",Mu]],["convnextv2",["ConvNextV2ForImageClassification",vu]],["dinov2",["Dinov2ForImageClassification",xu]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Cu]],["resnet",["ResNetForImageClassification",lu]],["swin",["SwinForImageClassification",Io]],["segformer",["SegformerForImageClassification",hd]],["efficientnet",["EfficientNetForImageClassification",fd]],["mobilenet_v1",["MobileNetV1ForImageClassification",yd]],["mobilenet_v2",["MobileNetV2ForImageClassification",Md]],["mobilenet_v3",["MobileNetV3ForImageClassification",vd]],["mobilenet_v4",["MobileNetV4ForImageClassification",sp]]]),oa=new Map([["detr",["DetrForObjectDetection",So]],["rt_detr",["RTDetrForObjectDetection",Nc]],["table-transformer",["TableTransformerForObjectDetection",ru]],["yolos",["YolosForObjectDetection",ku]]]),Bd=new Map([["owlvit",["OwlViTForObjectDetection",Jl]],["owlv2",["Owlv2ForObjectDetection",eu]]]),Rd=new Map([["detr",["DetrForSegmentation",Gr]],["clipseg",["CLIPSegForImageSegmentation",Va]]]),aa=new Map([["segformer",["SegformerForSemanticSegmentation",Vo]],["sapiens",["SapiensForSemanticSegmentation",Wc]]]),Nd=new Map([["detr",["DetrForSegmentation",Gr]],["maskformer",["MaskFormerForInstanceSegmentation",gu]]]),jd=new Map([["sam",["SamModel",Au]]]),la=new Map([["wav2vec2",["Wav2Vec2ForCTC",No]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ku]],["unispeech",["UniSpeechForCTC",Hc]],["unispeech-sat",["UniSpeechSatForCTC",Uu]],["wavlm",["WavLMForCTC",Jc]],["hubert",["HubertForCTC",qu]]]),Wd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",zu]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Hu]],["unispeech",["UniSpeechForSequenceClassification",Wu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Vu]],["wavlm",["WavLMForSequenceClassification",Yu]],["hubert",["HubertForSequenceClassification",Xu]],["audio-spectrogram-transformer",["ASTForAudioClassification",sr]]]),Ud=new Map([["wavlm",["WavLMForXVector",Ju]]]),Vd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Gu]],["wavlm",["WavLMForAudioFrameClassification",Zu]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Bu]],["pyannote",["PyAnnoteForAudioFrameClassification",Ru]]]),Gd=new Map([["vitmatte",["VitMatteForImageMatting",Gl]]]),Bp=new Map([["patchtst",["PatchTSTForPrediction",$d]],["patchtsmixer",["PatchTSMixerForPrediction",ip]]]),Kd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Oo]]]),Hd=new Map([["dpt",["DPTForDepthEstimation",hu]],["depth_anything",["DepthAnythingForDepthEstimation",mu]],["glpn",["GLPNForDepthEstimation",Uc]],["sapiens",["SapiensForDepthEstimation",_u]],["depth_pro",["DepthProForDepthEstimation",bi]]]),qd=new Map([["sapiens",["SapiensForNormalEstimation",Mi]]]),Xd=new Map([["vitpose",["VitPoseForPoseEstimation",Dl]]]),cp=new Map([["clip",["CLIPVisionModelWithProjection",Lc]],["siglip",["SiglipVisionModel",qi]],["jina_clip",["JinaCLIPVisionModel",Wa]]]),Qd=[[op,F.EncoderOnly],[ap,F.EncoderDecoder],[lp,F.DecoderOnly],[Fd,F.EncoderOnly],[Dd,F.EncoderOnly],[Ld,F.Seq2Seq],[sa,F.Seq2Seq],[Cn,F.DecoderOnly],[zd,F.MultiModality],[ra,F.EncoderOnly],[na,F.EncoderOnly],[Ai,F.Vision2Seq],[up,F.ImageTextToText],[ia,F.EncoderOnly],[Rd,F.EncoderOnly],[Nd,F.EncoderOnly],[aa,F.EncoderOnly],[Gd,F.EncoderOnly],[Bp,F.EncoderOnly],[Kd,F.EncoderOnly],[Hd,F.EncoderOnly],[qd,F.EncoderOnly],[Xd,F.EncoderOnly],[oa,F.EncoderOnly],[Bd,F.EncoderOnly],[jd,F.MaskGeneration],[la,F.EncoderOnly],[Wd,F.EncoderOnly],[Id,F.Seq2Seq],[Od,F.EncoderOnly],[Ud,F.EncoderOnly],[Vd,F.EncoderOnly],[cp,F.EncoderOnly]];for(const[_,x]of Qd)for(const[N,ye]of _.values())$.set(N,x),C.set(ye,N),g.set(N,ye);const pp=[["MusicgenForConditionalGeneration",qo,F.Musicgen],["Phi3VForCausalLM",Hi,F.Phi3V],["CLIPTextModelWithProjection",za,F.EncoderOnly],["SiglipTextModel",ai,F.EncoderOnly],["JinaCLIPTextModel",ja,F.EncoderOnly],["ClapTextModelWithProjection",ud,F.EncoderOnly],["ClapAudioModelWithProjection",dd,F.EncoderOnly]];for(const[_,x,N]of pp)$.set(_,N),C.set(x,_),g.set(_,x);class ua extends fs{}ge(ua,"MODEL_CLASS_MAPPINGS",Qd.map(x=>x[0])),ge(ua,"BASE_IF_FAIL",!0);class hp extends fs{}ge(hp,"MODEL_CLASS_MAPPINGS",[Fd]);class Yd extends fs{}ge(Yd,"MODEL_CLASS_MAPPINGS",[Dd]);class Jd extends fs{}ge(Jd,"MODEL_CLASS_MAPPINGS",[Ld]);class Zd extends fs{}ge(Zd,"MODEL_CLASS_MAPPINGS",[sa]);class ec extends fs{}ge(ec,"MODEL_CLASS_MAPPINGS",[Id]);class mp extends fs{}ge(mp,"MODEL_CLASS_MAPPINGS",[Od]);class tc extends fs{}ge(tc,"MODEL_CLASS_MAPPINGS",[Cn]);class sc extends fs{}ge(sc,"MODEL_CLASS_MAPPINGS",[ra]);class rc extends fs{}ge(rc,"MODEL_CLASS_MAPPINGS",[na]);class nc extends fs{}ge(nc,"MODEL_CLASS_MAPPINGS",[Ai]);class ic extends fs{}ge(ic,"MODEL_CLASS_MAPPINGS",[ia]);class oc extends fs{}ge(oc,"MODEL_CLASS_MAPPINGS",[Rd]);class ac extends fs{}ge(ac,"MODEL_CLASS_MAPPINGS",[aa]);class lc extends fs{}ge(lc,"MODEL_CLASS_MAPPINGS",[Nd]);class uc extends fs{}ge(uc,"MODEL_CLASS_MAPPINGS",[oa]);class dc extends fs{}ge(dc,"MODEL_CLASS_MAPPINGS",[Bd]);class cc extends fs{}ge(cc,"MODEL_CLASS_MAPPINGS",[jd]);class da extends fs{}ge(da,"MODEL_CLASS_MAPPINGS",[la]);class pc extends fs{}ge(pc,"MODEL_CLASS_MAPPINGS",[Wd]);class hc extends fs{}ge(hc,"MODEL_CLASS_MAPPINGS",[Ud]);class mc extends fs{}ge(mc,"MODEL_CLASS_MAPPINGS",[Vd]);class _c extends fs{}ge(_c,"MODEL_CLASS_MAPPINGS",[dp]);class fc extends fs{}ge(fc,"MODEL_CLASS_MAPPINGS",[Gd]);class gc extends fs{}ge(gc,"MODEL_CLASS_MAPPINGS",[Kd]);class wc extends fs{}ge(wc,"MODEL_CLASS_MAPPINGS",[Hd]);class _p extends fs{}ge(_p,"MODEL_CLASS_MAPPINGS",[qd]);class yc extends fs{}ge(yc,"MODEL_CLASS_MAPPINGS",[Xd]);class Mc extends fs{}ge(Mc,"MODEL_CLASS_MAPPINGS",[cp]);class fp extends Je{constructor({logits:x,past_key_values:N,encoder_outputs:ye,decoder_attentions:Oe=null,cross_attentions:ke=null}){super(),this.logits=x,this.past_key_values=N,this.encoder_outputs=ye,this.decoder_attentions=Oe,this.cross_attentions=ke}}class Xt extends Je{constructor({logits:x,...N}){super(),this.logits=x;const ye=Object.values(N);ye.length>0&&(this.attentions=ye)}}class bc extends Je{constructor({logits:x,embeddings:N}){super(),this.logits=x,this.embeddings=N}}class js extends Je{constructor({logits:x}){super(),this.logits=x}}class Us extends Je{constructor({logits:x}){super(),this.logits=x}}class Zs extends Je{constructor({start_logits:x,end_logits:N}){super(),this.start_logits=x,this.end_logits=N}}class ln extends Je{constructor({logits:x}){super(),this.logits=x}}class Ii extends Je{constructor({logits:x,past_key_values:N}){super(),this.logits=x,this.past_key_values=N}}class vc extends Je{constructor({alphas:x}){super(),this.alphas=x}}class ca extends Je{constructor({waveform:x,spectrogram:N}){super(),this.waveform=x,this.spectrogram=N}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(De,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>j});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js");class j extends f.FeatureExtractor{constructor(W){super(W);const w=this.config.sampling_rate,v=(0,L.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(w/2),w,null,"kaldi",!0);for(let y=0;y{r.r(A),r.d(A,{AutoFeatureExtractor:()=>J});var f=r("./src/utils/constants.js"),L=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var j=r("./src/models/feature_extractors.js");class J{static async from_pretrained(w,v={}){const y=await(0,L.getModelJSON)(w,f.FEATURE_EXTRACTOR_NAME,!0,v),M=y.feature_extractor_type,b=j[M];if(!b)throw new Error(`Unknown feature_extractor_type: '${M}'. Please report this at ${f.GITHUB_ISSUE_URL}.`);return new b(y)}}},"./src/models/auto/image_processing_auto.js":(De,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>W});var f=r("./src/utils/constants.js"),L=r("./src/utils/hub.js"),j=r("./src/base/image_processors_utils.js"),J=r("./src/models/image_processors.js");class W{static async from_pretrained(v,y={}){const M=await(0,L.getModelJSON)(v,f.IMAGE_PROCESSOR_NAME,!0,y),b=M.image_processor_type??M.feature_extractor_type;let D=J[b];return D||(b!==void 0&&console.warn(`Image processor type '${b}' not found, assuming base ImageProcessor. Please report this at ${f.GITHUB_ISSUE_URL}.`),D=j.ImageProcessor),new D(M)}}},"./src/models/auto/processing_auto.js":(De,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>v});var f=r("./src/utils/constants.js"),L=r("./src/utils/hub.js"),j=r("./src/base/processing_utils.js"),J=r("./src/models/processors.js"),W=r("./src/models/image_processors.js"),w=r("./src/models/feature_extractors.js");class v{static async from_pretrained(M,b={}){const D=await(0,L.getModelJSON)(M,f.IMAGE_PROCESSOR_NAME,!0,b),{image_processor_type:H,feature_extractor_type:re,processor_class:ie}=D;if(ie&&J[ie])return J[ie].from_pretrained(M,b);if(!H&&!re)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const z={};if(H){const Q=W[H];if(!Q)throw new Error(`Unknown image_processor_type: '${H}'.`);z.image_processor=new Q(D)}if(re){const Q=W[re];if(Q)z.image_processor=new Q(D);else{const F=w[re];if(!F)throw new Error(`Unknown feature_extractor_type: '${re}'.`);z.feature_extractor=new F(D)}}const V={};return new j.Processor(V,z)}}},"./src/models/beit/image_processing_beit.js":(De,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(De,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(De,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(De,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>j});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js");class j extends f.FeatureExtractor{constructor(W){super(W),this.mel_filters=(0,L.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,L.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,L.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(W,w,v,y){let M;const b=W.length-w;if(b>0)if(v==="rand_trunc"){const D=Math.floor(Math.random()*(b+1));W=W.subarray(D,D+w),M=await this._extract_fbank_features(W,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(b<0){let D=new Float64Array(w);if(D.set(W),y==="repeat")for(let H=W.length;H{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>j,CLIPImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/convnext/image_processing_convnext.js":(De,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>j,ConvNextImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(W){super(W),this.crop_pct=this.config.crop_pct??.875}async resize(W){var v;const w=(v=this.size)==null?void 0:v.shortest_edge;if(w===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(w<384){const y=Math.floor(w/this.crop_pct),[M,b]=this.get_resize_output_image_size(W,{shortest_edge:y});W=await W.resize(M,b,{resample:this.resample}),W=await W.center_crop(w,w)}else W=await W.resize(w,w,{resample:this.resample});return W}}class j extends L{}},"./src/models/deit/image_processing_deit.js":(De,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>j,DeiTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/detr/image_processing_detr.js":(De,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>J,DetrImageProcessor:()=>j});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class j extends f.ImageProcessor{async _call(w){const v=await super._call(w),y=[v.pixel_values.dims[0],64,64],M=(0,L.full)(y,1n);return{...v,pixel_mask:M}}post_process_object_detection(...w){return(0,f.post_process_object_detection)(...w)}post_process_panoptic_segmentation(...w){return(0,f.post_process_panoptic_segmentation)(...w)}post_process_instance_segmentation(...w){return(0,f.post_process_instance_segmentation)(...w)}}class J extends j{}},"./src/models/donut/image_processing_donut.js":(De,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>j,DonutImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{pad_image(W,w,v,y={}){const[M,b,D]=w;let H=this.image_mean;Array.isArray(this.image_mean)||(H=new Array(D).fill(H));let re=this.image_std;Array.isArray(re)||(re=new Array(D).fill(H));const ie=H.map((z,V)=>-z/re[V]);return super.pad_image(W,w,v,{center:!0,constant_values:ie,...y})}}class j extends L{}},"./src/models/dpt/image_processing_dpt.js":(De,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>j,DPTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/efficientnet/image_processing_efficientnet.js":(De,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(J){super(J),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(W=>W*W))}}},"./src/models/feature_extractors.js":(De,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>f.ASTFeatureExtractor,ClapFeatureExtractor:()=>L.ClapFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>j.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>J.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>W.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>w.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var f=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),L=r("./src/models/clap/feature_extraction_clap.js"),j=r("./src/models/moonshine/feature_extraction_moonshine.js"),J=r("./src/models/pyannote/feature_extraction_pyannote.js"),W=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),w=r("./src/models/speecht5/feature_extraction_speecht5.js"),v=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"),b=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(De,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class J extends f.Processor{constructor(w,v){super(w,v);const{tasks_answer_post_processing_type:y,task_prompts_without_inputs:M,task_prompts_with_input:b}=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(b??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(w){typeof w=="string"&&(w=[w]);const v=[];for(const y of w)if(this.task_prompts_without_inputs.has(y))v.push(this.task_prompts_without_inputs.get(y));else{for(const[M,b]of this.task_prompts_with_input)if(y.includes(M)){v.push(b.replaceAll("{input}",y).replaceAll(M,""));break}v.length!==w.length&&v.push(y)}return v}post_process_generation(w,v,y){const M=this.tasks_answer_post_processing_type.get(v)??"pure_text";w=w.replaceAll("","").replaceAll("","");let b;switch(M){case"pure_text":b=w;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const D=M==="ocr"?"quad_boxes":"bboxes",H=w.matchAll(this.regexes[D]),re=[],ie=[];for(const[z,V,...Q]of H)re.push(V?V.trim():re.at(-1)??""),ie.push(Q.map((F,$)=>(Number(F)+.5)/this.size_per_bin*y[$%2]));b={labels:re,[D]:ie};break;default:throw new Error(`Task "${v}" (of type "${M}") not yet implemented.`)}return{[v]:b}}async _call(w,v=null,y={}){if(!w&&!v)throw new Error("Either text or images must be provided");const M=await this.image_processor(w,y),b=v?this.tokenizer(v,y):{};return{...M,...b}}}ge(J,"tokenizer_class",j.AutoTokenizer),ge(J,"image_processor_class",L.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(De,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(De,A,r)=>{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>j});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class j extends f.ImageProcessor{constructor(W){super(W),this.do_image_splitting=W.do_image_splitting??!0,this.max_image_size=W.max_image_size}get_resize_for_vision_encoder(W,w){let[v,y]=W.dims.slice(-2);const M=y/v;return y>=v?(y=Math.ceil(y/w)*w,v=Math.floor(y/M),v=Math.ceil(v/w)*w):(v=Math.ceil(v/w)*w,y=Math.floor(v*M),y=Math.ceil(y/w)*w),{height:v,width:y}}async _call(W,{do_image_splitting:w=null,return_row_col_info:v=!1}={}){let y;if(!Array.isArray(W))y=[[W]];else{if(W.length===0||!W[0])throw new Error("No images provided.");Array.isArray(W[0])?y=W:y=[W]}let M=[],b=[],D=[];const H=[],re=[];for(const C of y){let T=await Promise.all(C.map(le=>this.preprocess(le)));H.push(...T.map(le=>le.original_size)),re.push(...T.map(le=>le.reshaped_input_size)),T.forEach(le=>le.pixel_values.unsqueeze_(0));const{longest_edge:ee}=this.max_image_size;let Y;if(w??this.do_image_splitting){let le=new Array(T.length),de=new Array(T.length);Y=await Promise.all(T.map(async(fe,Pe)=>{const xe=this.get_resize_for_vision_encoder(fe.pixel_values,ee),Le=await(0,L.interpolate_4d)(fe.pixel_values,{size:[xe.height,xe.width]}),{frames:qe,num_splits_h:je,num_splits_w:dt}=await this.split_image(Le,this.max_image_size);return le[Pe]=je,de[Pe]=dt,(0,L.cat)(qe,0)})),b.push(le),D.push(de)}else{const le=[ee,ee];Y=await Promise.all(T.map(de=>(0,L.interpolate_4d)(de.pixel_values,{size:le}))),b.push(new Array(T.length).fill(0)),D.push(new Array(T.length).fill(0))}M.push((0,L.cat)(Y,0))}const ie=M.length,[z,V,Q,F]=M[0].dims;let $,g;if(ie===1)$=M[0].unsqueeze_(0),g=(0,L.full)([ie,z,Q,F],!0);else{const C=Math.max(...M.map(Y=>Y.dims.at(0)));g=(0,L.full)([ie,C,Q,F],!0);const T=g.data,ee=C*Q*F;for(let Y=0;Yv||D>y){H=Math.ceil(b/v),re=Math.ceil(D/y);const ie=Math.ceil(b/H),z=Math.ceil(D/re);for(let F=0;F{r.r(A),r.d(A,{Idefics3Processor:()=>y});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");var J=r("./src/utils/core.js");function W(M,b,D,H,re,ie){let z="";for(let V=0;V`+re.repeat(M);z+=` `}return z+=` ${H}${ie}`+re.repeat(M)+`${H}`,z}function w(M,b,D,H){return`${b}${H}`+D.repeat(M)+`${b}`}function v(M,b,D,H,re,ie){return M===0&&b===0?w(D,H,re,ie):W(D,M,b,H,re,ie)}class y extends f.Processor{constructor(){super(...arguments);ge(this,"fake_image_token","");ge(this,"image_token","");ge(this,"global_img_token","")}async _call(D,H=null,re={}){re.return_row_col_info??(re.return_row_col_info=!0);let ie;H&&(ie=await this.image_processor(H,re)),Array.isArray(D)||(D=[D]);const z=ie.rows??[new Array(D.length).fill(0)],V=ie.cols??[new Array(D.length).fill(0)],Q=this.config.image_seq_len,F=[],$=[];for(let C=0;Cv(Pe,Y[xe],Q,this.fake_image_token,this.image_token,this.global_img_token)),de=T.split(this.image_token);if(de.length===0)throw new Error("The image token should be present in the text.");let fe=de[0];for(let Pe=0;Pe{r.r(A),r.d(A,{BeitFeatureExtractor:()=>f.BeitFeatureExtractor,BitImageProcessor:()=>L.BitImageProcessor,CLIPFeatureExtractor:()=>J.CLIPFeatureExtractor,CLIPImageProcessor:()=>J.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>j.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>W.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>W.ConvNextImageProcessor,DPTFeatureExtractor:()=>M.DPTFeatureExtractor,DPTImageProcessor:()=>M.DPTImageProcessor,DeiTFeatureExtractor:()=>w.DeiTFeatureExtractor,DeiTImageProcessor:()=>w.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>y.DonutFeatureExtractor,DonutImageProcessor:()=>y.DonutImageProcessor,EfficientNetImageProcessor:()=>b.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>D.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>H.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>ie.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>V.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Q.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>Q.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>F.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>F.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>$.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>$.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>g.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>g.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>T.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>T.MobileViTImageProcessor,NougatImageProcessor:()=>ee.NougatImageProcessor,OwlViTFeatureExtractor:()=>le.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>le.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Y.Owlv2ImageProcessor,Phi3VImageProcessor:()=>de.Phi3VImageProcessor,PvtImageProcessor:()=>fe.PvtImageProcessor,Qwen2VLImageProcessor:()=>Pe.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>xe.RTDetrImageProcessor,SamImageProcessor:()=>Le.SamImageProcessor,SegformerFeatureExtractor:()=>qe.SegformerFeatureExtractor,SegformerImageProcessor:()=>qe.SegformerImageProcessor,SiglipImageProcessor:()=>je.SiglipImageProcessor,Swin2SRImageProcessor:()=>dt.Swin2SRImageProcessor,VLMImageProcessor:()=>re.VLMImageProcessor,ViTFeatureExtractor:()=>ue.ViTFeatureExtractor,ViTImageProcessor:()=>ue.ViTImageProcessor,VitMatteImageProcessor:()=>te.VitMatteImageProcessor,VitPoseImageProcessor:()=>he.VitPoseImageProcessor,YolosFeatureExtractor:()=>Te.YolosFeatureExtractor,YolosImageProcessor:()=>Te.YolosImageProcessor});var f=r("./src/models/beit/image_processing_beit.js"),L=r("./src/models/bit/image_processing_bit.js"),j=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),J=r("./src/models/clip/image_processing_clip.js"),W=r("./src/models/convnext/image_processing_convnext.js"),w=r("./src/models/deit/image_processing_deit.js"),v=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"),b=r("./src/models/efficientnet/image_processing_efficientnet.js"),D=r("./src/models/glpn/image_processing_glpn.js"),H=r("./src/models/idefics3/image_processing_idefics3.js"),re=r("./src/models/janus/image_processing_janus.js"),ie=r("./src/models/jina_clip/image_processing_jina_clip.js"),z=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),V=r("./src/models/mask2former/image_processing_mask2former.js"),Q=r("./src/models/maskformer/image_processing_maskformer.js"),F=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),$=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),g=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),T=r("./src/models/mobilevit/image_processing_mobilevit.js"),ee=r("./src/models/nougat/image_processing_nougat.js"),Y=r("./src/models/owlv2/image_processing_owlv2.js"),le=r("./src/models/owlvit/image_processing_owlvit.js"),de=r("./src/models/phi3_v/image_processing_phi3_v.js"),fe=r("./src/models/pvt/image_processing_pvt.js"),Pe=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),xe=r("./src/models/rt_detr/image_processing_rt_detr.js"),Le=r("./src/models/sam/image_processing_sam.js"),qe=r("./src/models/segformer/image_processing_segformer.js"),je=r("./src/models/siglip/image_processing_siglip.js"),dt=r("./src/models/swin2sr/image_processing_swin2sr.js"),ue=r("./src/models/vit/image_processing_vit.js"),te=r("./src/models/vitmatte/image_processing_vitmatte.js"),he=r("./src/models/vitpose/image_processing_vitpose.js"),Te=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(De,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(J){super({do_pad:!0,pad_size:{width:J.image_size,height:J.image_size},...J}),this.constant_values=this.config.background_color.map(W=>W*this.rescale_factor)}pad_image(J,W,w,v){return super.pad_image(J,W,w,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(De,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>v});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),J=r("./src/utils/core.js"),W=r("./src/utils/tensor.js"),w=r("./src/utils/image.js");class v extends f.Processor{constructor(M,b){super(M,b),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:b=null,chat_template:D="default"}={}){b?Array.isArray(b)||(b=[b]):b=await Promise.all(M.filter(Y=>Y.images).flatMap(Y=>Y.images).map(Y=>w.RawImage.read(Y)));const H=this.tokenizer,re=H.apply_chat_template(M,{tokenize:!1,add_generation_prompt:!0,chat_template:D}),ie=Y=>H.encode(Y,{add_special_tokens:!1}),z=re.split(this.image_tag),V=z.length-1;if(b.length!==V)throw new Error(`Number of images provided (${b.length}) does not match number of "${this.image_tag}" image tags (${V})`);const[Q,F,$]=H.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let g=ie(z[0]),C=new Array(g.length).fill(!1);for(let Y=1;Y0){const Y=await this.image_processor(b);return Y.pixel_values.unsqueeze_(0),{...ee,...Y}}return ee}}ge(v,"image_processor_class",L.AutoImageProcessor),ge(v,"tokenizer_class",j.AutoTokenizer),ge(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(De,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(J){const{resize_mode:W,fill_color:w,interpolation:v,size:y,...M}=J,b=W==="squash"?{width:y,height:y}:W==="shortest"?{shortest_edge:y}:{longest_edge:y},D=v==="bicubic"?3:2;super({...M,size:b,resample:D,do_center_crop:!0,crop_size:y,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(De,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class J extends f.Processor{async _call(w=null,v=null,y={}){if(!w&&!v)throw new Error("Either text or images must be provided");const M=w?this.tokenizer(w,y):{},b=v?await this.image_processor(v,y):{};return{...M,...b}}}ge(J,"tokenizer_class",j.AutoTokenizer),ge(J,"image_processor_class",L.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(De,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(De,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>L});var f=r("./src/models/maskformer/image_processing_maskformer.js");class L extends f.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(De,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>j,MaskFormerImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_panoptic_segmentation(...W){return(0,f.post_process_panoptic_segmentation)(...W)}post_process_instance_segmentation(...W){return(0,f.post_process_instance_segmentation)(...W)}}class j extends L{}},"./src/models/mgp_str/processing_mgp_str.js":(De,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>w});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),J=r("./src/utils/maths.js");const W={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class w extends f.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(!W.hasOwnProperty(M))throw new Error(`Format ${M} is not supported.`);const[b,D]=W[M],H=this[b].bind(this),[re,ie]=y.dims,z=[],V=[],Q=y.tolist();for(let $=0;$0?T.reduce((Y,le)=>Y*le,1):0;V.push(C),z.push(ee)}return[H(V),z]}char_decode(y){return this.char_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}bpe_decode(y){return this.bpe_tokenizer.batch_decode(y)}wp_decode(y){return this.wp_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}batch_decode([y,M,b]){const[D,H]=this._decode_helper(y,"char"),[re,ie]=this._decode_helper(M,"bpe"),[z,V]=this._decode_helper(b,"wp"),Q=[],F=[];for(let $=0;${r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>j,MobileNetV1ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>j,MobileNetV2ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>j,MobileNetV3ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>j,MobileNetV4ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/mobilevit/image_processing_mobilevit.js":(De,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>j,MobileViTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/moonshine/feature_extraction_moonshine.js":(De,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>j});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js");class j extends f.FeatureExtractor{async _call(W){(0,f.validate_audio_inputs)(W,"MoonshineFeatureExtractor"),W instanceof Float64Array&&(W=new Float32Array(W));const w=[1,W.length];return{input_values:new L.Tensor("float32",W,w)}}}},"./src/models/moonshine/processing_moonshine.js":(De,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>J});var f=r("./src/models/auto/feature_extraction_auto.js"),L=r("./src/tokenizers.js"),j=r("./src/base/processing_utils.js");class J extends j.Processor{async _call(w){return await this.feature_extractor(w)}}ge(J,"tokenizer_class",L.AutoTokenizer),ge(J,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(De,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>L});var f=r("./src/models/donut/image_processing_donut.js");class L extends f.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(De,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>L});var f=r("./src/models/owlvit/image_processing_owlvit.js");class L extends f.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(De,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>j,OwlViTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_object_detection(...W){return(0,f.post_process_object_detection)(...W)}}class j extends L{}},"./src/models/owlvit/processing_owlvit.js":(De,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class J extends f.Processor{}ge(J,"tokenizer_class",j.AutoTokenizer),ge(J,"image_processor_class",L.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(De,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>w});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");const J="";function W(v,y,M,b,D){return`${b.repeat(M*D)}${y}${v} `}class w extends f.Processor{async _call(y,M=null,b={}){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 D=this.tokenizer.bos_token,H=this.image_processor.config.image_seq_length;let re;M.some(V=>V.includes(J))?re=M.map(V=>{const Q=V.replaceAll(J,J.repeat(H)),F=Q.lastIndexOf(J),$=F===-1?0:F+J.length;return Q.slice(0,$)+D+Q.slice($)+` `}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),re=M.map(V=>W(V,D,H,J,y.length)));const ie=this.tokenizer(re,b);return{...await this.image_processor(y,b),...ie}}}ge(w,"tokenizer_class",j.AutoTokenizer),ge(w,"image_processor_class",L.AutoImageProcessor),ge(w,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(De,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>y});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");const j=336,J=[2,3],{ceil:W,floor:w,sqrt:v}=Math;class y extends f.ImageProcessor{constructor(b){super({...b,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=b.num_crops}calc_num_image_tokens_from_image_size(b,D){const{num_img_tokens:H}=this.config;return w((w(D/j)*w(b/j)+1)*H+1+(w(D/j)+1)*v(H))}get_resize_output_image_size(b,D){const H=this._num_crops,[re,ie]=b.size;let z=re/ie,V=1;for(;V*Math.ceil(V/z)<=H;)V+=1;V-=1;const Q=Math.floor(V*336),F=Math.floor(Q/z);return[Q,F]}pad_image(b,D,H,re={}){const[ie,z]=D,V=j*W(ie/j),Q=j*W(z/j),F=[1,1,1].map(($,g)=>($-this.image_mean[g])/this.image_std[g]);return super.pad_image(b,D,{width:Q,height:V},{center:!0,constant_values:F,...re})}async _call(b,{num_crops:D=null}={}){if(this._num_crops=D??(D=this.config.num_crops),D<4||v(D)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(b)||(b=[b]);const H=b.length,re=await Promise.all(b.map(C=>this.preprocess(C))),ie=re.map(C=>C.original_size),z=re.map(C=>C.reshaped_input_size),V=[];for(const{pixel_values:C}of re){C.unsqueeze_(0);const[T,ee]=C.dims.slice(-2),Y=await(0,L.interpolate_4d)(C,{size:[j,j],mode:"bicubic"});if(D>0){const le=[],de=v(D),fe=w(ee/de),Pe=w(T/de);for(let Le=0;LeC.map(T=>j*W(T/j))),$=new L.Tensor("int64",F.flat(),[H,2]),g=F.map(([C,T])=>this.calc_num_image_tokens_from_image_size(T,C));return{pixel_values:Q,original_sizes:ie,reshaped_input_sizes:z,image_sizes:$,num_img_tokens:g}}}},"./src/models/phi3_v/processing_phi3_v.js":(De,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>w});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");const J="<|image|>",W=/<\|image_\d+\|>/g;class w extends f.Processor{async _call(y,M=null,{padding:b=!0,truncation:D=!0,num_crops:H=null}={}){Array.isArray(y)||(y=[y]);let re,ie;if(M){ie=await this.image_processor(M,{num_crops:H});const{num_img_tokens:z}=ie,V=y.map((F,$)=>F.split(W).join(J.repeat(z[$])));re=this.tokenizer(V,{padding:b,truncation:D});const Q=this.tokenizer.model.convert_tokens_to_ids([J])[0];re.input_ids.map_(F=>F==Q?-F:F)}else re=this.tokenizer(y);return{...re,...ie}}}ge(w,"image_processor_class",L.AutoImageProcessor),ge(w,"tokenizer_class",j.AutoTokenizer)},"./src/models/processors.js":(De,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>f.Florence2Processor,Idefics3Processor:()=>J.Idefics3Processor,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,MgpstrProcessor:()=>L.MgpstrProcessor,MoonshineProcessor:()=>j.MoonshineProcessor,OwlViTProcessor:()=>v.OwlViTProcessor,PaliGemmaProcessor:()=>M.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>b.PyAnnoteProcessor,Qwen2VLProcessor:()=>D.Qwen2VLProcessor,SamProcessor:()=>H.SamProcessor,SpeechT5Processor:()=>re.SpeechT5Processor,VLChatProcessor:()=>W.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>ie.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>z.WhisperProcessor});var f=r("./src/models/florence2/processing_florence2.js"),L=r("./src/models/mgp_str/processing_mgp_str.js"),j=r("./src/models/moonshine/processing_moonshine.js"),J=r("./src/models/idefics3/processing_idefics3.js"),W=r("./src/models/janus/processing_janus.js"),w=r("./src/models/jina_clip/processing_jina_clip.js"),v=r("./src/models/owlvit/processing_owlvit.js"),y=r("./src/models/phi3_v/processing_phi3_v.js"),M=r("./src/models/paligemma/processing_paligemma.js"),b=r("./src/models/pyannote/processing_pyannote.js"),D=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),H=r("./src/models/sam/processing_sam.js"),re=r("./src/models/speecht5/processing_speecht5.js"),ie=r("./src/models/wav2vec2/processing_wav2vec2.js"),z=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(De,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(De,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>J});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");class J extends f.FeatureExtractor{async _call(w){(0,f.validate_audio_inputs)(w,"PyAnnoteFeatureExtractor"),w instanceof Float64Array&&(w=new Float32Array(w));const v=[1,1,w.length];return{input_values:new L.Tensor("float32",w,v)}}samples_to_frames(w){return(w-this.config.offset)/this.config.step}post_process_speaker_diarization(w,v){const y=v/this.samples_to_frames(v)/this.config.sampling_rate,M=[];for(const b of w.tolist()){const D=[];let H=-1;for(let re=0;re({id:re,start:ie*y,end:z*y,confidence:V/(z-ie)})))}return M}}},"./src/models/pyannote/processing_pyannote.js":(De,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>j});var f=r("./src/base/processing_utils.js"),L=r("./src/models/pyannote/feature_extraction_pyannote.js");class j extends f.Processor{async _call(W){return await this.feature_extractor(W)}post_process_speaker_diarization(...W){return this.feature_extractor.post_process_speaker_diarization(...W)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}ge(j,"feature_extractor_class",L.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(De,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>j});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class j extends f.ImageProcessor{async _call(W,...w){const{pixel_values:v,original_sizes:y,reshaped_input_sizes:M}=await super._call(W,...w);let b=v;const{temporal_patch_size:D,merge_size:H,patch_size:re}=this.config;b.dims[0]===1&&(b=(0,L.cat)(Array.from({length:D},()=>b),0));const ie=b.dims[0]/D,z=b.dims[1],V=Math.floor(b.dims[2]/re),Q=Math.floor(b.dims[3]/re),F=b.view(ie,D,z,Math.floor(V/H),H,re,Math.floor(Q/H),H,re).permute(0,3,6,4,7,2,1,5,8).view(ie*V*Q,z*D*re*re),$=new L.Tensor("int64",[ie,V,Q],[1,3]);return{pixel_values:F,image_grid_thw:$,original_sizes:y,reshaped_input_sizes:M}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(De,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");class J extends f.Processor{async _call(w,v=null,...y){Array.isArray(w)||(w=[w]);let M,b;if(v&&(M=await this.image_processor(v),b=M.image_grid_thw),b){let H=this.image_processor.config.merge_size**2,re=0;const ie=b.tolist();w=w.map(z=>{for(;z.includes("<|image_pad|>");){const V=Number(ie[re++].reduce((Q,F)=>Q*F,1n));z=z.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(V/H)))}return z.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(w),...M}}}ge(J,"image_processor_class",L.AutoImageProcessor),ge(J,"tokenizer_class",j.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(De,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_object_detection(...J){return(0,f.post_process_object_detection)(...J)}}},"./src/models/sam/image_processing_sam.js":(De,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>J});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/core.js"),j=r("./src/utils/tensor.js");class J extends f.ImageProcessor{reshape_input_points(w,v,y,M=!1){w=structuredClone(w);let b=(0,L.calculateDimensions)(w);if(b.length===3)M||(b=[1,...b]),w=[w];else if(b.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 D=0;DM!==v.dims[b]))throw Error(`The first ${y.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j.Tensor("int64",w.flat(1/0).map(BigInt),y)}async _call(w,{input_points:v=null,input_labels:y=null,input_boxes:M=null}={}){const b=await super._call(w);if(v&&(b.input_points=this.reshape_input_points(v,b.original_sizes,b.reshaped_input_sizes)),y){if(!b.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");b.input_labels=this.add_input_labels(y,b.input_points)}return M&&(b.input_boxes=this.reshape_input_points(M,b.original_sizes,b.reshaped_input_sizes,!0)),b}async post_process_masks(w,v,y,{mask_threshold:M=0,binarize:b=!0,pad_size:D=null}={}){const H=[];D=D??this.pad_size;const re=[D.height,D.width];for(let ie=0;ieM&&($[g]=1);Q=new j.Tensor("bool",$,Q.dims)}H.push(Q)}return H}generate_crop_boxes(w,v,{crop_n_layers:y=0,overlap_ratio:M=.3413333333333333,points_per_crop:b=32,crop_n_points_downscale_factor:D=1}={}){}}},"./src/models/sam/processing_sam.js":(De,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>j});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js");class j extends f.Processor{async _call(...W){return await this.image_processor(...W)}post_process_masks(...W){return this.image_processor.post_process_masks(...W)}reshape_input_points(...W){return this.image_processor.reshape_input_points(...W)}}ge(j,"image_processor_class",L.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(De,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>J});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js"),j=r("./src/utils/audio.js");class J extends f.FeatureExtractor{constructor(w){super(w);const v=this.config.sampling_rate,y=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let M=0;My*32768),(0,j.spectrogram)(w,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:v,transpose:!0})}async _call(w,{padding:v=!0,pad_to_multiple_of:y=2,do_normalize_per_mel_bins:M=!0,return_attention_mask:b=!0}={}){(0,f.validate_audio_inputs)(w,"SeamlessM4TFeatureExtractor");let D=await this._extract_fbank_features(w,this.config.max_length);if(M){const[$,g]=D.dims,C=D.data;for(let T=0;T0){const ee=new Float32Array(g*($+T));ee.set(C),ee.fill(this.config.padding_value,C.length);const Y=$+T;D=new L.Tensor(D.type,ee,[Y,g]),b&&(H=new L.Tensor("int64",new BigInt64Array(Y),[1,Y]),H.data.fill(1n,0,$))}}const[re,ie]=D.dims,z=this.config.stride;if(re%z!==0)throw new Error(`The number of frames (${re}) must be a multiple of the stride (${z}).`);const Q=D.view(1,Math.floor(re/z),ie*z),F={input_features:Q};if(b){const $=Q.dims[1],g=new BigInt64Array($);if(H){const C=H.data;for(let T=1,ee=0;T{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>j,SegformerImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_semantic_segmentation(...W){return(0,f.post_process_semantic_segmentation)(...W)}}class j extends L{}},"./src/models/siglip/image_processing_siglip.js":(De,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(De,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>L});var f=r("./src/base/feature_extraction_utils.js");class L extends f.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(De,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/tokenizers.js"),j=r("./src/models/auto/feature_extraction_auto.js");class J extends f.Processor{async _call(w){return await this.feature_extractor(w)}}ge(J,"tokenizer_class",L.AutoTokenizer),ge(J,"feature_extractor_class",j.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(De,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{pad_image(J,W,w,v={}){const[y,M,b]=W;return super.pad_image(J,W,{width:M+(w-M%w)%w,height:y+(w-y%w)%w},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(De,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>j,ViTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class j extends L{}},"./src/models/vitmatte/image_processing_vitmatte.js":(De,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>j});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class j extends f.ImageProcessor{async _call(W,w){Array.isArray(W)||(W=[W]),Array.isArray(w)||(w=[w]);const v=await Promise.all(W.map(b=>this.preprocess(b))),y=await Promise.all(w.map(b=>this.preprocess(b,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,L.stack)(v.map((b,D)=>(0,L.cat)([b.pixel_values,y[D].pixel_values],0)),0),original_sizes:v.map(b=>b.original_size),reshaped_input_sizes:v.map(b=>b.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(De,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_pose_estimation(J,W,{threshold:w=null}={}){const v=J.tolist(),[y,M,b,D]=J.dims,H=[];for(let re=0;re{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>j});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js");class j extends f.FeatureExtractor{_zero_mean_unit_var_norm(W){const v=W.reduce((M,b)=>M+b,0)/W.length,y=W.reduce((M,b)=>M+(b-v)**2,0)/W.length;return W.map(M=>(M-v)/Math.sqrt(y+1e-7))}async _call(W){(0,f.validate_audio_inputs)(W,"Wav2Vec2FeatureExtractor"),W instanceof Float64Array&&(W=new Float32Array(W));let w=W;this.config.do_normalize&&(w=this._zero_mean_unit_var_norm(w));const v=[1,w.length];return{input_values:new L.Tensor("float32",w,v),attention_mask:new L.Tensor("int64",new BigInt64Array(w.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(De,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>j});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/feature_extraction_auto.js");class j extends f.Processor{async _call(W){return await this.feature_extractor(W)}}ge(j,"feature_extractor_class",L.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(De,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>j});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js");class j extends f.FeatureExtractor{constructor(W){super(W);const w=this.config.sampling_rate,v=(0,L.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(w/2),w,null,"kaldi",!0);for(let y=0;yw*32768),(0,L.spectrogram)(W,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(W){(0,f.validate_audio_inputs)(W,"WeSpeakerFeatureExtractor");const w=(await this._extract_fbank_features(W)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=w.mean(1).data,y=w.data,[M,b,D]=w.dims;for(let H=0;H{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>L,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>j,whisper_language_to_code:()=>J});const f=[["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"]],L=new Map(f),j=new Map([...f.map(([W,w])=>[w,W]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function J(W){W=W.toLowerCase();let w=j.get(W);if(w===void 0)if(L.has(W))w=W;else{const y=W.length===2?L.keys():L.values();throw new Error(`Language "${W}" is not supported. Must be one of: ${JSON.stringify(y)}`)}return w}},"./src/models/whisper/feature_extraction_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>J});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js"),j=r("./src/utils/maths.js");class J extends f.FeatureExtractor{constructor(w){var v;super(w),(v=this.config).mel_filters??(v.mel_filters=(0,L.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,L.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(w){const v=await(0,L.spectrogram)(w,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=v.data,M=(0,j.max)(y)[0];for(let b=0;bthis.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`."),v=w.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(w)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>L});var f=r("./src/generation/configuration_utils.js");class L extends f.GenerationConfig{constructor(){super(...arguments);ge(this,"return_timestamps",null);ge(this,"return_token_timestamps",null);ge(this,"num_frames",null);ge(this,"alignment_heads",null);ge(this,"task",null);ge(this,"language",null);ge(this,"no_timestamps_token_id",null);ge(this,"prompt_ids",null);ge(this,"is_multilingual",null);ge(this,"lang_to_id",null);ge(this,"task_to_id",null);ge(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>J});var f=r("./src/models/auto/feature_extraction_auto.js"),L=r("./src/tokenizers.js"),j=r("./src/base/processing_utils.js");class J extends j.Processor{async _call(w){return await this.feature_extractor(w)}}ge(J,"tokenizer_class",L.AutoTokenizer),ge(J,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(De,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>j,YolosImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_object_detection(...W){return(0,f.post_process_object_detection)(...W)}}class j extends L{}},"./src/ops/registry.js":(De,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>J});var f=r("./src/backends/onnx.js"),L=r("./src/utils/tensor.js");const j=async(W,w,v)=>{const y=await(0,f.createInferenceSession)(new Uint8Array(W),w);return async M=>{const b=(0,f.isONNXProxy)(),D=Object.fromEntries(Object.entries(M).map(([re,ie])=>[re,(b?ie.clone():ie).ort_tensor])),H=await y.run(D);return Array.isArray(v)?v.map(re=>new L.Tensor(H[re])):new L.Tensor(H[v])}};class J{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=j([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=j([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=j([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=j([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=j([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=j([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=j([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=j([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}}ge(J,"session_options",{})},"./src/pipelines.js":(De,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>de,AutomaticSpeechRecognitionPipeline:()=>Pe,DepthEstimationPipeline:()=>ze,DocumentQuestionAnsweringPipeline:()=>te,FeatureExtractionPipeline:()=>Y,FillMaskPipeline:()=>Q,ImageClassificationPipeline:()=>Le,ImageFeatureExtractionPipeline:()=>le,ImageSegmentationPipeline:()=>qe,ImageToImagePipeline:()=>Te,ImageToTextPipeline:()=>xe,ObjectDetectionPipeline:()=>dt,Pipeline:()=>re,QuestionAnsweringPipeline:()=>V,SummarizationPipeline:()=>$,Text2TextGenerationPipeline:()=>F,TextClassificationPipeline:()=>ie,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>he,TokenClassificationPipeline:()=>z,TranslationPipeline:()=>g,ZeroShotAudioClassificationPipeline:()=>fe,ZeroShotClassificationPipeline:()=>ee,ZeroShotImageClassificationPipeline:()=>je,ZeroShotObjectDetectionPipeline:()=>ue,pipeline:()=>oe});var f=r("./src/tokenizers.js"),L=r("./src/models.js"),j=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var J=r("./src/utils/generic.js"),W=r("./src/utils/core.js"),w=r("./src/utils/maths.js"),v=r("./src/utils/audio.js"),y=r("./src/utils/tensor.js"),M=r("./src/utils/image.js");async function b(Fe){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(pe=>M.RawImage.read(pe)))}async function D(Fe,pe){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(ve=>typeof ve=="string"||ve instanceof URL?(0,v.read_audio)(ve,pe):ve instanceof Float64Array?new Float32Array(ve):ve))}function H(Fe,pe){pe&&(Fe=Fe.map(Ne=>Ne|0));const[ve,Re,We,Ve]=Fe;return{xmin:ve,ymin:Re,xmax:We,ymax:Ve}}class re extends J.Callable{constructor({task:pe,model:ve,tokenizer:Re=null,processor:We=null}){super(),this.task=pe,this.model=ve,this.tokenizer=Re,this.processor=We}async dispose(){await this.model.dispose()}}class ie extends re{constructor(pe){super(pe)}async _call(pe,{top_k:ve=1}={}){const Re=this.tokenizer(pe,{padding:!0,truncation:!0}),We=await this.model(Re),Ve=this.model.config.problem_type==="multi_label_classification"?at=>at.sigmoid():at=>new y.Tensor("float32",(0,w.softmax)(at.data),at.dims),Ne=this.model.config.id2label,Ze=[];for(const at of We.logits){const ft=Ve(at),lt=await(0,y.topk)(ft,ve),ht=lt[0].tolist(),ne=lt[1].tolist().map((K,ce)=>({label:Ne?Ne[K]:`LABEL_${K}`,score:ht[ce]}));ve===1?Ze.push(...ne):Ze.push(ne)}return Array.isArray(pe)||ve===1?Ze:Ze[0]}}class z extends re{constructor(pe){super(pe)}async _call(pe,{ignore_labels:ve=["O"]}={}){const Re=Array.isArray(pe),We=this.tokenizer(Re?pe:[pe],{padding:!0,truncation:!0}),Ne=(await this.model(We)).logits,Ze=this.model.config.id2label,at=[];for(let ft=0;ftpt==this.tokenizer.sep_token_id);at[ht].map((pt,It)=>pt==1&&(It===0||It>ne&&ft.findIndex(St=>St==I[It])===-1));const K=Ve[ht].tolist(),ce=Ne[ht].tolist();for(let pt=1;ptIt==I[pt])!==-1)&&(K[pt]=-1/0,ce[pt]=-1/0);const Ie=(0,w.softmax)(K).map((pt,It)=>[pt,It]),Qe=(0,w.softmax)(ce).map((pt,It)=>[pt,It]);Ie[0][0]=0,Qe[0][0]=0;const rt=(0,W.product)(Ie,Qe).filter(pt=>pt[0][1]<=pt[1][1]).map(pt=>[pt[0][1],pt[1][1],pt[0][0]*pt[1][0]]).sort((pt,It)=>It[2]-pt[2]);for(let pt=0;ptK==this.tokenizer.mask_token_id);if(ft===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=We[Ze][ft],ht=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(lt.data),lt.dims),ve),I=ht[0].tolist(),ne=ht[1].tolist();Ve.push(ne.map((K,ce)=>{const Ie=at.slice();return Ie[ft]=K,{score:I[ce],token:Number(K),token_str:this.tokenizer.decode([K]),sequence:this.tokenizer.decode(Ie,{skip_special_tokens:!0})}}))}return Array.isArray(pe)?Ve:Ve[0]}}class F extends re{constructor(ve){super(ve);ge(this,"_key","generated_text")}async _call(ve,Re={}){Array.isArray(ve)||(ve=[ve]),this.model.config.prefix&&(ve=ve.map(ft=>this.model.config.prefix+ft));const We=this.model.config.task_specific_params;We&&We[this.task]&&We[this.task].prefix&&(ve=ve.map(ft=>We[this.task].prefix+ft));const Ve=this.tokenizer,Ne={padding:!0,truncation:!0};let Ze;this instanceof g&&"_build_translation_inputs"in Ve?Ze=Ve._build_translation_inputs(ve,Ne,Re):Ze=Ve(ve,Ne);const at=await this.model.generate({...Ze,...Re});return Ve.batch_decode(at,{skip_special_tokens:!0}).map(ft=>({[this._key]:ft}))}}class $ extends F{constructor(ve){super(ve);ge(this,"_key","summary_text")}}class g extends F{constructor(ve){super(ve);ge(this,"_key","translation_text")}}function C(Fe){return Array.isArray(Fe)&&Fe.every(pe=>"role"in pe&&"content"in pe)}class T extends re{constructor(pe){super(pe)}async _call(pe,ve={}){let Re=!1,We=!1,Ve;if(typeof pe=="string")Ve=pe=[pe];else if(Array.isArray(pe)&&pe.every(ne=>typeof ne=="string"))Re=!0,Ve=pe;else{if(C(pe))pe=[pe];else if(Array.isArray(pe)&&pe.every(C))Re=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");We=!0,Ve=pe.map(ne=>this.tokenizer.apply_chat_template(ne,{tokenize:!1,add_generation_prompt:!0}))}const Ne=ve.add_special_tokens??!1,Ze=We?!1:ve.return_full_text??!0;this.tokenizer.padding_side="left";const at=this.tokenizer(Ve,{add_special_tokens:Ne,padding:!0,truncation:!0}),ft=await this.model.generate({...at,...ve}),lt=this.tokenizer.batch_decode(ft,{skip_special_tokens:!0});let ht;!Ze&&at.input_ids.dims.at(-1)>0&&(ht=this.tokenizer.batch_decode(at.input_ids,{skip_special_tokens:!0}).map(ne=>ne.length));const I=Array.from({length:pe.length},ne=>[]);for(let ne=0;ne[ve.toLowerCase(),Re])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(pe,ve,{hypothesis_template:Re="This example is {}.",multi_label:We=!1}={}){const Ve=Array.isArray(pe);Ve||(pe=[pe]),Array.isArray(ve)||(ve=[ve]);const Ne=ve.map(ft=>Re.replace("{}",ft)),Ze=We||ve.length===1,at=[];for(const ft of pe){const lt=[];for(const ne of Ne){const K=this.tokenizer(ft,{text_pair:ne,padding:!0,truncation:!0}),ce=await this.model(K);Ze?lt.push([ce.logits.data[this.contradiction_id],ce.logits.data[this.entailment_id]]):lt.push(ce.logits.data[this.entailment_id])}const I=(Ze?lt.map(ne=>(0,w.softmax)(ne)[1]):(0,w.softmax)(lt)).map((ne,K)=>[ne,K]).sort((ne,K)=>K[0]-ne[0]);at.push({sequence:ft,labels:I.map(ne=>ve[ne[1]]),scores:I.map(ne=>ne[0])})}return Ve?at:at[0]}}class Y extends re{constructor(pe){super(pe)}async _call(pe,{pooling:ve="none",normalize:Re=!1,quantize:We=!1,precision:Ve="binary"}={}){const Ne=this.tokenizer(pe,{padding:!0,truncation:!0}),Ze=await this.model(Ne);let at=Ze.last_hidden_state??Ze.logits??Ze.token_embeddings;if(ve!=="none")if(ve==="mean")at=(0,y.mean_pooling)(at,Ne.attention_mask);else if(ve==="cls")at=at.slice(null,0);else throw Error(`Pooling method '${ve}' not supported.`);return Re&&(at=at.normalize(2,-1)),We&&(at=(0,y.quantize_embeddings)(at,Ve)),at}}class le extends re{constructor(pe){super(pe)}async _call(pe,{pool:ve=null}={}){const Re=await b(pe),{pixel_values:We}=await this.processor(Re),Ve=await this.model({pixel_values:We});let Ne;if(ve){if(!("pooler_output"in Ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ne=Ve.pooler_output}else Ne=Ve.last_hidden_state??Ve.logits??Ve.image_embeds;return Ne}}class de extends re{constructor(pe){super(pe)}async _call(pe,{top_k:ve=5}={}){const Re=this.processor.feature_extractor.config.sampling_rate,We=await D(pe,Re),Ve=this.model.config.id2label,Ne=[];for(const Ze of We){const at=await this.processor(Ze),lt=(await this.model(at)).logits[0],ht=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(lt.data),lt.dims),ve),I=ht[0].tolist(),K=ht[1].tolist().map((ce,Ie)=>({label:Ve?Ve[ce]:`LABEL_${ce}`,score:I[Ie]}));Ne.push(K)}return Array.isArray(pe)?Ne:Ne[0]}}class fe extends re{constructor(pe){super(pe)}async _call(pe,ve,{hypothesis_template:Re="This is a sound of {}."}={}){const We=!Array.isArray(pe);We&&(pe=[pe]);const Ve=ve.map(lt=>Re.replace("{}",lt)),Ne=this.tokenizer(Ve,{padding:!0,truncation:!0}),Ze=this.processor.feature_extractor.config.sampling_rate,at=await D(pe,Ze),ft=[];for(const lt of at){const ht=await this.processor(lt),I=await this.model({...Ne,...ht}),ne=(0,w.softmax)(I.logits_per_audio.data);ft.push([...ne].map((K,ce)=>({score:K,label:ve[ce]})))}return We?ft[0]:ft}}class Pe extends re{constructor(pe){super(pe)}async _call(pe,ve={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(pe,ve);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(pe,ve);case"moonshine":return this._call_moonshine(pe,ve);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(pe,ve){ve.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ve.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Re=!Array.isArray(pe);Re&&(pe=[pe]);const We=this.processor.feature_extractor.config.sampling_rate,Ve=await D(pe,We),Ne=[];for(const Ze of Ve){const at=await this.processor(Ze),lt=(await this.model(at)).logits[0],ht=[];for(const ne of lt)ht.push((0,w.max)(ne.data)[1]);const I=this.tokenizer.decode(ht);Ne.push({text:I})}return Re?Ne[0]:Ne}async _call_whisper(pe,ve){const Re=ve.return_timestamps??!1,We=ve.chunk_length_s??0,Ve=ve.force_full_sequences??!1;let Ne=ve.stride_length_s??null;const Ze={...ve};Re==="word"&&(Ze.return_token_timestamps=!0,Ze.return_timestamps=!1);const at=!Array.isArray(pe);at&&(pe=[pe]);const ft=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,I=await D(pe,ht),ne=[];for(const K of I){let ce=[];if(We>0){if(Ne===null)Ne=We/6;else if(We<=Ne)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const rt=ht*We,pt=ht*Ne,It=rt-2*pt;let St=0;for(;;){const Ft=St+rt,At=K.subarray(St,Ft),ns=await this.processor(At),gs=St===0,Ss=Ft>=K.length;if(ce.push({stride:[At.length,gs?0:pt,Ss?0:pt],input_features:ns.input_features,is_last:Ss}),Ss)break;St+=It}}else ce=[{stride:[K.length,0,0],input_features:(await this.processor(K)).input_features,is_last:!0}];for(const rt of ce){Ze.num_frames=Math.floor(rt.stride[0]/lt);const pt=await this.model.generate({inputs:rt.input_features,...Ze});Re==="word"?(rt.tokens=pt.sequences.tolist()[0],rt.token_timestamps=pt.token_timestamps.tolist()[0].map(It=>(0,w.round)(It,2))):rt.tokens=pt[0].tolist(),rt.stride=rt.stride.map(It=>It/ht)}const[Ie,Qe]=this.tokenizer._decode_asr(ce,{time_precision:ft,return_timestamps:Re,force_full_sequences:Ve});ne.push({text:Ie,...Qe})}return at?ne[0]:ne}async _call_moonshine(pe,ve){const Re=!Array.isArray(pe);Re&&(pe=[pe]);const We=this.processor.feature_extractor.config.sampling_rate,Ve=await D(pe,We),Ne=[];for(const Ze of Ve){const at=await this.processor(Ze),ft=Math.floor(Ze.length/We)*6,lt=await this.model.generate({max_new_tokens:ft,...ve,...at}),ht=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];Ne.push({text:ht})}return Re?Ne[0]:Ne}}class xe extends re{constructor(pe){super(pe)}async _call(pe,ve={}){const Re=Array.isArray(pe),We=await b(pe),{pixel_values:Ve}=await this.processor(We),Ne=[];for(const Ze of Ve){Ze.dims=[1,...Ze.dims];const at=await this.model.generate({inputs:Ze,...ve}),ft=this.tokenizer.batch_decode(at,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));Ne.push(ft)}return Re?Ne:Ne[0]}}class Le extends re{constructor(pe){super(pe)}async _call(pe,{top_k:ve=5}={}){const Re=await b(pe),{pixel_values:We}=await this.processor(Re),Ve=await this.model({pixel_values:We}),Ne=this.model.config.id2label,Ze=[];for(const at of Ve.logits){const ft=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(at.data),at.dims),ve),lt=ft[0].tolist(),I=ft[1].tolist().map((ne,K)=>({label:Ne?Ne[ne]:`LABEL_${ne}`,score:lt[K]}));Ze.push(I)}return Array.isArray(pe)?Ze:Ze[0]}}class qe extends re{constructor(pe){super(pe),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(pe,{threshold:ve=.5,mask_threshold:Re=.5,overlap_mask_area_threshold:We=.8,label_ids_to_fuse:Ve=null,target_sizes:Ne=null,subtask:Ze=null}={}){if(Array.isArray(pe)&&pe.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ft=await b(pe),lt=ft.map(Qe=>[Qe.height,Qe.width]),{pixel_values:ht,pixel_mask:I}=await this.processor(ft),ne=await this.model({pixel_values:ht,pixel_mask:I});let K=null;if(Ze!==null)K=this.subtasks_mapping[Ze];else for(let[Qe,rt]of Object.entries(this.subtasks_mapping))if(rt in this.processor.image_processor){K=this.processor.image_processor[rt].bind(this.processor.image_processor),Ze=Qe;break}const ce=this.model.config.id2label,Ie=[];if(Ze==="panoptic"||Ze==="instance"){const Qe=K(ne,ve,Re,We,Ve,Ne??lt)[0],rt=Qe.segmentation;for(const pt of Qe.segments_info){const It=new Uint8ClampedArray(rt.data.length);for(let Ft=0;FtRe.replace("{}",I)),Ze=this.tokenizer(Ne,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:at}=await this.processor(Ve),ft=await this.model({...Ze,pixel_values:at}),lt=this.model.config.model_type==="siglip"?I=>I.sigmoid().data:I=>(0,w.softmax)(I.data),ht=[];for(const I of ft.logits_per_image){const K=[...lt(I)].map((ce,Ie)=>({score:ce,label:ve[Ie]}));K.sort((ce,Ie)=>Ie.score-ce.score),ht.push(K)}return We?ht:ht[0]}}class dt extends re{constructor(pe){super(pe)}async _call(pe,{threshold:ve=.9,percentage:Re=!1}={}){const We=Array.isArray(pe);if(We&&pe.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ve=await b(pe),Ne=Re?null:Ve.map(ne=>[ne.height,ne.width]),{pixel_values:Ze,pixel_mask:at}=await this.processor(Ve),ft=await this.model({pixel_values:Ze,pixel_mask:at}),lt=this.processor.image_processor.post_process_object_detection(ft,ve,Ne),ht=this.model.config.id2label,I=lt.map(ne=>ne.boxes.map((K,ce)=>({score:ne.scores[ce],label:ht[ne.classes[ce]],box:H(K,!Re)})));return We?I:I[0]}}class ue extends re{constructor(pe){super(pe)}async _call(pe,ve,{threshold:Re=.1,top_k:We=null,percentage:Ve=!1}={}){const Ne=Array.isArray(pe),Ze=await b(pe),at=this.tokenizer(ve,{padding:!0,truncation:!0}),ft=await this.processor(Ze),lt=[];for(let ht=0;ht({score:Ie.scores[pt],label:ve[Ie.classes[pt]],box:H(rt,!Ve)})).sort((rt,pt)=>pt.score-rt.score);We!==null&&(Qe=Qe.slice(0,We)),lt.push(Qe)}return Ne?lt:lt[0]}}class te extends re{constructor(pe){super(pe)}async _call(pe,ve,Re={}){const We=(await b(pe))[0],{pixel_values:Ve}=await this.processor(We),Ne=`${ve}`,Ze=this.tokenizer(Ne,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,at=await this.model.generate({inputs:Ve,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ze,...Re}),lt=this.tokenizer.batch_decode(at)[0].match(/(.*?)<\/s_answer>/);let ht=null;return lt&<.length>=2&&(ht=lt[1].trim()),[{answer:ht}]}}class he extends re{constructor(ve){super(ve);ge(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ve.vocoder??null}async _call(ve,{speaker_embeddings:Re=null}={}){return this.processor?this._call_text_to_spectrogram(ve,{speaker_embeddings:Re}):this._call_text_to_waveform(ve)}async _call_text_to_waveform(ve){const Re=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:We}=await this.model(Re),Ve=this.model.config.sampling_rate;return{audio:We.data,sampling_rate:Ve}}async _call_text_to_spectrogram(ve,{speaker_embeddings:Re}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await L.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Re=="string"||Re instanceof URL)&&(Re=new Float32Array(await(await fetch(Re)).arrayBuffer())),Re instanceof Float32Array)Re=new y.Tensor("float32",Re,[1,Re.length]);else if(!(Re instanceof y.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:We}=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model.generate_speech(We,Re,{vocoder:this.vocoder}),Ne=this.processor.feature_extractor.config.sampling_rate;return{audio:Ve.data,sampling_rate:Ne}}}class Te extends re{constructor(pe){super(pe)}async _call(pe){const ve=await b(pe),Re=await this.processor(ve),We=await this.model(Re),Ve=[];for(const Ne of We.reconstruction){const Ze=Ne.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ve.push(M.RawImage.fromTensor(Ze))}return Ve.length>1?Ve:Ve[0]}}class ze extends re{constructor(pe){super(pe)}async _call(pe){const ve=await b(pe),Re=await this.processor(ve),{predicted_depth:We}=await this.model(Re),Ve=[];for(let Ne=0;Ne1?Ve:Ve[0]}}const et=Object.freeze({"text-classification":{tokenizer:f.AutoTokenizer,pipeline:ie,model:L.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:f.AutoTokenizer,pipeline:z,model:L.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:f.AutoTokenizer,pipeline:V,model:L.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:f.AutoTokenizer,pipeline:Q,model:L.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:f.AutoTokenizer,pipeline:$,model:L.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:f.AutoTokenizer,pipeline:g,model:L.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:f.AutoTokenizer,pipeline:F,model:L.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:f.AutoTokenizer,pipeline:T,model:L.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:f.AutoTokenizer,pipeline:ee,model:L.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:de,model:L.AutoModelForAudioClassification,processor:j.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:f.AutoTokenizer,pipeline:fe,model:L.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:f.AutoTokenizer,pipeline:Pe,model:[L.AutoModelForSpeechSeq2Seq,L.AutoModelForCTC],processor:j.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:f.AutoTokenizer,pipeline:he,model:[L.AutoModelForTextToWaveform,L.AutoModelForTextToSpectrogram],processor:[j.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:f.AutoTokenizer,pipeline:xe,model:L.AutoModelForVision2Seq,processor:j.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Le,model:L.AutoModelForImageClassification,processor:j.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:qe,model:[L.AutoModelForImageSegmentation,L.AutoModelForSemanticSegmentation,L.AutoModelForUniversalSegmentation],processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:f.AutoTokenizer,pipeline:je,model:L.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:dt,model:L.AutoModelForObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:f.AutoTokenizer,pipeline:ue,model:L.AutoModelForZeroShotObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:f.AutoTokenizer,pipeline:te,model:L.AutoModelForDocumentQuestionAnswering,processor:j.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Te,model:L.AutoModelForImageToImage,processor:j.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ze,model:L.AutoModelForDepthEstimation,processor:j.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:f.AutoTokenizer,pipeline:Y,model:L.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:j.AutoProcessor,pipeline:le,model:[L.AutoModelForImageFeatureExtraction,L.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Xe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function oe(Fe,pe=null,{progress_callback:ve=null,config:Re=null,cache_dir:We=null,local_files_only:Ve=!1,revision:Ne="main",device:Ze=null,dtype:at=null,model_file_name:ft=null,session_options:lt={}}={}){Fe=Xe[Fe]??Fe;const ht=et[Fe.split("_",1)[0]];if(!ht)throw Error(`Unsupported pipeline: ${Fe}. Must be one of [${Object.keys(et)}]`);pe||(pe=ht.default.model,console.log(`No model specified. Using default model: "${pe}".`));const I={progress_callback:ve,config:Re,cache_dir:We,local_files_only:Ve,revision:Ne,device:Ze,dtype:at,model_file_name:ft,session_options:lt},ne=new Map([["tokenizer",ht.tokenizer],["model",ht.model],["processor",ht.processor]]),K=await Je(ne,pe,I);K.task=Fe,(0,W.dispatchCallback)(ve,{status:"ready",task:Fe,model:pe});const ce=ht.pipeline;return new ce(K)}async function Je(Fe,pe,ve){const Re=Object.create(null),We=[];for(const[Ve,Ne]of Fe.entries()){if(!Ne)continue;let Ze;Array.isArray(Ne)?Ze=new Promise(async(at,ft)=>{var ht,I;let lt;for(const ne of Ne){if(ne===null){at(null);return}try{at(await ne.from_pretrained(pe,ve));return}catch(K){if((ht=K.message)!=null&&ht.includes("Unsupported model type"))lt=K;else if((I=K.message)!=null&&I.includes("Could not locate file"))lt=K;else{ft(K);return}}}ft(lt)}):Ze=Ne.from_pretrained(pe,ve),Re[Ve]=Ze,We.push(Ze)}await Promise.all(We);for(const[Ve,Ne]of Object.entries(Re))Re[Ve]=await Ne;return Re}},"./src/tokenizers.js":(De,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>kr,AutoTokenizer:()=>vn,BartTokenizer:()=>ts,BertTokenizer:()=>Yr,BlenderbotSmallTokenizer:()=>zn,BlenderbotTokenizer:()=>yn,BloomTokenizer:()=>Nr,CLIPTokenizer:()=>Fn,CamembertTokenizer:()=>nt,CodeGenTokenizer:()=>On,CodeLlamaTokenizer:()=>jr,CohereTokenizer:()=>Bn,ConvBertTokenizer:()=>Ar,DebertaTokenizer:()=>or,DebertaV2Tokenizer:()=>$r,DistilBertTokenizer:()=>ar,ElectraTokenizer:()=>Ot,EsmTokenizer:()=>lr,FalconTokenizer:()=>Wr,GPT2Tokenizer:()=>vr,GPTNeoXTokenizer:()=>xr,GemmaTokenizer:()=>en,Grok1Tokenizer:()=>gn,HerbertTokenizer:()=>pr,LlamaTokenizer:()=>An,M2M100Tokenizer:()=>zt,MBart50Tokenizer:()=>Rr,MBartTokenizer:()=>er,MPNetTokenizer:()=>ni,MarianTokenizer:()=>Ur,MgpstrTokenizer:()=>bn,MobileBertTokenizer:()=>Br,NllbTokenizer:()=>Er,NougatTokenizer:()=>Qs,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>fn,RoFormerTokenizer:()=>Jr,RobertaTokenizer:()=>Zr,SiglipTokenizer:()=>Dn,SpeechT5Tokenizer:()=>os,SqueezeBertTokenizer:()=>Sr,T5Tokenizer:()=>ls,TokenizerModel:()=>le,VitsTokenizer:()=>Mn,Wav2Vec2CTCTokenizer:()=>Ln,WhisperTokenizer:()=>wn,XLMRobertaTokenizer:()=>In,XLMTokenizer:()=>gt,is_chinese_char:()=>Q});var f=r("./src/utils/generic.js"),L=r("./src/utils/core.js"),j=r("./src/utils/hub.js"),J=r("./src/utils/maths.js"),W=r("./src/utils/tensor.js"),w=r("./src/utils/data-structures.js"),v=r("./node_modules/@huggingface/jinja/dist/index.js"),y=r("./src/models/whisper/common_whisper.js");async function M(Ee,P){const q=await Promise.all([(0,j.getModelJSON)(Ee,"tokenizer.json",!0,P),(0,j.getModelJSON)(Ee,"tokenizer_config.json",!0,P)]);return P.legacy!==null&&(q[1].legacy=P.legacy),q}function b(Ee,P){const q=[];let ae=0;for(const be of Ee.matchAll(P)){const Ce=be[0];ae0&&q.push(Ce),ae=be.index+Ce.length}return ae=19968&&Ee<=40959||Ee>=13312&&Ee<=19903||Ee>=131072&&Ee<=173791||Ee>=173824&&Ee<=177983||Ee>=177984&&Ee<=178207||Ee>=178208&&Ee<=183983||Ee>=63744&&Ee<=64255||Ee>=194560&&Ee<=195103}function F(Ee,P,q){const ae=[];let be=0;for(;bethis.tokens_to_ids.get(q)??this.unk_token_id)}convert_ids_to_tokens(P){return P.map(q=>this.vocab[q]??this.unk_token)}}class de extends le{constructor(P){super(P),this.tokens_to_ids=H(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.max_input_chars_per_word=P.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[q,ae]of this.tokens_to_ids)this.vocab[ae]=q}encode(P){const q=[];for(const ae of P){const be=[...ae];if(be.length>this.max_input_chars_per_word){q.push(this.unk_token);continue}let Ce=!1,He=0;const ct=[];for(;He0&&(ot=this.config.continuing_subword_prefix+ot),this.tokens_to_ids.has(ot)){mt=ot;break}--yt}if(mt===null){Ce=!0;break}ct.push(mt),He=yt}Ce?q.push(this.unk_token):q.push(...ct)}return q}}class fe extends le{constructor(P,q){super(P);const ae=P.vocab.length;this.vocab=new Array(ae),this.scores=new Array(ae);for(let be=0;be[be,Ce])),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,J.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new w.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(P){const q=P.chars,ae=1;let be=0;for(;be{const Ee=[...Array.from({length:94},(be,Ce)=>Ce+33),...Array.from({length:12},(be,Ce)=>Ce+161),...Array.from({length:82},(be,Ce)=>Ce+174)],P=Ee.slice();let q=0;for(let be=0;be<256;++be)Ee.includes(be)||(Ee.push(be),P.push(256+q),q+=1);const ae=P.map(be=>String.fromCharCode(be));return Object.fromEntries(Ee.map((be,Ce)=>[be,ae[Ce]]))})(),xe=(0,L.reverseDictionary)(Pe);class Le extends le{constructor(P){super(P),this.tokens_to_ids=H(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ae,be]of this.tokens_to_ids)this.vocab[be]=ae;const q=Array.isArray(P.merges[0]);this.merges=q?P.merges:P.merges.map(ae=>ae.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ae,be)=>[JSON.stringify(ae),be])),this.end_of_word_suffix=P.end_of_word_suffix,this.continuing_subword_suffix=P.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(P){if(P.length===0)return[];const q=this.cache.get(P);if(q!==void 0)return q;const ae=Array.from(P);this.end_of_word_suffix&&(ae[ae.length-1]+=this.end_of_word_suffix);let be=[];if(ae.length>1){const Ce=new w.PriorityQueue((yt,mt)=>yt.score`<0x${ct.toString(16).toUpperCase().padStart(2,"0")}>`);He.every(ct=>this.tokens_to_ids.has(ct))?q.push(...He):q.push(this.unk_token)}else q.push(this.unk_token)}return q}}class qe extends le{constructor(P,q){super(P),this.tokens_to_ids=H(q.target_lang?P.vocab[q.target_lang]:P.vocab),this.bos_token=q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=q.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[ae,be]of this.tokens_to_ids)this.vocab[be]=ae}encode(P){return P}}class je extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"BertNormalizer":return new Je(P);case"Precompiled":return new gs(P);case"Sequence":return new oe(P);case"Replace":return new dt(P);case"NFC":return new ue(P);case"NFKC":return new te(P);case"NFKD":return new he(P);case"Strip":return new Te(P);case"StripAccents":return new ze(P);case"Lowercase":return new et(P);case"Prepend":return new Xe(P);default:throw new Error(`Unknown Normalizer type: ${P.type}`)}}normalize(P){throw Error("normalize should be implemented in subclass.")}_call(P){return this.normalize(P)}}class dt extends je{normalize(P){const q=D(this.config.pattern);return q===null?P:P.replaceAll(q,this.config.content)}}class ue extends je{normalize(P){return P=P.normalize("NFC"),P}}class te extends je{normalize(P){return P=P.normalize("NFKC"),P}}class he extends je{normalize(P){return P=P.normalize("NFKD"),P}}class Te extends je{normalize(P){return this.config.strip_left&&this.config.strip_right?P=P.trim():(this.config.strip_left&&(P=P.trimStart()),this.config.strip_right&&(P=P.trimEnd())),P}}class ze extends je{normalize(P){return P=z(P),P}}class et extends je{normalize(P){return P=P.toLowerCase(),P}}class Xe extends je{normalize(P){return P=this.config.prepend+P,P}}class oe extends je{constructor(P){super(P),this.normalizers=P.normalizers.map(q=>je.fromConfig(q))}normalize(P){return this.normalizers.reduce((q,ae)=>ae.normalize(q),P)}}class Je extends je{_tokenize_chinese_chars(P){const q=[];for(let ae=0;aethis.pre_tokenize_text(ae,q)):this.pre_tokenize_text(P,q)).flat()}_call(P,q){return this.pre_tokenize(P,q)}}class pe extends Fe{constructor(P){super(),this.pattern=new RegExp(`[^\\s${g}]+|[${g}]`,"gu")}pre_tokenize_text(P,q){return P.trim().match(this.pattern)||[]}}class ve extends Fe{constructor(P){super(),this.config=P,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=Pe,this.text_encoder=new TextEncoder}pre_tokenize_text(P,q){return this.add_prefix_space&&!P.startsWith(" ")&&(P=" "+P),(this.use_regex?P.match(this.pattern)||[]:[P]).map(be=>Array.from(this.text_encoder.encode(be),Ce=>this.byte_encoder[Ce]).join(""))}}class Re extends Fe{constructor(P){super(),this.config=P,this.pattern=D(this.config.pattern,this.config.invert)}pre_tokenize_text(P,q){var ae;return this.pattern===null?[]:this.config.invert?P.match(this.pattern)||[]:((ae=this.config.behavior)==null?void 0:ae.toLowerCase())==="removed"?P.split(this.pattern).filter(be=>be):b(P,this.pattern)}}class We extends Fe{constructor(P){super(),this.config=P,this.pattern=new RegExp(`[^${g}]+|[${g}]+`,"gu")}pre_tokenize_text(P,q){return P.match(this.pattern)||[]}}class Ve extends Fe{constructor(P){super(),this.config=P;const q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(q,"gu")}pre_tokenize_text(P,q){return P.match(this.pattern)||[]}}class Ne extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"TemplateProcessing":return new ft(P);case"ByteLevel":return new lt(P);case"RobertaProcessing":return new at(P);case"BertProcessing":return new Ze(P);case"Sequence":return new ht(P);default:throw new Error(`Unknown PostProcessor type: ${P.type}`)}}post_process(P,...q){throw Error("post_process should be implemented in subclass.")}_call(P,...q){return this.post_process(P,...q)}}class Ze extends Ne{constructor(P){super(P),this.cls=P.cls[0],this.sep=P.sep[0]}post_process(P,q=null,{add_special_tokens:ae=!0}={}){ae&&(P=(0,L.mergeArrays)([this.cls],P,[this.sep]));let be=new Array(P.length).fill(0);if(q!==null){const Ce=ae&&this instanceof at?[this.sep]:[],He=ae?[this.sep]:[];P=(0,L.mergeArrays)(P,Ce,q,He),be=(0,L.mergeArrays)(be,new Array(q.length+Ce.length+He.length).fill(1))}return{tokens:P,token_type_ids:be}}}class at extends Ze{}class ft extends Ne{constructor(P){super(P),this.single=P.single,this.pair=P.pair}post_process(P,q=null,{add_special_tokens:ae=!0}={}){const be=q===null?this.single:this.pair;let Ce=[],He=[];for(const ct of be)"SpecialToken"in ct?ae&&(Ce.push(ct.SpecialToken.id),He.push(ct.SpecialToken.type_id)):"Sequence"in ct&&(ct.Sequence.id==="A"?(Ce=(0,L.mergeArrays)(Ce,P),He=(0,L.mergeArrays)(He,new Array(P.length).fill(ct.Sequence.type_id))):ct.Sequence.id==="B"&&(Ce=(0,L.mergeArrays)(Ce,q),He=(0,L.mergeArrays)(He,new Array(q.length).fill(ct.Sequence.type_id))));return{tokens:Ce,token_type_ids:He}}}class lt extends Ne{post_process(P,q=null){return q&&(P=(0,L.mergeArrays)(P,q)),{tokens:P}}}class ht extends Ne{constructor(P){super(P),this.processors=P.processors.map(q=>Ne.fromConfig(q))}post_process(P,q=null,ae={}){let be;for(const Ce of this.processors)if(Ce instanceof lt)P=Ce.post_process(P).tokens,q&&(q=Ce.post_process(q).tokens);else{const He=Ce.post_process(P,q,ae);P=He.tokens,be=He.token_type_ids}return{tokens:P,token_type_ids:be}}}class I extends f.Callable{constructor(P){super(),this.config=P,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=P.trim_offsets}static fromConfig(P){if(P===null)return null;switch(P.type){case"WordPiece":return new Qe(P);case"Metaspace":return new ns(P);case"ByteLevel":return new rt(P);case"Replace":return new ne(P);case"ByteFallback":return new K(P);case"Fuse":return new ce(P);case"Strip":return new Ie(P);case"Sequence":return new It(P);case"CTC":return new pt(P);case"BPEDecoder":return new St(P);default:throw new Error(`Unknown Decoder type: ${P.type}`)}}_call(P){return this.decode(P)}decode(P){return this.decode_chain(P).join("")}decode_chain(P){throw Error("`decode_chain` should be implemented in subclass.")}}class ne extends I{decode_chain(P){const q=D(this.config.pattern);return q===null?P:P.map(ae=>ae.replaceAll(q,this.config.content))}}class K extends I{constructor(P){super(P),this.text_decoder=new TextDecoder}decode_chain(P){const q=[];let ae=[];for(const be of P){let Ce=null;if(be.length===6&&be.startsWith("<0x")&&be.endsWith(">")){const He=parseInt(be.slice(3,5),16);isNaN(He)||(Ce=He)}if(Ce!==null)ae.push(Ce);else{if(ae.length>0){const He=this.text_decoder.decode(Uint8Array.from(ae));q.push(He),ae=[]}q.push(be)}}if(ae.length>0){const be=this.text_decoder.decode(Uint8Array.from(ae));q.push(be),ae=[]}return q}}class ce extends I{decode_chain(P){return[P.join("")]}}class Ie extends I{constructor(P){super(P),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(P){return P.map(q=>{let ae=0;for(let Ce=0;Ce(ae!==0&&(q.startsWith(this.config.prefix)?q=q.replace(this.config.prefix,""):q=" "+q),this.cleanup&&(q=ie(q)),q))}}class rt extends I{constructor(P){super(P),this.byte_decoder=xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(P){const q=P.join(""),ae=new Uint8Array([...q].map(Ce=>this.byte_decoder[Ce]));return this.text_decoder.decode(ae)}decode_chain(P){const q=[];let ae=[];for(const be of P)this.added_tokens.find(Ce=>Ce.content===be)!==void 0?(ae.length>0&&(q.push(this.convert_tokens_to_string(ae)),ae=[]),q.push(be)):ae.push(be);return ae.length>0&&q.push(this.convert_tokens_to_string(ae)),q}}class pt extends I{constructor(P){super(P),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(P){if(P.length===0)return"";const q=[P[0]];for(let Ce=1;CeCe!==this.pad_token).join("");return this.cleanup&&(be=ie(be).replaceAll(this.word_delimiter_token," ").trim()),be}decode_chain(P){return[this.convert_tokens_to_string(P)]}}class It extends I{constructor(P){super(P),this.decoders=P.decoders.map(q=>I.fromConfig(q))}decode_chain(P){return this.decoders.reduce((q,ae)=>ae.decode_chain(q),P)}}class St extends I{constructor(P){super(P),this.suffix=this.config.suffix}decode_chain(P){return P.map((q,ae)=>q.replaceAll(this.suffix,ae===P.length-1?"":" "))}}class Ft extends I{decode_chain(P){let q="";for(let ae=1;aeae.normalize("NFKC")).join("~"):P=P.normalize("NFKC"),P}}class Ss extends Fe{constructor(P){super(),this.tokenizers=P.pretokenizers.map(q=>Fe.fromConfig(q))}pre_tokenize_text(P,q){return this.tokenizers.reduce((ae,be)=>be.pre_tokenize(ae,q),[P])}}class As extends Fe{constructor(P){super()}pre_tokenize_text(P,q){return P.match(/\w+|[^\w\s]+/g)||[]}}class Xs extends Fe{constructor(P){super()}pre_tokenize_text(P,q){return $(P)}}class ir extends Fe{constructor(P){super(),this.config=P,this.pattern=D(this.config.pattern),this.content=this.config.content}pre_tokenize_text(P,q){return this.pattern===null?[P]:[P.replaceAll(this.pattern,this.config.content)]}}const Qr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function zr(Ee,P,q,ae){for(const be of Object.keys(Ee)){const Ce=P-Ee[be].length,He=q(be),ct=new Array(Ce).fill(He);Ee[be]=ae==="right"?(0,L.mergeArrays)(Ee[be],ct):(0,L.mergeArrays)(ct,Ee[be])}}function br(Ee,P){for(const q of Object.keys(Ee))Ee[q].length=P}class Nt extends f.Callable{constructor(q,ae){super();ge(this,"return_token_type_ids",!1);ge(this,"padding_side","right");this._tokenizer_config=ae,this.normalizer=je.fromConfig(q.normalizer),this.pre_tokenizer=Fe.fromConfig(q.pre_tokenizer),this.model=le.fromConfig(q.model,ae),this.post_processor=Ne.fromConfig(q.post_processor),this.decoder=I.fromConfig(q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const be of q.added_tokens){const Ce=new Y(be);this.added_tokens.push(Ce),this.model.tokens_to_ids.set(Ce.content,Ce.id),this.model.vocab[Ce.id]=Ce.content,Ce.special&&(this.special_tokens.push(Ce.content),this.all_special_ids.push(Ce.id))}if(this.additional_special_tokens=ae.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((be,Ce)=>Ce.content.length-be.content.length).map(be=>`${be.lstrip?"\\s*":""}(${(0,L.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=ae.model_max_length,this.remove_space=ae.remove_space,this.clean_up_tokenization_spaces=ae.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ae.do_lowercase_and_remove_accent??!1,ae.padding_side&&(this.padding_side=ae.padding_side),this.legacy=!1,this.chat_template=ae.chat_template??null,Array.isArray(this.chat_template)){const be=Object.create(null);for(const{name:Ce,template:He}of this.chat_template){if(typeof Ce!="string"||typeof He!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');be[Ce]=He}this.chat_template=be}this._compiled_template_cache=new Map}getToken(...q){for(const ae of q){const be=this._tokenizer_config[ae];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:ae=null,config:be=null,cache_dir:Ce=null,local_files_only:He=!1,revision:ct="main",legacy:yt=null}={}){const mt=await M(q,{progress_callback:ae,config:be,cache_dir:Ce,local_files_only:He,revision:ct,legacy:yt});return new this(...mt)}_call(q,{text_pair:ae=null,add_special_tokens:be=!0,padding:Ce=!1,truncation:He=null,max_length:ct=null,return_tensor:yt=!0,return_token_type_ids:mt=null}={}){const ot=Array.isArray(q);let Pt;if(ot){if(q.length===0)throw Error("text array must be non-empty");if(ae!==null){if(Array.isArray(ae)){if(q.length!==ae.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Pt=q.map((ss,Se)=>this._encode_plus(ss,{text_pair:ae[Se],add_special_tokens:be,return_token_type_ids:mt}))}else Pt=q.map(ss=>this._encode_plus(ss,{add_special_tokens:be,return_token_type_ids:mt}))}else{if(q==null)throw Error("text may not be null or undefined");if(Array.isArray(ae))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Pt=[this._encode_plus(q,{text_pair:ae,add_special_tokens:be,return_token_type_ids:mt})]}if(ct===null?Ce==="max_length"?ct=this.model_max_length:ct=(0,J.max)(Pt.map(ss=>ss.input_ids.length))[0]:He||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),ct=Math.min(ct,this.model_max_length??1/0),Ce||He)for(let ss=0;ssct?He&&br(Pt[ss],ct):Ce&&zr(Pt[ss],ct,Se=>Se==="input_ids"?this.pad_token_id:0,this.padding_side));const hs={};if(yt){if(!(Ce&&He)&&Pt.some(Se=>{var ws;for(const Rs of Object.keys(Se))if(Se[Rs].length!==((ws=Pt[0][Rs])==null?void 0:ws.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 ss=[Pt.length,Pt[0].input_ids.length];for(const Se of Object.keys(Pt[0]))hs[Se]=new W.Tensor("int64",BigInt64Array.from(Pt.flatMap(ws=>ws[Se]).map(BigInt)),ss)}else{for(const ss of Object.keys(Pt[0]))hs[ss]=Pt.map(Se=>Se[ss]);if(!ot)for(const ss of Object.keys(hs))hs[ss]=hs[ss][0]}return hs}_encode_text(q){return q===null?null:(this.added_tokens_regex?q.split(this.added_tokens_regex).filter(Ce=>Ce):[q]).map((Ce,He)=>{if(this.added_tokens.find(yt=>yt.content===Ce)!==void 0)return Ce;{if(this.remove_space===!0&&(Ce=Ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Ce=V(Ce)),this.normalizer!==null&&(Ce=this.normalizer(Ce)),Ce.length===0)return[];const yt=this.pre_tokenizer!==null?this.pre_tokenizer(Ce,{section_index:He}):[Ce];return this.model(yt)}}).flat()}_encode_plus(q,{text_pair:ae=null,add_special_tokens:be=!0,return_token_type_ids:Ce=null}={}){const{tokens:He,token_type_ids:ct}=this._tokenize_helper(q,{pair:ae,add_special_tokens:be}),yt=this.model.convert_tokens_to_ids(He),mt={input_ids:yt,attention_mask:new Array(yt.length).fill(1)};return(Ce??this.return_token_type_ids)&&ct&&(mt.token_type_ids=ct),mt}_tokenize_helper(q,{pair:ae=null,add_special_tokens:be=!1}={}){const Ce=this._encode_text(q),He=this._encode_text(ae);return this.post_processor?this.post_processor(Ce,He,{add_special_tokens:be}):{tokens:(0,L.mergeArrays)(Ce??[],He??[])}}tokenize(q,{pair:ae=null,add_special_tokens:be=!1}={}){return this._tokenize_helper(q,{pair:ae,add_special_tokens:be}).tokens}encode(q,{text_pair:ae=null,add_special_tokens:be=!0,return_token_type_ids:Ce=null}={}){return this._encode_plus(q,{text_pair:ae,add_special_tokens:be,return_token_type_ids:Ce}).input_ids}batch_decode(q,ae={}){return q instanceof W.Tensor&&(q=q.tolist()),q.map(be=>this.decode(be,ae))}decode(q,ae={}){if(q instanceof W.Tensor&&(q=re(q)),!Array.isArray(q)||q.length===0||!(0,L.isIntegralNumber)(q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(q,ae)}decode_single(q,{skip_special_tokens:ae=!1,clean_up_tokenization_spaces:be=null}){let Ce=this.model.convert_ids_to_tokens(q);ae&&(Ce=Ce.filter(ct=>!this.special_tokens.includes(ct)));let He=this.decoder?this.decoder(Ce):Ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(He=He.replaceAll(this.decoder.end_of_word_suffix," "),ae&&(He=He.trim())),(be??this.clean_up_tokenization_spaces)&&(He=ie(He)),He}get_chat_template({chat_template:q=null,tools:ae=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(ae!==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:ae=null,documents:be=null,chat_template:Ce=null,add_generation_prompt:He=!1,tokenize:ct=!0,padding:yt=!1,truncation:mt=!1,max_length:ot=null,return_tensor:Pt=!0,return_dict:hs=!1,tokenizer_kwargs:ss={},...Se}={}){if(Ce=this.get_chat_template({chat_template:Ce,tools:ae}),typeof Ce!="string")throw Error(`chat_template must be a string, but got ${typeof Ce}`);let ws=this._compiled_template_cache.get(Ce);ws===void 0&&(ws=new v.Template(Ce),this._compiled_template_cache.set(Ce,ws));const Rs=Object.create(null);for(const Js of Qr){const Bt=this.getToken(Js);Bt&&(Rs[Js]=Bt)}const Ys=ws.render({messages:q,add_generation_prompt:He,tools:ae,documents:be,...Rs,...Se});if(ct){const Js=this._call(Ys,{add_special_tokens:!1,padding:yt,truncation:mt,max_length:ot,return_tensor:Pt,...ss});return hs?Js:Js.input_ids}return Ys}}class Yr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class kr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Br extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Sr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class or extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class $r extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class pr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Ar extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Jr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class ar extends Nt{}class nt extends Nt{}class gt extends Nt{constructor(q,ae){super(q,ae);ge(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 Ot extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class ls extends Nt{}class vr extends Nt{}class ts extends Nt{}class er extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(P,q,ae){return tn(this,P,q,ae)}}class Rr extends er{}class Zr extends Nt{}class Nr extends Nt{}const Tr="▁";class An extends Nt{constructor(q,ae){super(q,ae);ge(this,"padding_side","left");this.legacy=ae.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:Tr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(q){if(q===null)return null;if(this.legacy||q.length===0)return super._encode_text(q);let ae=super._encode_text(Tr+q.replaceAll(Tr," "));return ae.length>1&&ae[0]===Tr&&this.special_tokens.includes(ae[1])&&(ae=ae.slice(1)),ae}}class jr extends Nt{}class In extends Nt{}class ni extends Nt{}class Wr extends Nt{}class xr extends Nt{}class lr extends Nt{}class fn extends Nt{}class en extends Nt{}class gn extends Nt{}function tn(Ee,P,q,ae){if(!("language_codes"in Ee)||!Array.isArray(Ee.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ee)||!(Ee.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ee)||typeof Ee.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const be=ae.src_lang,Ce=ae.tgt_lang;if(!Ee.language_codes.includes(Ce))throw new Error(`Target language code "${Ce}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);if(be!==void 0){if(!Ee.language_codes.includes(be))throw new Error(`Source language code "${be}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);for(const He of Ee.post_processor.config.single)if("SpecialToken"in He&&Ee.languageRegex.test(He.SpecialToken.id)){He.SpecialToken.id=Ee.lang_to_token(be);break}}return ae.forced_bos_token_id=Ee.model.convert_tokens_to_ids([Ee.lang_to_token(Ce)])[0],Ee._call(P,q)}class Er extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(P,q,ae){return tn(this,P,q,ae)}}class zt extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)).map(ae=>ae.slice(2,-2)),this.lang_to_token=ae=>`__${ae}__`}_build_translation_inputs(P,q,ae){return tn(this,P,q,ae)}}class wn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(P,{return_timestamps:q=!1,return_language:ae=!1,time_precision:be=null,force_full_sequences:Ce=!0}={}){if(be===null)throw Error("Must specify time_precision");let He=null;const ct=q==="word";function yt(){return{language:He,timestamp:[null,null],text:""}}const mt=[];let ot=yt(),Pt=0;const hs=this.timestamp_begin,Se=hs+1500;let ws=[],Rs=[],Ys=!1,Js=null;const Bt=new Set(this.all_special_ids);for(const es of P){const _s=es.tokens,vt=ct?es.token_timestamps:null;let ys=null,Pr=hs;if("stride"in es){const[Mt,bs,Be]=es.stride;if(Pt-=bs,Js=Mt-Be,bs&&(Pr=bs/be+hs),Be)for(let wt=_s.length-1;wt>=0;--wt){const tr=Number(_s[wt]);if(tr>=hs){if(ys!==null&&(tr-hs)*be=hs&&bs<=Se){const Be=(bs-hs)*be+Pt,wt=(0,J.round)(Be,2);if(ys!==null&&bs>=ys)Ys=!0;else if(Ys||ws.length>0&&bs0?(ws.push(Ds),ct&&Rs.push(Hs)):ws.every(Mt=>Mt.length===0)&&(ot=yt(),ws=[],Ds=[],Rs=[],Hs=[])}if(ws.length>0){if(Ce&&q)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[es,_s]=this.findLongestCommonSequence(ws,Rs),vt=this.decode(es);ot.text=vt,ct&&(ot.words=this.collateWordTimestamps(es,_s,He)),mt.push(ot)}let Ns=Object.create(null);const hr=mt.map(es=>es.text).join("");if(q||ae){for(let es=0;es0;let ct=He?[]:null,yt=He?q[0]:null;for(let mt=1;mtbs===Pr[Be]&&yt[hr+Be]<=q[mt][vt+Be]).length:Ds=_s.filter((bs,Be)=>bs===Pr[Be]).length;const Hs=Ns/1e4,Mt=Ds/Ns+Hs;Ds>1&&Mt>Pt&&(Pt=Mt,hs=[hr,es,vt,ys])}const[Se,ws,Rs,Ys]=hs,Js=Math.floor((ws+Se)/2),Bt=Math.floor((Ys+Rs)/2);Ce.push(...ae.slice(0,Js)),ae=ot.slice(Bt),be=ae.length,He&&(ct.push(...yt.slice(0,Js)),yt=q[mt].slice(Bt))}return Ce.push(...ae),He?(ct.push(...yt),[Ce,ct]):[Ce,[]]}collateWordTimestamps(P,q,ae){const[be,Ce,He]=this.combineTokensIntoWords(P,ae),ct=[];for(let yt=0;yt=be){const ct=((He-be)*ae).toFixed(2);Ce.push(`<|${ct}|>`),Ce.push([])}else Ce[Ce.length-1].push(He);return Ce=Ce.map(He=>typeof He=="string"?He:super.decode(He,q)),Ce.join("")}splitTokensOnUnicode(P){const q=this.decode(P,{decode_with_timestamps:!0}),ae="�",be=[],Ce=[],He=[];let ct=[],yt=[],mt=0;for(let ot=0;ot=this.model.tokens_to_ids.get("<|endoftext|>"),Se=ot.startsWith(" "),ws=ot.trim(),Rs=yt.test(ws);if(ss||Se||Rs||Ce.length===0)Ce.push(ot),He.push(Pt),ct.push(hs);else{const Ys=Ce.length-1;Ce[Ys]+=ot,He[Ys].push(...Pt),ct[Ys].push(...hs)}}return[Ce,He,ct]}mergePunctuations(P,q,ae,be,Ce){const He=structuredClone(P),ct=structuredClone(q),yt=structuredClone(ae);let mt=He.length-2,ot=He.length-1;for(;mt>=0;)He[mt].startsWith(" ")&&be.includes(He[mt].trim())?(He[ot]=He[mt]+He[ot],ct[ot]=(0,L.mergeArrays)(ct[mt],ct[ot]),yt[ot]=(0,L.mergeArrays)(yt[mt],yt[ot]),He[mt]="",ct[mt]=[],yt[mt]=[]):ot=mt,--mt;for(mt=0,ot=1;otPt),ct.filter(Pt=>Pt.length>0),yt.filter(Pt=>Pt.length>0)]}}class On extends Nt{}class Fn extends Nt{}class Dn extends Nt{}class Ur extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ae=>this.languageRegex.test(ae)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(P){if(P===null)return null;const[q,...ae]=P.trim().split(this.languageRegex);if(ae.length===0)return super._encode_text(q);if(ae.length===2){const[be,Ce]=ae;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,L.mergeArrays)([be],super._encode_text(Ce))}}}class Ln extends Nt{}class yn extends Nt{}class zn extends Nt{}class os extends Nt{}class Qs extends Nt{}class Mn extends Nt{constructor(P,q){super(P,q),this.decoder=new Ft({})}}class Bn extends Nt{}class bn extends Nt{}class vn{static async from_pretrained(P,{progress_callback:q=null,config:ae=null,cache_dir:be=null,local_files_only:Ce=!1,revision:He="main",legacy:ct=null}={}){var hs;const[yt,mt]=await M(P,{progress_callback:q,config:ae,cache_dir:be,local_files_only:Ce,revision:He,legacy:ct}),ot=((hs=mt.tokenizer_class)==null?void 0:hs.replace(/Fast$/,""))??"PreTrainedTokenizer";let Pt=this.TOKENIZER_CLASS_MAPPING[ot];return Pt||(console.warn(`Unknown tokenizer class "${ot}", attempting to construct from base class.`),Pt=Nt),new Pt(yt,mt)}}ge(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:ls,DistilBertTokenizer:ar,CamembertTokenizer:nt,DebertaTokenizer:or,DebertaV2Tokenizer:$r,BertTokenizer:Yr,HerbertTokenizer:pr,ConvBertTokenizer:Ar,RoFormerTokenizer:Jr,XLMTokenizer:gt,ElectraTokenizer:Ot,MobileBertTokenizer:Br,SqueezeBertTokenizer:Sr,AlbertTokenizer:kr,GPT2Tokenizer:vr,BartTokenizer:ts,MBartTokenizer:er,MBart50Tokenizer:Rr,RobertaTokenizer:Zr,WhisperTokenizer:wn,CodeGenTokenizer:On,CLIPTokenizer:Fn,SiglipTokenizer:Dn,MarianTokenizer:Ur,BloomTokenizer:Nr,NllbTokenizer:Er,M2M100Tokenizer:zt,LlamaTokenizer:An,CodeLlamaTokenizer:jr,XLMRobertaTokenizer:In,MPNetTokenizer:ni,FalconTokenizer:Wr,GPTNeoXTokenizer:xr,EsmTokenizer:lr,Wav2Vec2CTCTokenizer:Ln,BlenderbotTokenizer:yn,BlenderbotSmallTokenizer:zn,SpeechT5Tokenizer:os,NougatTokenizer:Qs,VitsTokenizer:Mn,Qwen2Tokenizer:fn,GemmaTokenizer:en,Grok1Tokenizer:gn,CohereTokenizer:Bn,MgpstrTokenizer:bn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(De,A,r)=>{r.r(A),r.d(A,{hamming:()=>y,hanning:()=>v,mel_filter_bank:()=>z,read_audio:()=>W,spectrogram:()=>g,window_function:()=>C});var f=r("./src/utils/hub.js"),L=r("./src/utils/maths.js"),j=r("./src/utils/core.js"),J=r("./src/utils/tensor.js");async function W(T,ee){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const Y=await(await(0,f.getFile)(T)).arrayBuffer(),le=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${le.sampleRate}Hz.`);const de=await le.decodeAudioData(Y);let fe;if(de.numberOfChannels===2){const Pe=Math.sqrt(2),xe=de.getChannelData(0),Le=de.getChannelData(1);fe=new Float32Array(xe.length);for(let qe=0;qe2595*Math.log10(1+T/700),kaldi:T=>1127*Math.log(1+T/700),slaney:(T,ee=1e3,Y=15,le=27/Math.log(6.4))=>T>=ee?Y+Math.log(T/ee)*le:3*T/200};function b(T,ee="htk"){const Y=M[ee];if(!Y)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?Y(T):T.map(le=>Y(le))}const D={htk:T=>700*(10**(T/2595)-1),kaldi:T=>700*(Math.exp(T/1127)-1),slaney:(T,ee=1e3,Y=15,le=Math.log(6.4)/27)=>T>=Y?ee*Math.exp(le*(T-Y)):200*T/3};function H(T,ee="htk"){const Y=D[ee];if(!Y)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?Y(T):T.map(le=>Y(le))}function re(T,ee){const Y=Float64Array.from({length:ee.length-1},(Pe,xe)=>ee[xe+1]-ee[xe]),le=Array.from({length:T.length},()=>new Array(ee.length));for(let Pe=0;Penew Array(T.length));for(let Pe=0;PeT+le*fe)}function z(T,ee,Y,le,de,fe=null,Pe="htk",xe=!1){if(fe!==null&&fe!=="slaney")throw new Error('norm must be one of null or "slaney"');const Le=b(Y,Pe),qe=b(le,Pe),je=ie(Le,qe,ee+2);let dt=H(je,Pe),ue;if(xe){const he=de/(T*2);ue=b(Float64Array.from({length:T},(Te,ze)=>ze*he),Pe),dt=je}else ue=ie(0,Math.floor(de/2),T);const te=re(ue,dt);if(fe!==null&&fe==="slaney")for(let he=0;hede)throw Error(`frame_length (${Y}) may not be larger than fft_length (${de})`);if(Fe!==Y)throw new Error(`Length of the window (${Fe}) must equal frame_length (${Y})`);if(le<=0)throw new Error("hop_length must be greater than zero");if(fe===null&&je!==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(Pe){if(xe!=="reflect")throw new Error(`pad_mode="${xe}" not implemented yet.`);const I=Math.floor((de-1)/2)+1;T=V(T,I,I)}let pe=Math.floor(1+Math.floor((T.length-Y)/le));et!==null&&pepe?oe&&(We=Xe):We=Re=Xe);const Ve=new L.FFT(de),Ne=new Float64Array(de),Ze=new Float64Array(Ve.outputBufferSize),at=new Float32Array(ve*We);for(let I=0;I=1;--ce)Ne[ce]-=qe*Ne[ce-1];Ne[0]*=1-qe}for(let ce=0;ceMath.pow(xe,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(Y&&(Pe=Pe.subarray(0,T)),le===null)return Pe;if(T>le)throw new Error(`Length of the window (${T}) may not be larger than frame_length (${le})`);return Pe}},"./src/utils/constants.js":(De,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>w,CONFIG_NAME:()=>L,FEATURE_EXTRACTOR_NAME:()=>j,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>f,IMAGE_PROCESSOR_NAME:()=>J,PROCESSOR_NAME:()=>W});const f="https://github.com/huggingface/transformers.js/issues/new/choose",L="config.json",j="preprocessor_config.json",J=j,W="processor_config.json",w="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(De,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>v,calculateReflectOffset:()=>D,count:()=>ie,dispatchCallback:()=>f,escapeRegExp:()=>j,isIntegralNumber:()=>W,isNullishDimension:()=>w,isTypedArray:()=>J,len:()=>re,mergeArrays:()=>M,pick:()=>H,pop:()=>y,product:()=>b,reverseDictionary:()=>L});function f(z,V){z&&z(V)}function L(z){return Object.fromEntries(Object.entries(z).map(([V,Q])=>[Q,V]))}function j(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(z){var V,Q,F;return((F=(Q=(V=z==null?void 0:z.prototype)==null?void 0:V.__proto__)==null?void 0:Q.constructor)==null?void 0:F.name)==="TypedArray"}function W(z){return Number.isInteger(z)||typeof z=="bigint"}function w(z){return z==null||z===-1}function v(z){const V=[];let Q=z;for(;Array.isArray(Q);)V.push(Q.length),Q=Q[0];return V}function y(z,V,Q=void 0){const F=z[V];if(F!==void 0)return delete z[V],F;if(Q===void 0)throw Error(`Key ${V} does not exist in object.`);return Q}function M(...z){return Array.prototype.concat.apply([],z)}function b(...z){return z.reduce((V,Q)=>V.flatMap(F=>Q.map($=>[F,$])))}function D(z,V){return Math.abs((z+V)%(2*V)-V)}function H(z,V){return Object.assign({},...V.map(Q=>{if(z[Q]!==void 0)return{[Q]:z[Q]}}))}function re(z){let V=0;for(const Q of z)++V;return V}function ie(z,V){let Q=0;for(const F of z)F===V&&++Q;return Q}},"./src/utils/data-structures.js":(De,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>L,PriorityQueue:()=>f,TokenLattice:()=>J});class f{constructor(v=(M,b)=>M>b,y=1/0){this._heap=[],this._comparator=v,this._maxSize=y}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...v){return this.extend(v)}extend(v){for(const y of v)if(this.size0&&this._swap(0,y),this._heap.pop(),this._siftDown(),v}replace(v){const y=this.peek();return this._heap[0]=v,this._siftDown(),y}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,y){return this._comparator(this._heap[v],this._heap[y])}_swap(v,y){const M=this._heap[v];this._heap[v]=this._heap[y],this._heap[y]=M}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(v){for(;v>0&&this._greater(v,this._parent(v));)this._swap(v,this._parent(v)),v=this._parent(v)}_siftDown(){let v=0;for(;this._left(v)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const b=new W(this.bosTokenId,0,0,0,0),D=new W(this.eosTokenId,1,this.len,0,0);this.nodes.push(b.clone()),this.nodes.push(D.clone()),this.beginNodes[this.len].push(D),this.endNodes[0].push(b)}insert(v,y,M,b){const D=this.nodes.length,H=new W(b,D,v,y,M);this.beginNodes[v].push(H),this.endNodes[v+y].push(H),this.nodes.push(H)}viterbi(){const v=this.len;let y=0;for(;y<=v;){if(this.beginNodes[y].length==0)return[];for(let re of this.beginNodes[y]){re.prev=null;let ie=0,z=null;for(let V of this.endNodes[y]){const Q=V.backtraceScore+re.score;(z===null||Q>ie)&&(z=V.clone(),ie=Q)}if(z!==null)re.prev=z,re.backtraceScore=ie;else return[]}++y}const M=[],D=this.beginNodes[v][0].prev;if(D===null)return[];let H=D.clone();for(;H.prev!==null;)M.push(H.clone()),H=H.clone().prev.clone();return M.reverse(),M}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(y=>this.piece(y))}tokenIds(){return this.viterbi().map(y=>y.tokenId)}}class W{constructor(v,y,M,b,D){this.tokenId=v,this.nodeId=y,this.pos=M,this.length=b,this.score=D,this.prev=null,this.backtraceScore=0}clone(){const v=new W(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(De,A,r)=>{r.r(A),r.d(A,{DEVICE_TYPES:()=>f});const f=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":(De,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>J,DEFAULT_DEVICE_DTYPE_MAPPING:()=>W,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>w,isWebGpuFp16Supported:()=>j});var f=r("./src/env.js"),L=r("./src/utils/devices.js");const j=function(){let v;return async function(){if(v===void 0)if(!f.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),J=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),W=Object.freeze({[L.DEVICE_TYPES.wasm]:J.q8}),w=Object.freeze({[J.fp32]:"",[J.fp16]:"_fp16",[J.int8]:"_int8",[J.uint8]:"_uint8",[J.q8]:"_quantized",[J.q4]:"_q4",[J.q4f16]:"_q4f16",[J.bnb4]:"_bnb4"})},"./src/utils/generic.js":(De,A,r)=>{r.r(A),r.d(A,{Callable:()=>f});const f=class{constructor(){let L=function(...j){return L._call(...j)};return Object.setPrototypeOf(L,new.target.prototype)}_call(...L){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(De,A,r)=>{r.r(A),r.d(A,{getFile:()=>y,getModelFile:()=>re,getModelJSON:()=>ie});var f=r("?7a2c"),L=r("?a42a"),j=r("./src/env.js"),J=r("./src/utils/core.js");const W={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 w{constructor(F){if(this.filePath=F,this.headers=new Headers,this.exists=f.existsSync(F),this.exists){this.status=200,this.statusText="OK";let $=f.statSync(F);this.headers.set("content-length",$.size.toString()),this.updateContentType();let g=this;this.body=new ReadableStream({start(C){g.arrayBuffer().then(T=>{C.enqueue(new Uint8Array(T)),C.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const F=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",W[F]??"application/octet-stream")}clone(){let F=new w(this.filePath);return F.exists=this.exists,F.status=this.status,F.statusText=this.statusText,F.headers=new Headers(this.headers),F}async arrayBuffer(){return(await f.promises.readFile(this.filePath)).buffer}async blob(){const F=await f.promises.readFile(this.filePath);return new Blob([F],{type:this.headers.get("content-type")})}async text(){return await f.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(Q,F=null,$=null){let g;try{g=new URL(Q)}catch{return!1}return!(F&&!F.includes(g.protocol)||$&&!$.includes(g.hostname))}async function y(Q){var F;if(j.env.useFS&&!v(Q,["http:","https:","blob:"]))return new w(Q);if(typeof process<"u"&&((F=process==null?void 0:process.release)==null?void 0:F.name)==="node"){const $=!!(nr!=null&&nr.TESTING_REMOTELY),g=j.env.version,C=new Headers;if(C.set("User-Agent",`transformers.js/${g}; is_ci/${$};`),v(Q,["http:","https:"],["huggingface.co","hf.co"])){const ee=(nr==null?void 0:nr.HF_TOKEN)??(nr==null?void 0:nr.HF_ACCESS_TOKEN);ee&&C.set("Authorization",`Bearer ${ee}`)}return fetch(Q,{headers:C})}else return fetch(Q)}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 b(Q,F,$){if(!$)return null;const g=M[Q]??`Error (${Q}) occurred while trying to load file`;throw Error(`${g}: "${F}".`)}class D{constructor(F){this.path=F}async match(F){let $=L.join(this.path,F),g=new w($);if(g.exists)return g}async put(F,$){const g=Buffer.from(await $.arrayBuffer());let C=L.join(this.path,F);try{await f.promises.mkdir(L.dirname(C),{recursive:!0}),await f.promises.writeFile(C,g)}catch(T){console.warn("An error occurred while writing the file to cache:",T)}}}async function H(Q,...F){for(let $ of F)try{let g=await Q.match($);if(g)return g}catch{continue}}async function re(Q,F,$=!0,g={}){if(!j.env.allowLocalModels){if(g.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(!j.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,J.dispatchCallback)(g.progress_callback,{status:"initiate",name:Q,file:F});let C;if(!C&&j.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{C=await caches.open("transformers-cache")}catch(dt){console.warn("An error occurred while opening the browser cache:",dt)}}if(!C&&j.env.useFSCache&&(C=new D(g.cache_dir??j.env.cacheDir)),!C&&j.env.useCustomCache){if(!j.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!j.env.customCache.match||!j.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");C=j.env.customCache}const T=g.revision??"main";let ee=V(Q,F),Y=V(j.env.localModelPath,ee),le=V(j.env.remoteHost,j.env.remotePathTemplate.replaceAll("{model}",Q).replaceAll("{revision}",encodeURIComponent(T)),F),de=T==="main"?ee:V(Q,T,F),fe,Pe=C instanceof D?de:le,xe=!1,Le;C&&(Le=await H(C,Y,Pe));const qe=Le!==void 0;if(Le===void 0){if(j.env.allowLocalModels)if(v(ee,["http:","https:"])){if(g.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ee}.`);if(!j.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ee}.`)}else try{Le=await y(Y),fe=Y}catch(ue){console.warn(`Unable to load from local path "${Y}": "${ue}"`)}if(Le===void 0||Le.status===404){if(g.local_files_only||!j.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Y}".`);return null}if(Le=await y(le),Le.status!==200)return b(Le.status,le,$);fe=Pe}xe=C&&typeof Response<"u"&&Le instanceof Response&&Le.status===200}(0,J.dispatchCallback)(g.progress_callback,{status:"download",name:Q,file:F});let je;return g.progress_callback?qe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(je=new Uint8Array(await Le.arrayBuffer()),(0,J.dispatchCallback)(g.progress_callback,{status:"progress",name:Q,file:F,progress:100,loaded:je.length,total:je.length})):je=await z(Le,dt=>{(0,J.dispatchCallback)(g.progress_callback,{status:"progress",name:Q,file:F,...dt})}):je=new Uint8Array(await Le.arrayBuffer()),xe&&fe&&await C.match(fe)===void 0&&await C.put(fe,new Response(je,{headers:Le.headers})).catch(dt=>{console.warn(`Unable to add response to browser cache: ${dt}.`)}),(0,J.dispatchCallback)(g.progress_callback,{status:"done",name:Q,file:F}),je}async function ie(Q,F,$=!0,g={}){let C=await re(Q,F,$,g);if(C===null)return{};let ee=new TextDecoder("utf-8").decode(C);return JSON.parse(ee)}async function z(Q,F){const $=Q.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let g=parseInt($??"0"),C=new Uint8Array(g),T=0;const ee=Q.body.getReader();async function Y(){const{done:le,value:de}=await ee.read();if(le)return;let fe=T+de.length;if(fe>g){g=fe;let xe=new Uint8Array(g);xe.set(C),C=xe}C.set(de,T),T=fe;const Pe=T/g*100;return F({progress:Pe,loaded:T,total:g}),Y()}return await Y(),C}function V(...Q){return Q=Q.map((F,$)=>($&&(F=F.replace(new RegExp("^/"),"")),$!==Q.length-1&&(F=F.replace(new RegExp("/$"),"")),F)),Q.join("/")}},"./src/utils/image.js":(De,A,r)=>{r.r(A),r.d(A,{RawImage:()=>H,load_image:()=>re});var f=r("./src/utils/core.js"),L=r("./src/utils/hub.js"),j=r("./src/env.js"),J=r("./src/utils/tensor.js"),W=r("?2b25");let w,v,y;const M=j.apis.IS_BROWSER_ENV||j.apis.IS_WEBWORKER_ENV;if(M)w=(ie,z)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ie,z)},y=self.createImageBitmap,v=self.ImageData;else if(W)y=async ie=>{const V=(await ie.metadata()).channels,{data:Q,info:F}=await ie.rotate().raw().toBuffer({resolveWithObject:!0}),$=new H(new Uint8ClampedArray(Q),F.width,F.height,F.channels);return V!==void 0&&V!==F.channels&&$.convert(V),$};else throw new Error("Unable to load image processing library.");const b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},D=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class H{constructor(z,V,Q,F){this.data=z,this.width=V,this.height=Q,this.channels=F}get size(){return[this.width,this.height]}static async read(z){if(z instanceof H)return z;if(typeof z=="string"||z instanceof URL)return await this.fromURL(z);throw new Error(`Unsupported input type: ${typeof z}`)}static fromCanvas(z){if(!M)throw new Error("fromCanvas() is only supported in browser environments.");const Q=z.getContext("2d").getImageData(0,0,z.width,z.height).data;return new H(Q,z.width,z.height,4)}static async fromURL(z){const V=await(0,L.getFile)(z);if(V.status!==200)throw new Error(`Unable to read image from "${z}" (${V.status} ${V.statusText})`);const Q=await V.blob();return this.fromBlob(Q)}static async fromBlob(z){if(M){const V=await y(z),Q=w(V.width,V.height).getContext("2d");return Q.drawImage(V,0,0),new this(Q.getImageData(0,0,V.width,V.height).data,V.width,V.height,4)}else{const V=W(await z.arrayBuffer());return await y(V)}}static fromTensor(z,V="CHW"){if(z.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${z.dims.length} dimensions.`);if(V==="CHW")z=z.transpose(1,2,0);else if(V!=="HWC")throw new Error(`Unsupported channel format: ${V}`);if(!(z.data instanceof Uint8ClampedArray||z.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${z.type}`);switch(z.dims[2]){case 1:case 2:case 3:case 4:return new H(z.data,z.dims[1],z.dims[0],z.dims[2]);default:throw new Error(`Unsupported number of channels: ${z.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const z=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let V=0,Q=0;V=0?T=Q:Y=-Q,F>=0?ee=F:le=-F,C.drawImage(g,T,ee,z,V,Y,le,z,V),new H(C.getImageData(0,0,z,V).data,z,V,4).convert($)}else{let $=this.toSharp();if(Q>=0&&F>=0)$=$.extract({left:Math.floor(Q),top:Math.floor(F),width:z,height:V});else if(Q<=0&&F<=0){const g=Math.floor(-F),C=Math.floor(-Q);$=$.extend({top:g,left:C,right:z-this.width-C,bottom:V-this.height-g})}else{let g=[0,0],C=0;F<0?(g[0]=Math.floor(-F),g[1]=V-this.height-g[0]):C=Math.floor(F);let T=[0,0],ee=0;Q<0?(T[0]=Math.floor(-Q),T[1]=z-this.width-T[0]):ee=Math.floor(Q),$=$.extend({top:g[0],bottom:g[1],left:T[0],right:T[1]}).extract({left:ee,top:C,width:z,height:V})}return await y($)}}async toBlob(z="image/png",V=1){if(!M)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:z,quality:V})}toTensor(z="CHW"){let V=new J.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(z!=="HWC")if(z==="CHW")V=V.permute(2,0,1);else throw new Error(`Unsupported channel format: ${z}`);return V}toCanvas(){if(!M)throw new Error("toCanvas() is only supported in browser environments.");const z=this.clone().rgba(),V=w(z.width,z.height),Q=new v(z.data,z.width,z.height);return V.getContext("2d").putImageData(Q,0,0),V}split(){const{data:z,width:V,height:Q,channels:F}=this,$=z.constructor,g=z.length/F,C=Array.from({length:F},()=>new $(g));for(let T=0;Tnew H(T,V,Q,1))}_update(z,V,Q,F=null){return this.data=z,this.width=V,this.height=Q,F!==null&&(this.channels=F),this}clone(){return new H(this.data.slice(),this.width,this.height,this.channels)}convert(z){if(this.channels===z)return this;switch(z){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(z){if(M){if(j.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const V=z.split(".").pop().toLowerCase(),Q=D.get(V)??"image/png",F=await this.toBlob(Q),$=URL.createObjectURL(F),g=document.createElement("a");g.href=$,g.download=z,g.click(),g.remove()}else{if(j.env.useFS)return await this.toSharp().toFile(z);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(M)throw new Error("toSharp() is only supported in server-side environments.");return W(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const re=H.read.bind(H)},"./src/utils/maths.js":(De,A,r)=>{r.r(A),r.d(A,{FFT:()=>re,bankers_round:()=>V,cos_sim:()=>w,dot:()=>W,dynamic_time_warping:()=>Q,interpolate_data:()=>f,log_softmax:()=>J,magnitude:()=>v,max:()=>M,medianFilter:()=>ie,min:()=>y,permute_data:()=>L,round:()=>z,softmax:()=>j});function f(F,[$,g,C],[T,ee],Y="bilinear",le=!1){const de=ee/C,fe=T/g,Pe=new F.constructor(T*ee*$),xe=g*C,Le=T*ee;for(let qe=0;qe=0;--le)T[le]=de,C[le]=$[g[le]],de*=C[le];const ee=g.map((le,de)=>T[g.indexOf(de)]),Y=new F.constructor(F.length);for(let le=0;le=0;--fe)de+=Pe%$[fe]*ee[fe],Pe=Math.floor(Pe/$[fe]);Y[de]=F[le]}return[Y,C]}function j(F){const $=M(F)[0],g=F.map(ee=>Math.exp(ee-$)),C=g.reduce((ee,Y)=>ee+Y,0);return g.map(ee=>ee/C)}function J(F){const $=M(F)[0];let g=0;for(let ee=0;eeee-$-C)}function W(F,$){let g=0;for(let C=0;C$+g*g,0))}function y(F){if(F.length===0)throw Error("Array must not be empty");let $=F[0],g=0;for(let C=1;C$&&($=F[C],g=C);return[$,g]}function b(F){return F>0&&(F&F-1)===0}class D{constructor($){if(this.size=$|0,this.size<=1||!b(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=$<<1,this.table=new Float64Array(this.size*2);for(let C=0;CC;C<<=1)++g;this._width=g%2===0?g-1:g,this._bitrev=new Int32Array(1<>>T&3)<>>1);for(let T=0;T<$.length;T+=2)C[T>>>1]=$[T];return C}toComplexArray($,g){const C=g||this.createComplexArray();for(let T=0;T>>1],C[T+1]=0;return C}transform($,g){if($===g)throw new Error("Input and output buffers must be different");this._transform4($,g,1)}realTransform($,g){if($===g)throw new Error("Input and output buffers must be different");this._realTransform4($,g,1)}inverseTransform($,g){if($===g)throw new Error("Input and output buffers must be different");this._transform4($,g,-1);for(let C=0;C<$.length;++C)$[C]/=this.size}_transform4($,g,C){const T=this._csize;let Y=1<>=2;Y>=2;Y>>=2){le=T/Y<<1;const Le=le>>>2;for(de=0;de>>1,Y>>>1)}else for(de=0,fe=0;de>>1,Y>>>1,C)}const xe=this.table;for(Y>>=2;Y>=2;Y>>=2){le=T/Y<<1;const qe=le>>>1,je=qe>>>1,dt=je>>>1;for(de=0;de>>1;for(let qe=2;qe>1;++Pe){const xe=(Pe+1-$)**2/2,Le=Math.sqrt(de**2+fe**2)**xe,qe=xe*Math.atan2(fe,de),je=2*Pe;ee[je]=Le*Math.cos(qe),ee[je+1]=Le*Math.sin(qe),Y[je]=ee[je],Y[je+1]=-ee[je+1]}this._slicedChirpBuffer=ee.subarray(g,C),this._f=new D(T>>1),this._f.transform(this._chirpBuffer,Y)}_transform($,g,C){const T=this._buffer1,ee=this._buffer2,Y=this._outBuffer1,le=this._outBuffer2,de=this._chirpBuffer,fe=this._slicedChirpBuffer,Pe=this._a;if(C)for(let xe=0;xe>1,je=g[qe];T[xe]=je*fe[xe],T[Le]=je*fe[Le]}else for(let xe=0;xe=F.length&&(de=2*(F.length-1)-de),C[Y++]=F[de]}C.sort(),g[ee]=C[T]}return g}function z(F,$){const g=Math.pow(10,$);return Math.round(F*g)/g}function V(F){const $=Math.round(F);return Math.abs(F)%1===.5?$%2===0?$:$-1:$}function Q(F){const $=F.length,g=F[0].length,C=[$+1,g+1],T=Array.from({length:C[0]},()=>Array(C[1]).fill(1/0));T[0][0]=0;const ee=Array.from({length:C[0]},()=>Array(C[1]).fill(-1));for(let Pe=1;Pe0||le>0;)switch(de.push(Y-1),fe.push(le-1),ee[Y][le]){case 0:--Y,--le;break;case 1:--Y;break;case 2:--le;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${Y}, ${le}]. Please file a bug report.`)}return de.reverse(),fe.reverse(),[de,fe]}},"./src/utils/tensor.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>W,cat:()=>g,full:()=>de,full_like:()=>fe,interpolate:()=>y,interpolate_4d:()=>M,layer_norm:()=>V,matmul:()=>b,mean:()=>ee,mean_pooling:()=>z,ones:()=>Pe,ones_like:()=>xe,permute:()=>v,quantize_embeddings:()=>dt,rand:()=>je,rfft:()=>D,slice:()=>ie,stack:()=>C,std_mean:()=>T,topk:()=>H,zeros:()=>Le,zeros_like:()=>qe});var f=r("./src/utils/maths.js"),L=r("./src/backends/onnx.js"),j=r("./src/ops/registry.js");const J=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 W{constructor(...te){ge(this,"ort_tensor");return(0,L.isONNXTensor)(te[0])?this.ort_tensor=te[0]:this.ort_tensor=new L.Tensor(te[0],te[1],te[2]),new Proxy(this,{get:(he,Te)=>{if(typeof Te=="string"){let ze=Number(Te);if(Number.isInteger(ze))return he._getitem(ze)}return he[Te]},set:(he,Te,ze)=>he[Te]=ze})}get dims(){return this.ort_tensor.dims}set dims(te){this.ort_tensor.dims=te}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[te,...he]=this.dims;if(he.length>0){const Te=he.reduce((ze,et)=>ze*et);for(let ze=0;ze0){const ze=Te.reduce((et,Xe)=>et*Xe);return this._subarray(te,ze,Te)}else return new W(this.type,[this.data[te]],Te)}indexOf(te){const he=this.data;for(let Te=0;TeRe)throw new Error(`Invalid slice: ${pe}`);const We=[Math.max(ve,0),Math.min(Re,this.dims[Fe])];Te.push(We),he.push(We[1]-We[0])}else throw new Error(`Invalid slice: ${pe}`)}const ze=Te.map(([Fe,pe])=>pe-Fe),et=ze.reduce((Fe,pe)=>Fe*pe),Xe=this.data,oe=new Xe.constructor(et),Je=this.stride();for(let Fe=0;Fe=0;--ve){const We=ze[ve];pe+=(Re%We+Te[ve][0])*Je[ve],Re=Math.floor(Re/We)}oe[Fe]=Xe[pe]}return new W(this.type,oe,he)}permute(...te){return v(this,te)}transpose(...te){return this.permute(...te)}sum(te=null,he=!1){return this.norm(1,te,he)}norm(te="fro",he=null,Te=!1){if(te==="fro")te=2;else if(typeof te=="string")throw Error(`Unsupported norm: ${te}`);const ze=this.data;if(he===null){let oe=ze.reduce((Je,Fe)=>Je+Fe**te,0)**(1/te);return new W(this.type,[oe],[])}he=$(he,this.dims.length);const et=this.dims.slice();et[he]=1;const Xe=new ze.constructor(ze.length/this.dims[he]);for(let oe=0;oe=0;--Fe){const Re=this.dims[Fe];if(Fe!==he){const We=pe%Re;Je+=We*ve,ve*=et[Fe]}pe=Math.floor(pe/Re)}Xe[Je]+=ze[oe]**te}if(te!==1)for(let oe=0;oe=0;--Je){const ve=this.dims[Je];if(Je!==he){const Re=Fe%ve;oe+=Re*pe,pe*=this.dims[Je]}Fe=Math.floor(Fe/ve)}ze[Xe]/=et[oe]}return this}normalize(te=2,he=1){return this.clone().normalize_(te,he)}stride(){return Y(this.dims)}squeeze(te=null){return new W(this.type,this.data,Q(this.dims,te))}squeeze_(te=null){return this.dims=Q(this.dims,te),this}unsqueeze(te=null){return new W(this.type,this.data,F(this.dims,te))}unsqueeze_(te=null){return this.dims=F(this.dims,te),this}flatten_(te=0,he=-1){he=(he+this.dims.length)%this.dims.length;let Te=this.dims.slice(0,te),ze=this.dims.slice(te,he+1),et=this.dims.slice(he+1);return this.dims=[...Te,ze.reduce((Xe,oe)=>Xe*oe,1),...et],this}flatten(te=0,he=-1){return this.clone().flatten_(te,he)}view(...te){let he=-1;for(let ze=0;zeoe!==he?et*Xe:et,1);te[he]=Te.length/ze}return new W(this.type,Te,te)}neg_(){const te=this.data;for(let he=0;heet*Xe);if(he!==Te)throw Error(`cannot reshape array of size ${he} into shape (${te})`);let ze=ue;for(let et=te.length-1;et>=0;et--)ze=ze.reduce((Xe,oe)=>{let Je=Xe[Xe.length-1];return Je.lengthnew W("int64",ue,[ue.length]);async function ie(ue,te,he,Te,ze){return await(await j.TensorOpRegistry.slice)({x:ue,s:re(te),e:re(he),a:re(Te),t:re(ze??new Array(Te.length).fill(1))})}function z(ue,te){const he=ue.data,Te=te.data,ze=[ue.dims[0],ue.dims[2]],et=new he.constructor(ze[0]*ze[1]),[Xe,oe,Je]=ue.dims;let Fe=0;for(let pe=0;pehe!==1):typeof te=="number"?ue[te]===1&&ue.splice(te,1):Array.isArray(te)&&(ue=ue.filter((he,Te)=>he!==1||!te.includes(Te))),ue}function F(ue,te){return te=$(te,ue.length+1),ue=ue.slice(),ue.splice(te,0,1),ue}function $(ue,te,he=null,Te=!0){if(Te&&(ue<-te||ue>=te))throw new Error(`IndexError: index ${ue} is out of bounds for dimension${he===null?"":" "+he} with size ${te}`);return ue<0&&(ue=(ue%te+te)%te),ue}function g(ue,te=0){te=$(te,ue[0].dims.length);const he=ue[0].dims.slice();he[te]=ue.reduce((Xe,oe)=>Xe+oe.dims[te],0);const Te=he.reduce((Xe,oe)=>Xe*oe,1),ze=new ue[0].data.constructor(Te),et=ue[0].type;if(te===0){let Xe=0;for(const oe of ue){const Je=oe.data;ze.set(Je,Xe),Xe+=Je.length}}else{let Xe=0;for(let oe=0;oe=0;--Re){const Ne=Fe[Re];let Ze=We%Ne;Re===te&&(Ze+=Xe),ve+=Ze*Ve,Ve*=he[Re],We=Math.floor(We/Ne)}ze[ve]=Je[pe]}Xe+=Fe[te]}}return new W(et,ze,he)}function C(ue,te=0){return g(ue.map(he=>he.unsqueeze(te)),te)}function T(ue,te=null,he=1,Te=!1){const ze=ue.data,et=ue.dims;if(te===null){const Re=ze.reduce((Ze,at)=>Ze+at,0)/ze.length,We=Math.sqrt(ze.reduce((Ze,at)=>Ze+(at-Re)**2,0)/(ze.length-he)),Ve=new W(ue.type,[Re],[]);return[new W(ue.type,[We],[]),Ve]}te=$(te,et.length);const Xe=ee(ue,te,Te),oe=Xe.data,Je=et.slice();Je[te]=1;const Fe=new ze.constructor(ze.length/et[te]);for(let ve=0;ve=0;--We){const Ze=et[We];if(We!==te){const at=Ve%Ze;Re+=at*Ne,Ne*=Je[We]}Ve=Math.floor(Ve/Ze)}Fe[Re]+=(ze[ve]-oe[Re])**2}for(let ve=0;veJe+Fe,0);return new W(ue.type,[oe/Te.length],[])}const ze=ue.dims;te=$(te,ze.length);const et=ze.slice();et[te]=1;const Xe=new Te.constructor(Te.length/ze[te]);for(let oe=0;oe=0;--Fe){const Re=ze[Fe];if(Fe!==te){const We=pe%Re;Je+=We*ve,ve*=et[Fe]}pe=Math.floor(pe/Re)}Xe[Je]+=Te[oe]}if(ze[te]!==1)for(let oe=0;oe=0;--he)te[he]=Te,Te*=ue[he];return te}function le(ue,te,he,Te){const ze=ue.reduce((et,Xe)=>et*Xe,1);return new W(he,new Te(ze).fill(te),ue)}function de(ue,te){let he,Te;if(typeof te=="number")he="float32",Te=Float32Array;else if(typeof te=="bigint")he="int64",Te=BigInt64Array;else if(typeof te=="boolean")he="bool",Te=Uint8Array;else throw new Error(`Unsupported data type: ${typeof te}`);return le(ue,te,he,Te)}function fe(ue,te){return de(ue.dims,te)}function Pe(ue){return le(ue,1n,"int64",BigInt64Array)}function xe(ue){return Pe(ue.dims)}function Le(ue){return le(ue,0n,"int64",BigInt64Array)}function qe(ue){return Le(ue.dims)}function je(ue){const te=ue.reduce((he,Te)=>he*Te,1);return new W("float32",Float32Array.from({length:te},()=>Math.random()),ue)}function dt(ue,te){if(ue.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ue.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(te))throw new Error("The precision must be either 'binary' or 'ubinary'");const he=te==="binary",Te=he?"int8":"uint8",ze=he?Int8Array:Uint8Array,et=ue.data,Xe=new ze(et.length/8);for(let oe=0;oe0?1:0,Fe=Math.floor(oe/8),pe=oe%8;Xe[Fe]|=Je<<7-pe,he&&pe===0&&(Xe[Fe]-=128)}return new W(Te,Xe,[ue.dims[0],ue.dims[1]/8])}}},ri={};function ms(De){var A=ri[De];if(A!==void 0)return A.exports;var r=ri[De]={exports:{}};return Xr[De](r,r.exports,ms),r.exports}ms.m=Xr,(()=>{var De=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;ms.t=function(r,f){if(f&1&&(r=this(r)),f&8||typeof r=="object"&&r&&(f&4&&r.__esModule||f&16&&typeof r.then=="function"))return r;var L=Object.create(null);ms.r(L);var j={};A=A||[null,De({}),De([]),De(De)];for(var J=f&2&&r;typeof J=="object"&&!~A.indexOf(J);J=De(J))Object.getOwnPropertyNames(J).forEach(W=>j[W]=()=>r[W]);return j.default=()=>r,ms.d(L,j),L}})(),ms.d=(De,A)=>{for(var r in A)ms.o(A,r)&&!ms.o(De,r)&&Object.defineProperty(De,r,{enumerable:!0,get:A[r]})},ms.o=(De,A)=>Object.prototype.hasOwnProperty.call(De,A),ms.r=De=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(De,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(De,"__esModule",{value:!0})},(()=>{var De;if(typeof self.location.href=="string"&&(De=self.location.href),!De)throw new Error("Automatic publicPath is not supported in this browser");De=De.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),ms.p=De})(),ms.b=new URL("./",self.location.href);var c={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/ms.r(c),ms.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:()=>f.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>L.AutoConfig,AutoFeatureExtractor:()=>M.AutoFeatureExtractor,AutoImageProcessor:()=>H.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>z.AutoProcessor,AutoTokenizer:()=>f.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>f.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>V.BaseStreamer,BeitFeatureExtractor:()=>D.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:()=>f.BertTokenizer,BitImageProcessor:()=>D.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>f.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>f.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>f.BloomTokenizer,CLIPFeatureExtractor:()=>D.CLIPFeatureExtractor,CLIPImageProcessor:()=>D.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>f.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:()=>f.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>D.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>y.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>F.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>f.CodeGenTokenizer,CodeLlamaTokenizer:()=>f.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>f.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>f.ConvBertTokenizer,ConvNextFeatureExtractor:()=>D.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>D.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>D.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>D.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:()=>f.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>f.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>D.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>D.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>D.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>D.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:()=>f.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>D.DonutFeatureExtractor,DonutImageProcessor:()=>D.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>D.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:()=>f.ElectraTokenizer,EosTokenCriteria:()=>Q.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>f.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>w.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>f.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ie.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>F.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>F.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>D.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>f.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:()=>f.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>f.GemmaTokenizer,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>f.Grok1Tokenizer,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HerbertTokenizer:()=>f.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:()=>D.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ie.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>y.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>b.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Q.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>D.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ie.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>f.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>D.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>F.LogitsProcessor,LogitsProcessorList:()=>F.LogitsProcessorList,LogitsWarper:()=>F.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>f.M2M100Tokenizer,MBart50Tokenizer:()=>f.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>f.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>f.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>f.MarianTokenizer,Mask2FormerImageProcessor:()=>D.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>D.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>D.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>Q.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ie.MgpstrProcessor,MgpstrTokenizer:()=>f.MgpstrTokenizer,MinLengthLogitsProcessor:()=>F.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>F.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:()=>f.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>D.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>D.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>D.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>D.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>D.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>D.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>D.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>D.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>D.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>D.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:()=>ie.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:()=>f.NllbTokenizer,NoBadWordsLogitsProcessor:()=>F.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>F.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>D.NougatImageProcessor,NougatTokenizer:()=>f.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>D.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>D.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ie.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>D.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ie.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:()=>D.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ie.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>f.PreTrainedTokenizer,PretrainedConfig:()=>L.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>re.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>D.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>y.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ie.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>f.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>D.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ie.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>D.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>J.RawImage,RepetitionPenaltyLogitsProcessor:()=>F.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:()=>f.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>f.RobertaTokenizer,SamImageProcessor:()=>D.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ie.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>y.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>D.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>D.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>D.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>f.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ie.SpeechT5Processor,SpeechT5Tokenizer:()=>f.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>f.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>Q.StoppingCriteria,StoppingCriteriaList:()=>Q.StoppingCriteriaList,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>F.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>D.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:()=>f.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>F.TemperatureLogitsWarper,Tensor:()=>W.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>V.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>f.TokenizerModel,TopKLogitsWarper:()=>F.TopKLogitsWarper,TopPLogitsWarper:()=>F.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ie.VLChatProcessor,VLMImageProcessor:()=>D.VLMImageProcessor,ViTFeatureExtractor:()=>D.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>D.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:()=>D.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>D.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>f.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>f.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>y.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>ie.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:()=>ie.WhisperProcessor,WhisperTextStreamer:()=>V.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>F.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>f.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:()=>f.XLMRobertaTokenizer,XLMTokenizer:()=>f.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>D.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>D.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>w.bankers_round,cat:()=>W.cat,cos_sim:()=>w.cos_sim,dot:()=>w.dot,dynamic_time_warping:()=>w.dynamic_time_warping,env:()=>De.env,full:()=>W.full,full_like:()=>W.full_like,getKeyValueShapes:()=>L.getKeyValueShapes,hamming:()=>j.hamming,hanning:()=>j.hanning,interpolate:()=>W.interpolate,interpolate_4d:()=>W.interpolate_4d,interpolate_data:()=>w.interpolate_data,is_chinese_char:()=>f.is_chinese_char,layer_norm:()=>W.layer_norm,load_image:()=>J.load_image,log_softmax:()=>w.log_softmax,magnitude:()=>w.magnitude,matmul:()=>W.matmul,max:()=>w.max,mean:()=>W.mean,mean_pooling:()=>W.mean_pooling,medianFilter:()=>w.medianFilter,mel_filter_bank:()=>j.mel_filter_bank,min:()=>w.min,ones:()=>W.ones,ones_like:()=>W.ones_like,permute:()=>W.permute,permute_data:()=>w.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>W.quantize_embeddings,rand:()=>W.rand,read_audio:()=>j.read_audio,rfft:()=>W.rfft,round:()=>w.round,slice:()=>W.slice,softmax:()=>w.softmax,spectrogram:()=>j.spectrogram,stack:()=>W.stack,std_mean:()=>W.std_mean,topk:()=>W.topk,window_function:()=>j.window_function,zeros:()=>W.zeros,zeros_like:()=>W.zeros_like});var De=ms("./src/env.js"),A=ms("./src/pipelines.js"),r=ms("./src/models.js"),f=ms("./src/tokenizers.js"),L=ms("./src/configs.js"),j=ms("./src/utils/audio.js"),J=ms("./src/utils/image.js"),W=ms("./src/utils/tensor.js"),w=ms("./src/utils/maths.js"),v=ms("./src/base/feature_extraction_utils.js"),y=ms("./src/models/feature_extractors.js"),M=ms("./src/models/auto/feature_extraction_auto.js"),b=ms("./src/base/image_processors_utils.js"),D=ms("./src/models/image_processors.js"),H=ms("./src/models/auto/image_processing_auto.js"),re=ms("./src/base/processing_utils.js"),ie=ms("./src/models/processors.js"),z=ms("./src/models/auto/processing_auto.js"),V=ms("./src/generation/streamers.js"),Q=ms("./src/generation/stopping_criteria.js"),F=ms("./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,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC;var Jm=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;var Zm=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.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.IJepaForImageClassification,c.IJepaModel,c.IJepaPreTrainedModel,c.Idefics3ForConditionalGeneration,c.Idefics3ImageProcessor,c.Idefics3PreTrainedModel,c.Idefics3Processor,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageProcessor,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline;var e_=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.RawImage,c.RepetitionPenaltyLogitsProcessor,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerImageProcessor,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.SummarizationPipeline,c.SuppressTokensAtBeginLogitsProcessor,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.TemperatureLogitsWarper,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var t_=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,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;async function s_(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(De){self.postMessage({status:"error",data:De.toString()})}}class Lp{static async getInstance(A=null){return this.tokenizer??(this.tokenizer=Zm.from_pretrained(this.model_id,{progress_callback:A})),this.model??(this.model=Jm.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",progress_callback:A})),Promise.all([this.tokenizer,this.model])}}ge(Lp,"model_id","ngxson/MiniThinky-v2-1B-Llama-3.2");const Ic=new e_;async function r_(De){const[A,r]=await Lp.getInstance();De=[{role:"system",content:"You are MiniThinky, a helpful AI assistant. You always think before giving the answer. Use <|thinking|> before thinking and <|answer|> before giving the answer."},...De];const f=A.apply_chat_template(De,{add_generation_prompt:!0,return_dict:!0}),[L,j]=A.encode("<|thinking|><|answer|>",{add_special_tokens:!1});let J="thinking",W,w=0,v;const y=ie=>{W??(W=performance.now()),w++>0&&(v=w/(performance.now()-W)*1e3),ie[0]==j&&(J="answering")},M=ie=>{self.postMessage({status:"update",output:ie,tps:v,numTokens:w,state:J})},b=new t_(A,{skip_prompt:!0,skip_special_tokens:!0,callback_function:M,token_callback_function:y});self.postMessage({status:"start"});const{past_key_values:D,sequences:H}=await r.generate({...f,do_sample:!1,repetition_penalty:1.1,max_new_tokens:2048,streamer:b,stopping_criteria:Ic,return_dict_in_generate:!0}),re=A.batch_decode(H,{skip_special_tokens:!0});self.postMessage({status:"complete",output:re})}async function n_(){self.postMessage({status:"loading",data:"Loading model..."});const[De,A]=await Lp.getInstance(f=>{self.postMessage(f)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const r=De("a");await A.generate({...r,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async De=>{const{type:A,data:r}=De.data;switch(A){case"check":s_();break;case"load":n_();break;case"generate":Ic.reset(),r_(r);break;case"interrupt":Ic.interrupt();break;case"reset":Ic.reset();break}})})();