diff --git "a/assets/index-SL8uGygA.js" "b/assets/index-SL8uGygA.js" new file mode 100644--- /dev/null +++ "b/assets/index-SL8uGygA.js" @@ -0,0 +1,2885 @@ +var wg=Object.defineProperty;var bg=(R,c,s)=>c in R?wg(R,c,{enumerable:!0,configurable:!0,writable:!0,value:s}):R[c]=s;var _e=(R,c,s)=>bg(R,typeof c!="symbol"?c+"":c,s);import{d as lh,c as or,o as Zs,a as Js,t as Xc,u as Mg,r as $f,B as vn,m as qi,i as Nh,b as Rf,e as Uh,f as Gc,g as vg,s as Ga,h as Ka,j as xg,k as Tg,l as Pg,n as Eg,p as Cg,q as Sg,v as sh,w as rh,F as ih,x as Hh,y as Vh,z as Wh,A as $g,C as kg,D as xn,E as oh,G as Ig,H as Ys,I as jh,J as ah,K as Nf,L as qh,M as jf,N as Ag,O as kf,_ as Uf,P as If}from"./index-oqfyI0Df.js";const Og={class:"m-1 inline-flex flex-col items-center rounded bg-gray-100 p-2 dark:bg-gray-800"},Fg={class:"text-sm"},Dg={class:"text-xs text-gray-500"},Lg=lh({__name:"TokenBlock",props:{token:null,id:null},setup(R){return(c,s)=>(Zs(),or("div",Og,[Js("span",Fg,Xc(R.token),1),Js("span",Dg,Xc(R.id),1)]))}});var zn={},Vf={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(R,c,s)=>{R.exports=s.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(R,c,s)=>{R.exports=s.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(R,c,s)=>{s.r(c),s.d(c,{Environment:()=>st,Interpreter:()=>ut,Template:()=>mt,parse:()=>be,tokenize:()=>b});var h=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"}),T=Object.freeze({set:h.Set,for:h.For,in:h.In,is:h.Is,if:h.If,else:h.Else,endif:h.EndIf,elif:h.ElseIf,endfor:h.EndFor,and:h.And,or:h.Or,not:h.Not,"not in":h.NotIn,macro:h.Macro,endmacro:h.EndMacro,true:h.BooleanLiteral,false:h.BooleanLiteral,none:h.NullLiteral,True:h.BooleanLiteral,False:h.BooleanLiteral,None:h.NullLiteral}),I=class{constructor(B,ae){this.value=B,this.type=ae}};function U(B){return/\w/.test(B)}function F(B){return/[0-9]/.test(B)}var _=[["{%",h.OpenStatement],["%}",h.CloseStatement],["{{",h.OpenExpression],["}}",h.CloseExpression],["(",h.OpenParen],[")",h.CloseParen],["{",h.OpenCurlyBracket],["}",h.CloseCurlyBracket],["[",h.OpenSquareBracket],["]",h.CloseSquareBracket],[",",h.Comma],[".",h.Dot],[":",h.Colon],["|",h.Pipe],["<=",h.ComparisonBinaryOperator],[">=",h.ComparisonBinaryOperator],["==",h.ComparisonBinaryOperator],["!=",h.ComparisonBinaryOperator],["<",h.ComparisonBinaryOperator],[">",h.ComparisonBinaryOperator],["+",h.AdditiveBinaryOperator],["-",h.AdditiveBinaryOperator],["*",h.MultiplicativeBinaryOperator],["/",h.MultiplicativeBinaryOperator],["%",h.MultiplicativeBinaryOperator],["=",h.Equals]],v=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function w(B,ae={}){return B.endsWith(` +`)&&(B=B.slice(0,-1)),B=B.replace(/{#.*?#}/gs,"{##}"),ae.lstrip_blocks&&(B=B.replace(/^[ \t]*({[#%])/gm,"$1")),ae.trim_blocks&&(B=B.replace(/([#%]})\n/g,"$1")),B.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function b(B,ae={}){var qe,at,ct;const q=[],me=w(B,ae);let $e=0;const Re=vt=>{let St="";for(;vt(me[$e]);){if(me[$e]==="\\"){if(++$e,$e>=me.length)throw new SyntaxError("Unexpected end of input");const kt=me[$e++],is=v.get(kt);if(is===void 0)throw new SyntaxError(`Unexpected escaped character: ${kt}`);St+=is;continue}if(St+=me[$e++],$e>=me.length)throw new SyntaxError("Unexpected end of input")}return St};e:for(;$e0){q.push(new I(kt,h.Text));continue}}Re(kt=>/\s/.test(kt));const St=me[$e];if(St==="-"||St==="+"){const kt=(at=q.at(-1))==null?void 0:at.type;if(kt===h.Text||kt===void 0)throw new SyntaxError(`Unexpected character: ${St}`);switch(kt){case h.Identifier:case h.NumericLiteral:case h.BooleanLiteral:case h.NullLiteral:case h.StringLiteral:case h.CloseParen:case h.CloseSquareBracket:break;default:{++$e;const is=Re(F);q.push(new I(`${St}${is}`,is.length>0?h.NumericLiteral:h.UnaryOperator));continue}}}for(const[kt,is]of _)if(me.slice($e,$e+kt.length)===kt){q.push(new I(kt,is)),$e+=kt.length;continue e}if(St==="'"||St==='"'){++$e;const kt=Re(is=>is!==St);q.push(new I(kt,h.StringLiteral)),++$e;continue}if(F(St)){const kt=Re(F);q.push(new I(kt,h.NumericLiteral));continue}if(U(St)){const kt=Re(U),is=Object.hasOwn(T,kt)?T[kt]:h.Identifier;is===h.In&&((ct=q.at(-1))==null?void 0:ct.type)===h.Not?(q.pop(),q.push(new I("not in",h.NotIn))):q.push(new I(kt,is));continue}throw new SyntaxError(`Unexpected character: ${St}`)}return q}var x=class{constructor(){_e(this,"type","Statement")}},O=class extends x{constructor(ae){super();_e(this,"type","Program");this.body=ae}},H=class extends x{constructor(ae,q,me){super();_e(this,"type","If");this.test=ae,this.body=q,this.alternate=me}},re=class extends x{constructor(ae,q,me,$e){super();_e(this,"type","For");this.loopvar=ae,this.iterable=q,this.body=me,this.defaultBlock=$e}},ne=class extends x{constructor(ae,q){super();_e(this,"type","Set");this.assignee=ae,this.value=q}},G=class extends x{constructor(ae,q,me){super();_e(this,"type","Macro");this.name=ae,this.args=q,this.body=me}},W=class extends x{constructor(){super(...arguments);_e(this,"type","Expression")}},X=class extends W{constructor(ae,q,me){super();_e(this,"type","MemberExpression");this.object=ae,this.property=q,this.computed=me}},D=class extends W{constructor(ae,q){super();_e(this,"type","CallExpression");this.callee=ae,this.args=q}},A=class extends W{constructor(ae){super();_e(this,"type","Identifier");this.value=ae}},M=class extends W{constructor(ae){super();_e(this,"type","Literal");this.value=ae}},P=class extends M{constructor(){super(...arguments);_e(this,"type","NumericLiteral")}},L=class extends M{constructor(){super(...arguments);_e(this,"type","StringLiteral")}},le=class extends M{constructor(){super(...arguments);_e(this,"type","BooleanLiteral")}},oe=class extends M{constructor(){super(...arguments);_e(this,"type","NullLiteral")}},Te=class extends M{constructor(){super(...arguments);_e(this,"type","ArrayLiteral")}},we=class extends M{constructor(){super(...arguments);_e(this,"type","TupleLiteral")}},ie=class extends M{constructor(){super(...arguments);_e(this,"type","ObjectLiteral")}},Pe=class extends W{constructor(ae,q,me){super();_e(this,"type","BinaryExpression");this.operator=ae,this.left=q,this.right=me}},pe=class extends W{constructor(ae,q){super();_e(this,"type","FilterExpression");this.operand=ae,this.filter=q}},ke=class extends W{constructor(ae,q){super();_e(this,"type","SelectExpression");this.iterable=ae,this.test=q}},Oe=class extends W{constructor(ae,q,me){super();_e(this,"type","TestExpression");this.operand=ae,this.negate=q,this.test=me}},Ce=class extends W{constructor(ae,q){super();_e(this,"type","UnaryExpression");this.operator=ae,this.argument=q}},tt=class extends W{constructor(ae=void 0,q=void 0,me=void 0){super();_e(this,"type","SliceExpression");this.start=ae,this.stop=q,this.step=me}},Ge=class extends W{constructor(ae,q){super();_e(this,"type","KeywordArgumentExpression");this.key=ae,this.value=q}};function be(B){const ae=new O([]);let q=0;function me(it,xt){const Ft=B[q++];if(!Ft||Ft.type!==it)throw new Error(`Parser Error: ${xt}. ${Ft.type} !== ${it}.`);return Ft}function $e(){switch(B[q].type){case h.Text:return at();case h.OpenStatement:return ct();case h.OpenExpression:return vt();default:throw new SyntaxError(`Unexpected token type: ${B[q].type}`)}}function Re(...it){return q+it.length<=B.length&&it.some((xt,Ft)=>xt!==B[q+Ft].type)}function qe(...it){return q+it.length<=B.length&&it.every((xt,Ft)=>xt===B[q+Ft].type)}function at(){return new L(me(h.Text,"Expected text token").value)}function ct(){me(h.OpenStatement,"Expected opening statement token");let it;switch(B[q].type){case h.Set:++q,it=St(),me(h.CloseStatement,"Expected closing statement token");break;case h.If:++q,it=kt(),me(h.OpenStatement,"Expected {% token"),me(h.EndIf,"Expected endif token"),me(h.CloseStatement,"Expected %} token");break;case h.Macro:++q,it=is(),me(h.OpenStatement,"Expected {% token"),me(h.EndMacro,"Expected endmacro token"),me(h.CloseStatement,"Expected %} token");break;case h.For:++q,it=$s(),me(h.OpenStatement,"Expected {% token"),me(h.EndFor,"Expected endfor token"),me(h.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${B[q].type}`)}return it}function vt(){me(h.OpenExpression,"Expected opening expression token");const it=zs();return me(h.CloseExpression,"Expected closing expression token"),it}function St(){const it=zs();if(qe(h.Equals)){++q;const xt=St();return new ne(it,xt)}return it}function kt(){var Ws,Kr,Lr,vs,pr,Fs,Sr,ss;const it=zs();me(h.CloseStatement,"Expected closing statement token");const xt=[],Ft=[];for(;!(((Ws=B[q])==null?void 0:Ws.type)===h.OpenStatement&&(((Kr=B[q+1])==null?void 0:Kr.type)===h.ElseIf||((Lr=B[q+1])==null?void 0:Lr.type)===h.Else||((vs=B[q+1])==null?void 0:vs.type)===h.EndIf));)xt.push($e());if(((pr=B[q])==null?void 0:pr.type)===h.OpenStatement&&((Fs=B[q+1])==null?void 0:Fs.type)!==h.EndIf)if(++q,qe(h.ElseIf))me(h.ElseIf,"Expected elseif token"),Ft.push(kt());else for(me(h.Else,"Expected else token"),me(h.CloseStatement,"Expected closing statement token");!(((Sr=B[q])==null?void 0:Sr.type)===h.OpenStatement&&((ss=B[q+1])==null?void 0:ss.type)===h.EndIf);)Ft.push($e());return new H(it,xt,Ft)}function is(){const it=cr();if(it.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const xt=Fr();me(h.CloseStatement,"Expected closing statement token");const Ft=[];for(;Re(h.OpenStatement,h.EndMacro);)Ft.push($e());return new G(it,xt,Ft)}function Ms(it=!1){const xt=it?cr:zs,Ft=[xt()],Ws=qe(h.Comma);for(;Ws&&(++q,Ft.push(xt()),!!qe(h.Comma)););return Ws?new we(Ft):Ft[0]}function $s(){const it=Ms(!0);if(!(it instanceof A||it instanceof we))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${it.type} instead`);me(h.In,"Expected `in` keyword following loop variable");const xt=zs();me(h.CloseStatement,"Expected closing statement token");const Ft=[];for(;Re(h.OpenStatement,h.EndFor)&&Re(h.OpenStatement,h.Else);)Ft.push($e());const Ws=[];if(qe(h.OpenStatement,h.Else))for(++q,++q,me(h.CloseStatement,"Expected closing statement token");Re(h.OpenStatement,h.EndFor);)Ws.push($e());return new re(it,xt,Ft,Ws)}function zs(){return ar()}function ar(){const it=Ar();if(qe(h.If)){++q;const xt=Ar();if(qe(h.Else)){++q;const Ft=Ar();return new H(xt,[it],[Ft])}else return new ke(it,xt)}return it}function Ar(){let it=sn();for(;qe(h.Or);){const xt=B[q];++q;const Ft=sn();it=new Pe(xt,it,Ft)}return it}function sn(){let it=Vs();for(;qe(h.And);){const xt=B[q];++q;const Ft=Vs();it=new Pe(xt,it,Ft)}return it}function Vs(){let it;for(;qe(h.Not);){const xt=B[q];++q;const Ft=Vs();it=new Ce(xt,Ft)}return it??Cr()}function Cr(){let it=Nt();for(;qe(h.ComparisonBinaryOperator)||qe(h.In)||qe(h.NotIn);){const xt=B[q];++q;const Ft=Nt();it=new Pe(xt,it,Ft)}return it}function Nt(){let it=Dr();for(;qe(h.AdditiveBinaryOperator);){const xt=B[q];++q;const Ft=Dr();it=new Pe(xt,it,Ft)}return it}function rn(){const it=Vr(cr());return qe(h.OpenParen)?Or(it):it}function Or(it){let xt=new D(it,Fr());return xt=Vr(xt),qe(h.OpenParen)&&(xt=Or(xt)),xt}function Fr(){me(h.OpenParen,"Expected opening parenthesis for arguments list");const it=nn();return me(h.CloseParen,"Expected closing parenthesis for arguments list"),it}function nn(){const it=[];for(;!qe(h.CloseParen);){let xt=zs();if(qe(h.Equals)){if(++q,!(xt instanceof A))throw new SyntaxError("Expected identifier for keyword argument");const Ft=zs();xt=new Ge(xt,Ft)}it.push(xt),qe(h.Comma)&&++q}return it}function fr(){const it=[];let xt=!1;for(;!qe(h.CloseSquareBracket);)qe(h.Colon)?(it.push(void 0),++q,xt=!0):(it.push(zs()),qe(h.Colon)&&(++q,xt=!0));if(it.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(xt){if(it.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new tt(...it)}return it[0]}function Vr(it){for(;qe(h.Dot)||qe(h.OpenSquareBracket);){const xt=B[q];++q;let Ft;const Ws=xt.type!==h.Dot;if(Ws)Ft=fr(),me(h.CloseSquareBracket,"Expected closing square bracket");else if(Ft=cr(),Ft.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");it=new X(it,Ft,Ws)}return it}function Dr(){let it=Wr();for(;qe(h.MultiplicativeBinaryOperator);){const xt=B[q];++q;const Ft=Wr();it=new Pe(xt,it,Ft)}return it}function Wr(){let it=Gr();for(;qe(h.Is);){++q;const xt=qe(h.Not);xt&&++q;let Ft=cr();if(Ft instanceof le?Ft=new A(Ft.value.toString()):Ft instanceof oe&&(Ft=new A("none")),!(Ft instanceof A))throw new SyntaxError("Expected identifier for the test");it=new Oe(it,xt,Ft)}return it}function Gr(){let it=rn();for(;qe(h.Pipe);){++q;let xt=cr();if(!(xt instanceof A))throw new SyntaxError("Expected identifier for the filter");qe(h.OpenParen)&&(xt=Or(xt)),it=new pe(it,xt)}return it}function cr(){const it=B[q];switch(it.type){case h.NumericLiteral:return++q,new P(Number(it.value));case h.StringLiteral:return++q,new L(it.value);case h.BooleanLiteral:return++q,new le(it.value.toLowerCase()==="true");case h.NullLiteral:return++q,new oe(null);case h.Identifier:return++q,new A(it.value);case h.OpenParen:{++q;const xt=Ms();if(B[q].type!==h.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${B[q].type} instead`);return++q,xt}case h.OpenSquareBracket:{++q;const xt=[];for(;!qe(h.CloseSquareBracket);)xt.push(zs()),qe(h.Comma)&&++q;return++q,new Te(xt)}case h.OpenCurlyBracket:{++q;const xt=new Map;for(;!qe(h.CloseCurlyBracket);){const Ft=zs();me(h.Colon,"Expected colon between key and value in object literal");const Ws=zs();xt.set(Ft,Ws),qe(h.Comma)&&++q}return++q,new ie(xt)}default:throw new SyntaxError(`Unexpected token: ${it.type}`)}}for(;q=0?(ae=(ae??(ae=0))<0?Math.max(B.length+ae,0):Math.min(ae,B.length),q=(q??(q=B.length))<0?Math.max(B.length+q,0):Math.min(q,B.length)):(ae=(ae??(ae=B.length-1))<0?Math.max(B.length+ae,-1):Math.min(ae,B.length-1),q=(q??(q=-1))<-1?Math.max(B.length+q,-1):Math.min(q,B.length-1));const Re=[];for(let qe=ae;$e*qe<$e*q;qe+=me)Re.push(B[qe]);return Re}function Se(B){return B.replace(/\b\w/g,ae=>ae.toUpperCase())}var Be=class{constructor(B=void 0){_e(this,"type","RuntimeValue");_e(this,"value");_e(this,"builtins",new Map);this.value=B}__bool__(){return new Ke(!!this.value)}},Je=class extends Be{constructor(){super(...arguments);_e(this,"type","NumericValue")}},se=class extends Be{constructor(){super(...arguments);_e(this,"type","StringValue");_e(this,"builtins",new Map([["upper",new We(()=>new se(this.value.toUpperCase()))],["lower",new We(()=>new se(this.value.toLowerCase()))],["strip",new We(()=>new se(this.value.trim()))],["title",new We(()=>new se(Se(this.value)))],["length",new Je(this.value.length)],["rstrip",new We(()=>new se(this.value.trimEnd()))],["lstrip",new We(()=>new se(this.value.trimStart()))],["split",new We(ae=>{const q=ae[0]??new Ne;if(!(q instanceof se||q instanceof Ne))throw new Error("sep argument must be a string or null");const me=ae[1]??new Je(-1);if(!(me instanceof Je))throw new Error("maxsplit argument must be a number");let $e=[];if(q instanceof Ne){const Re=this.value.trimStart();for(const{0:qe,index:at}of Re.matchAll(/\S+/g)){if(me.value!==-1&&$e.length>=me.value&&at!==void 0){$e.push(qe+Re.slice(at+qe.length));break}$e.push(qe)}}else{if(q.value==="")throw new Error("empty separator");$e=this.value.split(q.value),me.value!==-1&&$e.length>me.value&&$e.push($e.splice(me.value).join(q.value))}return new ve($e.map(Re=>new se(Re)))})]]))}},Ke=class extends Be{constructor(){super(...arguments);_e(this,"type","BooleanValue")}},Ue=class extends Be{constructor(){super(...arguments);_e(this,"type","ObjectValue");_e(this,"builtins",new Map([["get",new We(([ae,q])=>{if(!(ae instanceof se))throw new Error(`Object key must be a string: got ${ae.type}`);return this.value.get(ae.value)??q??new Ne})],["items",new We(()=>new ve(Array.from(this.value.entries()).map(([ae,q])=>new ve([new se(ae),q]))))]]))}__bool__(){return new Ke(this.value.size>0)}},ue=class extends Ue{constructor(){super(...arguments);_e(this,"type","KeywordArgumentsValue")}},ve=class extends Be{constructor(){super(...arguments);_e(this,"type","ArrayValue");_e(this,"builtins",new Map([["length",new Je(this.value.length)]]))}__bool__(){return new Ke(this.value.length>0)}},Ve=class extends ve{constructor(){super(...arguments);_e(this,"type","TupleValue")}},We=class extends Be{constructor(){super(...arguments);_e(this,"type","FunctionValue")}},Ne=class extends Be{constructor(){super(...arguments);_e(this,"type","NullValue")}},je=class extends Be{constructor(){super(...arguments);_e(this,"type","UndefinedValue")}},st=class{constructor(B){_e(this,"variables",new Map([["namespace",new We(B=>{if(B.length===0)return new Ue(new Map);if(B.length!==1||!(B[0]instanceof Ue))throw new Error("`namespace` expects either zero arguments or a single object argument");return B[0]})]]));_e(this,"tests",new Map([["boolean",B=>B.type==="BooleanValue"],["callable",B=>B instanceof We],["odd",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${B.type}`);return B.value%2!==0}],["even",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${B.type}`);return B.value%2===0}],["false",B=>B.type==="BooleanValue"&&!B.value],["true",B=>B.type==="BooleanValue"&&B.value],["none",B=>B.type==="NullValue"],["string",B=>B.type==="StringValue"],["number",B=>B.type==="NumericValue"],["integer",B=>B.type==="NumericValue"&&Number.isInteger(B.value)],["iterable",B=>B.type==="ArrayValue"||B.type==="StringValue"],["mapping",B=>B.type==="ObjectValue"],["lower",B=>{const ae=B.value;return B.type==="StringValue"&&ae===ae.toLowerCase()}],["upper",B=>{const ae=B.value;return B.type==="StringValue"&&ae===ae.toUpperCase()}],["none",B=>B.type==="NullValue"],["defined",B=>B.type!=="UndefinedValue"],["undefined",B=>B.type==="UndefinedValue"],["equalto",(B,ae)=>B.value===ae.value],["eq",(B,ae)=>B.value===ae.value]]));this.parent=B}set(B,ae){return this.declareVariable(B,pt(ae))}declareVariable(B,ae){if(this.variables.has(B))throw new SyntaxError(`Variable already declared: ${B}`);return this.variables.set(B,ae),ae}setVariable(B,ae){return this.variables.set(B,ae),ae}resolve(B){if(this.variables.has(B))return this;if(this.parent)return this.parent.resolve(B);throw new Error(`Unknown variable: ${B}`)}lookupVariable(B){try{return this.resolve(B).variables.get(B)??new je}catch{return new je}}},ut=class{constructor(B){_e(this,"global");this.global=B??new st}run(B){return this.evaluate(B,this.global)}evaluateBinaryExpression(B,ae){const q=this.evaluate(B.left,ae);switch(B.operator.value){case"and":return q.__bool__().value?this.evaluate(B.right,ae):q;case"or":return q.__bool__().value?q:this.evaluate(B.right,ae)}const me=this.evaluate(B.right,ae);switch(B.operator.value){case"==":return new Ke(q.value==me.value);case"!=":return new Ke(q.value!=me.value)}if(q instanceof je||me instanceof je)throw new Error("Cannot perform operation on undefined values");if(q instanceof Ne||me instanceof Ne)throw new Error("Cannot perform operation on null values");if(q instanceof Je&&me instanceof Je)switch(B.operator.value){case"+":return new Je(q.value+me.value);case"-":return new Je(q.value-me.value);case"*":return new Je(q.value*me.value);case"/":return new Je(q.value/me.value);case"%":return new Je(q.value%me.value);case"<":return new Ke(q.value":return new Ke(q.value>me.value);case">=":return new Ke(q.value>=me.value);case"<=":return new Ke(q.value<=me.value)}else if(q instanceof ve&&me instanceof ve)switch(B.operator.value){case"+":return new ve(q.value.concat(me.value))}else if(me instanceof ve){const $e=me.value.find(Re=>Re.value===q.value)!==void 0;switch(B.operator.value){case"in":return new Ke($e);case"not in":return new Ke(!$e)}}if(q instanceof se||me instanceof se)switch(B.operator.value){case"+":return new se(q.value.toString()+me.value.toString())}if(q instanceof se&&me instanceof se)switch(B.operator.value){case"in":return new Ke(me.value.includes(q.value));case"not in":return new Ke(!me.value.includes(q.value))}if(q instanceof se&&me instanceof Ue)switch(B.operator.value){case"in":return new Ke(me.value.has(q.value));case"not in":return new Ke(!me.value.has(q.value))}throw new SyntaxError(`Unknown operator "${B.operator.value}" between ${q.type} and ${me.type}`)}evaluateArguments(B,ae){const q=[],me=new Map;for(const $e of B)if($e.type==="KeywordArgumentExpression"){const Re=$e;me.set(Re.key.value,this.evaluate(Re.value,ae))}else{if(me.size>0)throw new Error("Positional arguments must come before keyword arguments");q.push(this.evaluate($e,ae))}return[q,me]}evaluateFilterExpression(B,ae){const q=this.evaluate(B.operand,ae);if(B.filter.type==="Identifier"){const me=B.filter;if(me.value==="tojson")return new se(lt(q));if(q instanceof ve)switch(me.value){case"list":return q;case"first":return q.value[0];case"last":return q.value[q.value.length-1];case"length":return new Je(q.value.length);case"reverse":return new ve(q.value.reverse());case"sort":return new ve(q.value.sort(($e,Re)=>{if($e.type!==Re.type)throw new Error(`Cannot compare different types: ${$e.type} and ${Re.type}`);switch($e.type){case"NumericValue":return $e.value-Re.value;case"StringValue":return $e.value.localeCompare(Re.value);default:throw new Error(`Cannot compare type: ${$e.type}`)}}));case"join":return new se(q.value.map($e=>$e.value).join(""));default:throw new Error(`Unknown ArrayValue filter: ${me.value}`)}else if(q instanceof se)switch(me.value){case"length":return new Je(q.value.length);case"upper":return new se(q.value.toUpperCase());case"lower":return new se(q.value.toLowerCase());case"title":return new se(Se(q.value));case"capitalize":return new se(q.value.charAt(0).toUpperCase()+q.value.slice(1));case"trim":return new se(q.value.trim());case"indent":return new se(q.value.split(` +`).map(($e,Re)=>Re===0||$e.length===0?$e:" "+$e).join(` +`));case"join":case"string":return q;default:throw new Error(`Unknown StringValue filter: ${me.value}`)}else if(q instanceof Je)switch(me.value){case"abs":return new Je(Math.abs(q.value));default:throw new Error(`Unknown NumericValue filter: ${me.value}`)}else if(q instanceof Ue)switch(me.value){case"items":return new ve(Array.from(q.value.entries()).map(([$e,Re])=>new ve([new se($e),Re])));case"length":return new Je(q.value.size);default:throw new Error(`Unknown ObjectValue filter: ${me.value}`)}throw new Error(`Cannot apply filter "${me.value}" to type: ${q.type}`)}else if(B.filter.type==="CallExpression"){const me=B.filter;if(me.callee.type!=="Identifier")throw new Error(`Unknown filter: ${me.callee.type}`);const $e=me.callee.value;if($e==="tojson"){const[,Re]=this.evaluateArguments(me.args,ae),qe=Re.get("indent")??new Ne;if(!(qe instanceof Je||qe instanceof Ne))throw new Error("If set, indent must be a number");return new se(lt(q,qe.value))}else if($e==="join"){let Re;if(q instanceof se)Re=Array.from(q.value);else if(q instanceof ve)Re=q.value.map(vt=>vt.value);else throw new Error(`Cannot apply filter "${$e}" to type: ${q.type}`);const[qe,at]=this.evaluateArguments(me.args,ae),ct=qe.at(0)??at.get("separator")??new se("");if(!(ct instanceof se))throw new Error("separator must be a string");return new se(Re.join(ct.value))}if(q instanceof ve){switch($e){case"selectattr":case"rejectattr":{const Re=$e==="selectattr";if(q.value.some(kt=>!(kt instanceof Ue)))throw new Error(`\`${$e}\` can only be applied to array of objects`);if(me.args.some(kt=>kt.type!=="StringLiteral"))throw new Error(`arguments of \`${$e}\` must be strings`);const[qe,at,ct]=me.args.map(kt=>this.evaluate(kt,ae));let vt;if(at){const kt=ae.tests.get(at.value);if(!kt)throw new Error(`Unknown test: ${at.value}`);vt=kt}else vt=(...kt)=>kt[0].__bool__().value;const St=q.value.filter(kt=>{const is=kt.value.get(qe.value),Ms=is?vt(is,ct):!1;return Re?Ms:!Ms});return new ve(St)}case"map":{const[,Re]=this.evaluateArguments(me.args,ae);if(Re.has("attribute")){const qe=Re.get("attribute");if(!(qe instanceof se))throw new Error("attribute must be a string");const at=Re.get("default"),ct=q.value.map(vt=>{if(!(vt instanceof Ue))throw new Error("items in map must be an object");return vt.value.get(qe.value)??at??new je});return new ve(ct)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${$e}`)}else if(q instanceof se){switch($e){case"indent":{const[Re,qe]=this.evaluateArguments(me.args,ae),at=Re.at(0)??qe.get("width")??new Je(4);if(!(at instanceof Je))throw new Error("width must be a number");const ct=Re.at(1)??qe.get("first")??new Ke(!1),vt=Re.at(2)??qe.get("blank")??new Ke(!1),St=q.value.split(` +`),kt=" ".repeat(at.value),is=St.map((Ms,$s)=>!ct.value&&$s===0||!vt.value&&Ms.length===0?Ms:kt+Ms);return new se(is.join(` +`))}}throw new Error(`Unknown StringValue filter: ${$e}`)}else throw new Error(`Cannot apply filter "${$e}" to type: ${q.type}`)}throw new Error(`Unknown filter: ${B.filter.type}`)}evaluateTestExpression(B,ae){const q=this.evaluate(B.operand,ae),me=ae.tests.get(B.test.value);if(!me)throw new Error(`Unknown test: ${B.test.value}`);const $e=me(q);return new Ke(B.negate?!$e:$e)}evaluateUnaryExpression(B,ae){const q=this.evaluate(B.argument,ae);switch(B.operator.value){case"not":return new Ke(!q.value);default:throw new SyntaxError(`Unknown operator: ${B.operator.value}`)}}evalProgram(B,ae){return this.evaluateBlock(B.body,ae)}evaluateBlock(B,ae){let q="";for(const me of B){const $e=this.evaluate(me,ae);$e.type!=="NullValue"&&$e.type!=="UndefinedValue"&&(q+=$e.value)}return new se(q)}evaluateIdentifier(B,ae){return ae.lookupVariable(B.value)}evaluateCallExpression(B,ae){const[q,me]=this.evaluateArguments(B.args,ae);me.size>0&&q.push(new ue(me));const $e=this.evaluate(B.callee,ae);if($e.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${$e.type}`);return $e.value(q,ae)}evaluateSliceExpression(B,ae,q){if(!(B instanceof ve||B instanceof se))throw new Error("Slice object must be an array or string");const me=this.evaluate(ae.start,q),$e=this.evaluate(ae.stop,q),Re=this.evaluate(ae.step,q);if(!(me instanceof Je||me instanceof je))throw new Error("Slice start must be numeric or undefined");if(!($e instanceof Je||$e instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(Re instanceof Je||Re instanceof je))throw new Error("Slice step must be numeric or undefined");return B instanceof ve?new ve(ce(B.value,me.value,$e.value,Re.value)):new se(ce(Array.from(B.value),me.value,$e.value,Re.value).join(""))}evaluateMemberExpression(B,ae){const q=this.evaluate(B.object,ae);let me;if(B.computed){if(B.property.type==="SliceExpression")return this.evaluateSliceExpression(q,B.property,ae);me=this.evaluate(B.property,ae)}else me=new se(B.property.value);let $e;if(q instanceof Ue){if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);$e=q.value.get(me.value)??q.builtins.get(me.value)}else if(q instanceof ve||q instanceof se)if(me instanceof Je)$e=q.value.at(me.value),q instanceof se&&($e=new se(q.value.at(me.value)));else if(me instanceof se)$e=q.builtins.get(me.value);else throw new Error(`Cannot access property with non-string/non-number: got ${me.type}`);else{if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);$e=q.builtins.get(me.value)}return $e instanceof Be?$e:new je}evaluateSet(B,ae){const q=this.evaluate(B.value,ae);if(B.assignee.type==="Identifier"){const me=B.assignee.value;ae.setVariable(me,q)}else if(B.assignee.type==="MemberExpression"){const me=B.assignee,$e=this.evaluate(me.object,ae);if(!($e instanceof Ue))throw new Error("Cannot assign to member of non-object");if(me.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");$e.value.set(me.property.value,q)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(B.assignee)}`);return new Ne}evaluateIf(B,ae){const q=this.evaluate(B.test,ae);return this.evaluateBlock(q.__bool__().value?B.body:B.alternate,ae)}evaluateFor(B,ae){const q=new st(ae);let me,$e;if(B.iterable.type==="SelectExpression"){const vt=B.iterable;$e=this.evaluate(vt.iterable,q),me=vt.test}else $e=this.evaluate(B.iterable,q);if(!($e instanceof ve))throw new Error(`Expected iterable type in for loop: got ${$e.type}`);const Re=[],qe=[];for(let vt=0;vt<$e.value.length;++vt){const St=new st(q),kt=$e.value[vt];let is;if(B.loopvar.type==="Identifier")is=Ms=>Ms.setVariable(B.loopvar.value,kt);else if(B.loopvar.type==="TupleLiteral"){const Ms=B.loopvar;if(kt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${kt.type}`);const $s=kt;if(Ms.value.length!==$s.value.length)throw new Error(`Too ${Ms.value.length>$s.value.length?"few":"many"} items to unpack`);is=zs=>{for(let ar=0;ar0?Re[vt-1]:new je],["nextitem",vt{var qe;const $e=new st(me);q=q.slice();let Re;((qe=q.at(-1))==null?void 0:qe.type)==="KeywordArgumentsValue"&&(Re=q.pop());for(let at=0;atthis.evaluate(q,ae)));case"TupleLiteral":return new Ve(B.value.map(q=>this.evaluate(q,ae)));case"ObjectLiteral":{const q=new Map;for(const[me,$e]of B.value){const Re=this.evaluate(me,ae);if(!(Re instanceof se))throw new Error(`Object keys must be strings: got ${Re.type}`);q.set(Re.value,this.evaluate($e,ae))}return new Ue(q)}case"Identifier":return this.evaluateIdentifier(B,ae);case"CallExpression":return this.evaluateCallExpression(B,ae);case"MemberExpression":return this.evaluateMemberExpression(B,ae);case"UnaryExpression":return this.evaluateUnaryExpression(B,ae);case"BinaryExpression":return this.evaluateBinaryExpression(B,ae);case"FilterExpression":return this.evaluateFilterExpression(B,ae);case"TestExpression":return this.evaluateTestExpression(B,ae);default:throw new SyntaxError(`Unknown node type: ${B.type}`)}}};function pt(B){switch(typeof B){case"number":return new Je(B);case"string":return new se(B);case"boolean":return new Ke(B);case"undefined":return new je;case"object":return B===null?new Ne:Array.isArray(B)?new ve(B.map(pt)):new Ue(new Map(Object.entries(B).map(([ae,q])=>[ae,pt(q)])));case"function":return new We((ae,q)=>{const me=B(...ae.map($e=>$e.value))??null;return pt(me)});default:throw new Error(`Cannot convert to runtime value: ${B}`)}}function lt(B,ae,q){const me=q??0;switch(B.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(B.value);case"ArrayValue":case"ObjectValue":{const $e=ae?" ".repeat(ae):"",Re=` +`+$e.repeat(me),qe=Re+$e;if(B.type==="ArrayValue"){const at=B.value.map(ct=>lt(ct,ae,me+1));return ae?`[${qe}${at.join(`,${qe}`)}${Re}]`:`[${at.join(", ")}]`}else{const at=Array.from(B.value.entries()).map(([ct,vt])=>{const St=`"${ct}": ${lt(vt,ae,me+1)}`;return ae?`${qe}${St}`:St});return ae?`{${at.join(",")}${Re}}`:`{${at.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${B.type}`)}}var mt=class{constructor(B){_e(this,"parsed");const ae=b(B,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=be(ae)}render(B){const ae=new st;if(ae.set("false",!1),ae.set("true",!0),ae.set("raise_exception",$e=>{throw new Error($e)}),ae.set("range",Z),B)for(const[$e,Re]of Object.entries(B))ae.set($e,Re);return new ut(ae).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(R,c,s)=>{s.r(c),s.d(c,{registerBackend:()=>I,resolveBackendAndExecutionProviders:()=>F});const h=new Map,T=[],I=(_,v,w)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const b=h.get(_);if(b===void 0)h.set(_,{backend:v,priority:w});else{if(b.priority>w)return;if(b.priority===w&&b.backend!==v)throw new Error(`cannot register backend "${_}" using priority ${w}`)}if(w>=0){const x=T.indexOf(_);x!==-1&&T.splice(x,1);for(let O=0;O{const v=h.get(_);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const w=!!v.initPromise;try{return w||(v.initPromise=v.backend.init(_)),await v.initPromise,v.initialized=!0,v.backend}catch(b){return w||(v.error=`${b}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},F=async _=>{const v=_.executionProviders||[],w=v.map(ne=>typeof ne=="string"?ne:ne.name),b=w.length===0?T:w;let x;const O=[],H=new Set;for(const ne of b){const G=await U(ne);typeof G=="string"?O.push({name:ne,err:G}):(x||(x=G),x===G&&H.add(ne))}if(!x)throw new Error(`no available backend found. ERR: ${O.map(ne=>`[${ne.name}] ${ne.err}`).join(", ")}`);for(const{name:ne,err:G}of O)w.includes(ne)&&console.warn(`removing requested execution provider "${ne}" from session options because it is not available: ${G}`);const re=v.filter(ne=>H.has(typeof ne=="string"?ne:ne.name));return[x,new Proxy(_,{get:(ne,G)=>G==="executionProviders"?re:Reflect.get(ne,G)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(R,c,s)=>{s.r(c),s.d(c,{registerBackend:()=>h.registerBackend});var h=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(R,c,s)=>{s.r(c),s.d(c,{env:()=>I});var h=s("./node_modules/onnxruntime-common/dist/esm/version.js");let T="warning";const I={wasm:{},webgl:{},webgpu:{},versions:{common:h.version},set logLevel(U){if(U!==void 0){if(typeof U!="string"||["verbose","info","warning","error","fatal"].indexOf(U)===-1)throw new Error(`Unsupported logging level: ${U}`);T=U}},get logLevel(){return T}};Object.defineProperty(I,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(R,c,s)=>{s.r(c),s.d(c,{env:()=>T});var h=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const T=h.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(R,c,s)=>{s.r(c),s.d(c,{InferenceSession:()=>I.InferenceSession,TRACE:()=>F.TRACE,TRACE_FUNC_BEGIN:()=>F.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>F.TRACE_FUNC_END,Tensor:()=>U.Tensor,TrainingSession:()=>_.TrainingSession,env:()=>T.env,registerBackend:()=>h.registerBackend});var h=s("./node_modules/onnxruntime-common/dist/esm/backend.js"),T=s("./node_modules/onnxruntime-common/dist/esm/env.js"),I=s("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),U=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),s("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var F=s("./node_modules/onnxruntime-common/dist/esm/trace.js");s("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),s("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var _=s("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(R,c,s)=>{s.r(c),s.d(c,{InferenceSession:()=>U});var h=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),T=s("./node_modules/onnxruntime-common/dist/esm/tensor.js"),I=s("./node_modules/onnxruntime-common/dist/esm/trace.js");class U{constructor(_){this.handler=_}async run(_,v,w){(0,I.TRACE_FUNC_BEGIN)();const b={};let x={};if(typeof _!="object"||_===null||_ instanceof T.Tensor||Array.isArray(_))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let O=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof T.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.");O=!1;for(const ne of v){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);b[ne]=null}if(typeof w=="object"&&w!==null)x=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const G=Object.getOwnPropertyNames(v);for(const W of this.outputNames)if(G.indexOf(W)!==-1){const X=v[W];(X===null||X instanceof T.Tensor)&&(ne=!0,O=!1,b[W]=X)}if(ne){if(typeof w=="object"&&w!==null)x=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else x=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of this.inputNames)if(typeof _[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(O)for(const ne of this.outputNames)b[ne]=null;const H=await this.handler.run(_,b,x),re={};for(const ne in H)if(Object.hasOwnProperty.call(H,ne)){const G=H[ne];G instanceof T.Tensor?re[ne]=G:re[ne]=new T.Tensor(G.type,G.data,G.dims)}return(0,I.TRACE_FUNC_END)(),re}async release(){return this.handler.dispose()}static async create(_,v,w,b){(0,I.TRACE_FUNC_BEGIN)();let x,O={};if(typeof _=="string"){if(x=_,typeof v=="object"&&v!==null)O=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(_ instanceof Uint8Array){if(x=_,typeof v=="object"&&v!==null)O=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(_ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&_ instanceof SharedArrayBuffer){const G=_;let W=0,X=_.byteLength;if(typeof v=="object"&&v!==null)O=v;else if(typeof v=="number"){if(W=v,!Number.isSafeInteger(W))throw new RangeError("'byteOffset' must be an integer.");if(W<0||W>=G.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${G.byteLength}).`);if(X=_.byteLength-W,typeof w=="number"){if(X=w,!Number.isSafeInteger(X))throw new RangeError("'byteLength' must be an integer.");if(X<=0||W+X>G.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${G.byteLength-W}].`);if(typeof b=="object"&&b!==null)O=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(typeof w<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof v<"u")throw new TypeError("'options' must be an object.");x=new Uint8Array(G,W,X)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[H,re]=await(0,h.resolveBackendAndExecutionProviders)(O),ne=await H.createInferenceSessionHandler(x,re);return(0,I.TRACE_FUNC_END)(),new U(ne)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(R,c,s)=>{s.r(c),s.d(c,{InferenceSession:()=>T});var h=s("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const T=h.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(R,c,s)=>{s.r(c)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(R,c,s)=>{s.r(c)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(R,c,s)=>{s.r(c),s.d(c,{tensorToDataURL:()=>h,tensorToImageData:()=>T});const h=(I,U)=>{const F=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);F.width=I.dims[3],F.height=I.dims[2];const _=F.getContext("2d");if(_!=null){let v,w;(U==null?void 0:U.tensorLayout)!==void 0&&U.tensorLayout==="NHWC"?(v=I.dims[2],w=I.dims[3]):(v=I.dims[3],w=I.dims[2]);const b=(U==null?void 0:U.format)!==void 0?U.format:"RGB",x=U==null?void 0:U.norm;let O,H;x===void 0||x.mean===void 0?O=[255,255,255,255]:typeof x.mean=="number"?O=[x.mean,x.mean,x.mean,x.mean]:(O=[x.mean[0],x.mean[1],x.mean[2],0],x.mean[3]!==void 0&&(O[3]=x.mean[3])),x===void 0||x.bias===void 0?H=[0,0,0,0]:typeof x.bias=="number"?H=[x.bias,x.bias,x.bias,x.bias]:(H=[x.bias[0],x.bias[1],x.bias[2],0],x.bias[3]!==void 0&&(H[3]=x.bias[3]));const re=w*v;let ne=0,G=re,W=re*2,X=-1;b==="RGBA"?(ne=0,G=re,W=re*2,X=re*3):b==="RGB"?(ne=0,G=re,W=re*2):b==="RBG"&&(ne=0,W=re,G=re*2);for(let D=0;D{const F=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let _;if(F!=null){let v,w,b;(U==null?void 0:U.tensorLayout)!==void 0&&U.tensorLayout==="NHWC"?(v=I.dims[2],w=I.dims[1],b=I.dims[3]):(v=I.dims[3],w=I.dims[2],b=I.dims[1]);const x=U!==void 0&&U.format!==void 0?U.format:"RGB",O=U==null?void 0:U.norm;let H,re;O===void 0||O.mean===void 0?H=[255,255,255,255]:typeof O.mean=="number"?H=[O.mean,O.mean,O.mean,O.mean]:(H=[O.mean[0],O.mean[1],O.mean[2],255],O.mean[3]!==void 0&&(H[3]=O.mean[3])),O===void 0||O.bias===void 0?re=[0,0,0,0]:typeof O.bias=="number"?re=[O.bias,O.bias,O.bias,O.bias]:(re=[O.bias[0],O.bias[1],O.bias[2],0],O.bias[3]!==void 0&&(re[3]=O.bias[3]));const ne=w*v;if(U!==void 0&&(U.format!==void 0&&b===4&&U.format!=="RGBA"||b===3&&U.format!=="RGB"&&U.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const G=4;let W=0,X=1,D=2,A=3,M=0,P=ne,L=ne*2,le=-1;x==="RGBA"?(M=0,P=ne,L=ne*2,le=ne*3):x==="RGB"?(M=0,P=ne,L=ne*2):x==="RBG"&&(M=0,L=ne,P=ne*2),_=F.createImageData(v,w);for(let oe=0;oe{s.r(c)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(R,c,s)=>{s.r(c),s.d(c,{bufferToTensor:()=>T,tensorFromGpuBuffer:()=>F,tensorFromImage:()=>I,tensorFromMLTensor:()=>_,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>U});var h=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const T=(w,b)=>{if(w===void 0)throw new Error("Image buffer must be defined");if(b.height===void 0||b.width===void 0)throw new Error("Image height and width must be defined");if(b.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:x,width:O}=b,H=b.norm??{mean:255,bias:0};let re,ne;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"?ne=[H.bias,H.bias,H.bias,H.bias]:ne=[H.bias[0],H.bias[1],H.bias[2],H.bias[3]??0];const G=b.format!==void 0?b.format:"RGBA",W=b.tensorFormat!==void 0&&b.tensorFormat!==void 0?b.tensorFormat:"RGB",X=x*O,D=W==="RGBA"?new Float32Array(X*4):new Float32Array(X*3);let A=4,M=0,P=1,L=2,le=3,oe=0,Te=X,we=X*2,ie=-1;G==="RGB"&&(A=3,M=0,P=1,L=2,le=-1),W==="RGBA"?ie=X*3:W==="RBG"?(oe=0,we=X,Te=X*2):W==="BGR"&&(we=0,Te=X,oe=X*2);for(let pe=0;pe{const x=typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement,O=typeof ImageData<"u"&&w instanceof ImageData,H=typeof ImageBitmap<"u"&&w instanceof ImageBitmap,re=typeof w=="string";let ne,G=b??{};const W=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},X=D=>typeof HTMLCanvasElement<"u"&&D instanceof HTMLCanvasElement||D instanceof OffscreenCanvas?D.getContext("2d"):null;if(x){const D=W();D.width=w.width,D.height=w.height;const A=X(D);if(A!=null){let M=w.height,P=w.width;if(b!==void 0&&b.resizedHeight!==void 0&&b.resizedWidth!==void 0&&(M=b.resizedHeight,P=b.resizedWidth),b!==void 0){if(G=b,b.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");G.tensorFormat="RGBA",G.height=M,G.width=P}else G.tensorFormat="RGBA",G.height=M,G.width=P;A.drawImage(w,0,0),ne=A.getImageData(0,0,P,M).data}else throw new Error("Can not access image data")}else if(O){let D,A;if(b!==void 0&&b.resizedWidth!==void 0&&b.resizedHeight!==void 0?(D=b.resizedHeight,A=b.resizedWidth):(D=w.height,A=w.width),b!==void 0&&(G=b),G.format="RGBA",G.height=D,G.width=A,b!==void 0){const M=W();M.width=A,M.height=D;const P=X(M);if(P!=null)P.putImageData(w,0,0),ne=P.getImageData(0,0,A,D).data;else throw new Error("Can not access image data")}else ne=w.data}else if(H){if(b===void 0)throw new Error("Please provide image config with format for Imagebitmap");const D=W();D.width=w.width,D.height=w.height;const A=X(D);if(A!=null){const M=w.height,P=w.width;return A.drawImage(w,0,0,P,M),ne=A.getImageData(0,0,P,M).data,G.height=M,G.width=P,T(ne,G)}else throw new Error("Can not access image data")}else{if(re)return new Promise((D,A)=>{const M=W(),P=X(M);if(!w||!P)return A();const L=new Image;L.crossOrigin="Anonymous",L.src=w,L.onload=()=>{M.width=L.width,M.height=L.height,P.drawImage(L,0,0,M.width,M.height);const le=P.getImageData(0,0,M.width,M.height);G.height=M.height,G.width=M.width,D(T(le.data,G))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ne!==void 0)return T(ne,G);throw new Error("Input data provided is not supported - aborted tensor creation")},U=(w,b)=>{const{width:x,height:O,download:H,dispose:re}=b,ne=[1,O,x,4];return new h.Tensor({location:"texture",type:"float32",texture:w,dims:ne,download:H,dispose:re})},F=(w,b)=>{const{dataType:x,dims:O,download:H,dispose:re}=b;return new h.Tensor({location:"gpu-buffer",type:x??"float32",gpuBuffer:w,dims:O,download:H,dispose:re})},_=(w,b)=>{const{dataType:x,dims:O,download:H,dispose:re}=b;return new h.Tensor({location:"ml-tensor",type:x??"float32",mlTensor:w,dims:O,download:H,dispose:re})},v=(w,b,x)=>new h.Tensor({location:"cpu-pinned",type:w,data:b,dims:x??[b.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(R,c,s)=>{s.r(c)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(R,c,s)=>{s.r(c),s.d(c,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>T,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>h,checkTypedArray:()=>U});const h=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),T=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let I=!1;const U=()=>{if(!I){I=!0;const F=typeof BigInt64Array<"u"&&BigInt64Array.from,_=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;F&&(h.set("int64",BigInt64Array),T.set(BigInt64Array,"int64")),_&&(h.set("uint64",BigUint64Array),T.set(BigUint64Array,"uint64")),v?(h.set("float16",Float16Array),T.set(Float16Array,"float16")):h.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(R,c,s)=>{s.r(c),s.d(c,{Tensor:()=>F});var h=s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),T=s("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),I=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),U=s("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class F{constructor(v,w,b){(0,I.checkTypedArray)();let x,O;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,x=v.type,O=v.dims,v.location){case"cpu-pinned":{const re=I.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(x);if(!re)throw new TypeError(`unsupported type "${x}" 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(x!=="float32")throw new TypeError(`unsupported type "${x}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(x!=="float32"&&x!=="float16"&&x!=="int32"&&x!=="int64"&&x!=="uint32"&&x!=="uint8"&&x!=="bool"&&x!=="uint4"&&x!=="int4")throw new TypeError(`unsupported type "${x}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(x!=="float32"&&x!=="float16"&&x!=="int32"&&x!=="int64"&&x!=="uint32"&&x!=="uint64"&&x!=="int8"&&x!=="uint8"&&x!=="bool")throw new TypeError(`unsupported type "${x}" 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,ne;if(typeof v=="string")if(x=v,ne=b,v==="string"){if(!Array.isArray(w))throw new TypeError("A string tensor's data must be a string array.");re=w}else{const G=I.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(G===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(w)){if(v==="float16"&&G===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${G.name} as data.`);v==="uint64"||v==="int64"?re=G.from(w,BigInt):re=G.from(w)}else if(w instanceof G)re=w;else if(w instanceof Uint8ClampedArray)if(v==="uint8")re=Uint8Array.from(w);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${x} tensor's data must be type of ${G}`)}else if(ne=w,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const G=typeof v[0];if(G==="string")x="string",re=v;else if(G==="boolean")x="bool",re=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${G}.`)}else if(v instanceof Uint8ClampedArray)x="uint8",re=Uint8Array.from(v);else{const G=I.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(G===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);x=G,re=v}if(ne===void 0)ne=[re.length];else if(!Array.isArray(ne))throw new TypeError("A tensor's dims must be a number array");O=ne,this.cpuData=re,this.dataLocation="cpu"}const H=(0,U.calculateSize)(O);if(this.cpuData&&H!==this.cpuData.length&&!((x==="uint4"||x==="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=x,this.dims=O,this.size=H}static async fromImage(v,w){return(0,T.tensorFromImage)(v,w)}static fromTexture(v,w){return(0,T.tensorFromTexture)(v,w)}static fromGpuBuffer(v,w){return(0,T.tensorFromGpuBuffer)(v,w)}static fromMLTensor(v,w){return(0,T.tensorFromMLTensor)(v,w)}static fromPinnedBuffer(v,w,b){return(0,T.tensorFromPinnedBuffer)(v,w,b)}toDataURL(v){return(0,h.tensorToDataURL)(this,v)}toImageData(v){return(0,h.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 w=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=w,v&&this.disposer&&(this.disposer(),this.disposer=void 0),w}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,U.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(R,c,s)=>{s.r(c),s.d(c,{calculateSize:()=>T,tensorReshape:()=>I});var h=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const T=U=>{let F=1;for(let _=0;_{switch(U.location){case"cpu":return new h.Tensor(U.type,U.data,F);case"cpu-pinned":return new h.Tensor({location:"cpu-pinned",data:U.data,type:U.type,dims:F});case"texture":return new h.Tensor({location:"texture",texture:U.texture,type:U.type,dims:F});case"gpu-buffer":return new h.Tensor({location:"gpu-buffer",gpuBuffer:U.gpuBuffer,type:U.type,dims:F});case"ml-tensor":return new h.Tensor({location:"ml-tensor",mlTensor:U.mlTensor,type:U.type,dims:F});default:throw new Error(`tensorReshape: tensor location ${U.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(R,c,s)=>{s.r(c),s.d(c,{Tensor:()=>T});var h=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const T=h.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(R,c,s)=>{s.r(c),s.d(c,{TRACE:()=>T,TRACE_FUNC_BEGIN:()=>U,TRACE_FUNC_END:()=>F});var h=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const T=(_,v)=>{(typeof h.env.trace>"u"?!h.env.wasm.trace:!h.env.trace)||console.timeStamp(`${_}::ORT::${v}`)},I=(_,v)=>{var x;const w=((x=new Error().stack)==null?void 0:x.split(/\r\n|\r|\n/g))||[];let b=!1;for(let O=0;O{(typeof h.env.trace>"u"?!h.env.wasm.trace:!h.env.trace)||I("BEGIN",_)},F=_=>{(typeof h.env.trace>"u"?!h.env.wasm.trace:!h.env.trace)||I("END",_)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(R,c,s)=>{s.r(c),s.d(c,{TrainingSession:()=>U});var h=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),T=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");const I="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class U{constructor(_,v,w){this.handler=_,this.hasOptimizerModel=v,this.hasEvalModel=w}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(_,v){const w=_.evalModel||"",b=_.optimizerModel||"",x=v||{},[O,H]=await(0,h.resolveBackendAndExecutionProviders)(x);if(O.createTrainingSessionHandler){const re=await O.createTrainingSessionHandler(_.checkpointState,_.trainModel,w,b,H);return new U(re,!!_.optimizerModel,!!_.evalModel)}else throw new Error(I)}typeNarrowingForRunStep(_,v,w,b,x){const O={};let H={};if(typeof w!="object"||w===null||w instanceof T.Tensor||Array.isArray(w))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof b=="object"){if(b===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(b instanceof T.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(b)){if(b.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const ne of b){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);O[ne]=null}if(typeof x=="object"&&x!==null)H=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const G=Object.getOwnPropertyNames(b);for(const W of v)if(G.indexOf(W)!==-1){const X=b[W];(X===null||X instanceof T.Tensor)&&(ne=!0,re=!1,O[W]=X)}if(ne){if(typeof x=="object"&&x!==null)H=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else H=b}}else if(typeof b<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of _)if(typeof w[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(re)for(const ne of v)O[ne]=null;return[O,H]}convertHandlerReturnTypeToMapOfTensors(_){const v={};for(const w in _)if(Object.hasOwnProperty.call(_,w)){const b=_[w];b instanceof T.Tensor?v[w]=b:v[w]=new T.Tensor(b.type,b.data,b.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(_,v,w){const[b,x]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,_,v,w),O=await this.handler.runTrainStep(_,b,x);return this.convertHandlerReturnTypeToMapOfTensors(O)}async runOptimizerStep(_){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(_||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(_,v,w){if(this.hasEvalModel){const[b,x]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,_,v,w),O=await this.handler.runEvalStep(_,b,x);return this.convertHandlerReturnTypeToMapOfTensors(O)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(_=!0){return this.handler.getParametersSize(_)}async loadParametersBuffer(_,v=!0){const w=await this.getParametersSize(v);if(_.length!==4*w)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(_,v)}async getContiguousParameters(_=!0){return this.handler.getContiguousParameters(_)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(R,c,s)=>{s.r(c),s.d(c,{TrainingSession:()=>T});var h=s("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const T=h.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(R,c,s)=>{s.r(c),s.d(c,{version:()=>h});const h="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(R,c,s)=>{s.r(c),s.d(c,{InferenceSession:()=>lt,TRACE:()=>Ve,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>je,Tensor:()=>ue,default:()=>e_,env:()=>L,registerBackend:()=>H});/*! + * ONNX Runtime Web v1.21.0-dev.20250206-d981b153d3 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var h=Object.defineProperty,T=Object.getOwnPropertyDescriptor,I=Object.getOwnPropertyNames,U=Object.prototype.hasOwnProperty,F=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),_=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var r in t)h(e,r,{get:t[r],enumerable:!0})},w=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of I(t))!U.call(e,i)&&i!==r&&h(e,i,{get:()=>t[i],enumerable:!(n=T(t,i))||n.enumerable});return e},b=e=>w(h({},"__esModule",{value:!0}),e),x,O,H,re,ne,G=_(()=>{x=new Map,O=[],H=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=x.get(e);if(n===void 0)x.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let i=O.indexOf(e);i!==-1&&O.splice(i,1);for(let a=0;a{let t=x.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ne=async e=>{let t=e.executionProviders||[],r=t.map(m=>typeof m=="string"?m:m.name),n=r.length===0?O:r,i,a=[],o=new Set;for(let m of n){let f=await re(m);typeof f=="string"?a.push({name:m,err:f}):(i||(i=f),i===f&&o.add(m))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(m=>`[${m.name}] ${m.err}`).join(", ")}`);for(let{name:m,err:f}of a)r.includes(m)&&console.warn(`removing requested execution provider "${m}" from session options because it is not available: ${f}`);let u=t.filter(m=>o.has(typeof m=="string"?m:m.name));return[i,new Proxy(e,{get:(m,f)=>f==="executionProviders"?u:Reflect.get(m,f)})]}}),W=_(()=>{G()}),X,D=_(()=>{X="1.21.0-dev.20250206-d981b153d3"}),A,M,P=_(()=>{D(),A="warning",M={wasm:{},webgl:{},webgpu:{},versions:{common:X},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);A=e}},get logLevel(){return A}},Object.defineProperty(M,"logLevel",{enumerable:!0})}),L,le=_(()=>{P(),L=M}),oe,Te,we=_(()=>{oe=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,m,f;u===void 0||u.mean===void 0?m=[255,255,255,255]:typeof u.mean=="number"?m=[u.mean,u.mean,u.mean,u.mean]:(m=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(m[3]=u.mean[3])),u===void 0||u.bias===void 0?f=[0,0,0,0]:typeof u.bias=="number"?f=[u.bias,u.bias,u.bias,u.bias]:(f=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(f[3]=u.bias[3]));let $=a*i,k=0,d=$,N=$*2,j=-1;o==="RGBA"?(k=0,d=$,N=$*2,j=$*3):o==="RGB"?(k=0,d=$,N=$*2):o==="RBG"&&(k=0,N=$,d=$*2);for(let K=0;K{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let i,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",m=t==null?void 0:t.norm,f,$;m===void 0||m.mean===void 0?f=[255,255,255,255]:typeof m.mean=="number"?f=[m.mean,m.mean,m.mean,m.mean]:(f=[m.mean[0],m.mean[1],m.mean[2],255],m.mean[3]!==void 0&&(f[3]=m.mean[3])),m===void 0||m.bias===void 0?$=[0,0,0,0]:typeof m.bias=="number"?$=[m.bias,m.bias,m.bias,m.bias]:($=[m.bias[0],m.bias[1],m.bias[2],0],m.bias[3]!==void 0&&($[3]=m.bias[3]));let k=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,N=0,j=1,K=2,ee=3,te=0,J=k,fe=k*2,he=-1;u==="RGBA"?(te=0,J=k,fe=k*2,he=k*3):u==="RGB"?(te=0,J=k,fe=k*2):u==="RBG"&&(te=0,fe=k,J=k*2),n=r.createImageData(i,a);for(let Me=0;Me{Ue(),ie=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,i=t.norm??{mean:255,bias:0},a,o;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",m=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",f=r*n,$=m==="RGBA"?new Float32Array(f*4):new Float32Array(f*3),k=4,d=0,N=1,j=2,K=3,ee=0,te=f,J=f*2,fe=-1;u==="RGB"&&(k=3,d=0,N=1,j=2,K=-1),m==="RGBA"?fe=f*3:m==="RBG"?(ee=0,J=f,te=f*2):m==="BGR"&&(J=0,te=f,ee=f*2);for(let he=0;he{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,u=t??{},m=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},f=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(r){let $=m();$.width=e.width,$.height=e.height;let k=f($);if(k!=null){let d=e.height,N=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,N=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=d,u.width=N}else u.tensorFormat="RGBA",u.height=d,u.width=N;k.drawImage(e,0,0),o=k.getImageData(0,0,N,d).data}else throw new Error("Can not access image data")}else if(n){let $,k;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?($=t.resizedHeight,k=t.resizedWidth):($=e.height,k=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=$,u.width=k,t!==void 0){let d=m();d.width=k,d.height=$;let N=f(d);if(N!=null)N.putImageData(e,0,0),o=N.getImageData(0,0,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 $=m();$.width=e.width,$.height=e.height;let k=f($);if(k!=null){let d=e.height,N=e.width;return k.drawImage(e,0,0,N,d),o=k.getImageData(0,0,N,d).data,u.height=d,u.width=N,ie(o,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise(($,k)=>{let d=m(),N=f(d);if(!e||!N)return k();let j=new Image;j.crossOrigin="Anonymous",j.src=e,j.onload=()=>{d.width=j.width,d.height=j.height,N.drawImage(j,0,0,d.width,d.height);let K=N.getImageData(0,0,d.width,d.height);u.height=d.height,u.width=d.width,$(ie(K.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ie(o,u);throw new Error("Input data provided is not supported - aborted tensor creation")},pe=(e,t)=>{let{width:r,height:n,download:i,dispose:a}=t,o=[1,n,r,4];return new Ke({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:a})},ke=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:a}=t;return new Ke({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},Oe=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:a}=t;return new Ke({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:i,dispose:a})},Ce=(e,t,r)=>new Ke({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Ge,be,Z,ce,Se=_(()=>{Ge=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),be=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Z=!1,ce=()=>{if(!Z){Z=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(Ge.set("int64",BigInt64Array),be.set(BigInt64Array,"int64")),t&&(Ge.set("uint64",BigUint64Array),be.set(BigUint64Array,"uint64")),r?(Ge.set("float16",Float16Array),be.set(Float16Array,"float16")):Ge.set("float16",Uint16Array)}}}),Be,Je,se=_(()=>{Ue(),Be=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Ke(e.type,e.data,t);case"cpu-pinned":return new Ke({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ke({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ke({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ke({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ke,Ue=_(()=>{we(),tt(),Se(),se(),Ke=class{constructor(e,t,r){ce();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=Ge.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let m=Ge.get(e);if(m===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&m===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${m.name} as data.`);e==="uint64"||e==="int64"?o=m.from(t,BigInt):o=m.from(t)}else if(t instanceof m)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 ${m}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let m=typeof e[0];if(m==="string")n="string",o=e;else if(m==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${m}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let m=be.get(e.constructor);if(m===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=m,o=e}if(u===void 0)u=[o.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=o,this.dataLocation="cpu"}let a=Be(i);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=a}static async fromImage(e,t){return Pe(e,t)}static fromTexture(e,t){return pe(e,t)}static fromGpuBuffer(e,t){return ke(e,t)}static fromMLTensor(e,t){return Oe(e,t)}static fromPinnedBuffer(e,t,r){return Ce(e,t,r)}toDataURL(e){return oe(this,e)}toImageData(e){return Te(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 Je(this,e)}}}),ue,ve=_(()=>{Ue(),ue=Ke}),Ve,We,Ne,je,st=_(()=>{P(),Ve=(e,t)=>{(typeof M.trace>"u"?!M.wasm.trace:!M.trace)||console.timeStamp(`${e}::ORT::${t}`)},We=(e,t)=>{var i;let r=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof M.trace>"u"?!M.wasm.trace:!M.trace)||We("BEGIN",e)},je=e=>{(typeof M.trace>"u"?!M.wasm.trace:!M.trace)||We("END",e)}}),ut,pt=_(()=>{G(),ve(),st(),ut=class Wf{constructor(t){this.handler=t}async run(t,r,n){Ne();let i={},a={};if(typeof t!="object"||t===null||t instanceof ue||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 r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ue)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let f of r){if(typeof f!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(f)===-1)throw new RangeError(`'fetches' contains invalid output name: ${f}.`);i[f]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let f=!1,$=Object.getOwnPropertyNames(r);for(let k of this.outputNames)if($.indexOf(k)!==-1){let d=r[k];(d===null||d instanceof ue)&&(f=!0,o=!1,i[k]=d)}if(f){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let f of this.inputNames)if(typeof t[f]>"u")throw new Error(`input '${f}' is missing in 'feeds'.`);if(o)for(let f of this.outputNames)i[f]=null;let u=await this.handler.run(t,i,a),m={};for(let f in u)if(Object.hasOwnProperty.call(u,f)){let $=u[f];$ instanceof ue?m[f]=$:m[f]=new ue($.type,$.data,$.dims)}return je(),m}async release(){return this.handler.dispose()}static async create(t,r,n,i){Ne();let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let $=t,k=0,d=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(k=r,!Number.isSafeInteger(k))throw new RangeError("'byteOffset' must be an integer.");if(k<0||k>=$.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${$.byteLength}).`);if(d=t.byteLength-k,typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||k+d>$.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$.byteLength-k}].`);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 r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array($,k,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,m]=await ne(o),f=await u.createInferenceSessionHandler(a,m);return je(),new Wf(f)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,mt=_(()=>{pt(),lt=ut}),B=_(()=>{}),ae=_(()=>{}),q=_(()=>{}),me=_(()=>{}),$e={};v($e,{InferenceSession:()=>lt,TRACE:()=>Ve,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>je,Tensor:()=>ue,env:()=>L,registerBackend:()=>H});var Re=_(()=>{W(),le(),mt(),ve(),B(),ae(),st(),q(),me()}),qe=_(()=>{}),at={};v(at,{default:()=>St});var ct,vt,St,kt=_(()=>{var e;Qh(),pr(),Gr(),ct="ort-wasm-proxy-worker",vt=((e=globalThis.self)==null?void 0:e.name)===ct,vt&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Lr(n.wasm).then(()=>{ri(n).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})})},i=>{postMessage({type:r,err:i})});break;case"init-ep":{let{epName:i,env:a}=n;ji(a,i).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:i}=n,a=On(i);postMessage({type:r,out:a});break}case"create":{let{model:i,options:a}=n;Bc(i,a).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":Rc(n),postMessage({type:r});break;case"run":{let{sessionId:i,inputIndices:a,inputs:o,outputIndices:u,options:m}=n;tn(i,a,o,u,new Array(u.length).fill(null),m).then(f=>{f.some($=>$[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:f},ph([...o,...f]))},f=>{postMessage({type:r,err:f})});break}case"end-profiling":yr(n),postMessage({type:r});break;default:}}catch(i){postMessage({type:r,err:i})}}),St=vt?null:t=>new Worker(t??Vs,{type:"module",name:ct})}),is={};v(is,{default:()=>zs});var Ms,$s,zs,ar=_(()=>{var e;$s=(Ms=import.meta.url,async function(t={}){function r(){return yt.buffer!=Ut.buffer&&Ss(),Ut}function n(){return yt.buffer!=Ut.buffer&&Ss(),Qt}function i(){return yt.buffer!=Ut.buffer&&Ss(),gs}function a(){return yt.buffer!=Ut.buffer&&Ss(),ot}function o(){return yt.buffer!=Ut.buffer&&Ss(),Et}function u(){return yt.buffer!=Ut.buffer&&Ss(),hs}function m(){return yt.buffer!=Ut.buffer&&Ss(),js}function f(){return yt.buffer!=Ut.buffer&&Ss(),gn}var $,k,d=Object.assign({},t),N=new Promise((l,g)=>{$=l,k=g}),j=typeof window=="object",K=typeof importScripts=="function",ee=K&&self.name=="em-pthread";d.mountExternalData=(l,g)=>{l.startsWith("./")&&(l=l.substring(2)),(d.Fb||(d.Fb=new Map)).set(l,g)},d.unmountExternalData=()=>{delete d.Fb};var te=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let J=()=>{let l=(S,z,Q)=>(...ye)=>{let Ye=bn,nt=z==null?void 0:z();ye=S(...ye);let wt=z==null?void 0:z();return nt!==wt&&(S=wt,Q(nt),z=Q=null),bn!=Ye?new Promise((Ct,Vt)=>{Ah={resolve:Ct,reject:Vt}}):ye},g=S=>async(...z)=>{var Q;try{if(d.Gb)throw Error("Session already started");let ye=d.Gb={hc:z[0],errors:[]},Ye=await S(...z);if(d.Gb!==ye)throw Error("Session mismatch");(Q=d.Hb)==null||Q.flush();let nt=ye.errors;if(0Ct),0d._OrtCreateSession,S=>d._OrtCreateSession=S),d._OrtRun=g(l(d._OrtRun,()=>d._OrtRun,S=>d._OrtRun=S)),d._OrtRunWithBinding=g(l(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,S=>d._OrtRunWithBinding=S)),d._OrtBindInput=l(d._OrtBindInput,()=>d._OrtBindInput,S=>d._OrtBindInput=S),J=void 0};d.jsepInit=(l,g)=>{if(J==null||J(),l==="webgpu"){[d.Hb,d.Vb,d.Zb,d.Ob,d.Yb,d.kb,d.$b,d.cc,d.Wb,d.Xb,d.ac]=g;let S=d.Hb;d.jsepRegisterBuffer=(z,Q,ye,Ye)=>S.registerBuffer(z,Q,ye,Ye),d.jsepGetBuffer=z=>S.getBuffer(z),d.jsepCreateDownloader=(z,Q,ye)=>S.createDownloader(z,Q,ye),d.jsepOnCreateSession=z=>{S.onCreateSession(z)},d.jsepOnReleaseSession=z=>{S.onReleaseSession(z)},d.jsepOnRunStart=z=>S.onRunStart(z),d.dc=(z,Q)=>{S.upload(z,Q)}}else if(l==="webnn"){[d.Hb,d.bc,d.Pb,d.jsepEnsureTensor,d.ec,d.jsepDownloadTensor]=g,d.jsepReleaseTensorId=d.Pb;let S=d.Hb;d.jsepOnRunStart=z=>S.onRunStart(z),d.jsepRegisterMLContext=(z,Q)=>{S.registerMLContext(z,Q)},d.jsepOnReleaseSession=z=>{S.onReleaseSession(z)},d.jsepCreateMLTensorDownloader=(z,Q)=>S.createMLTensorDownloader(z,Q),d.jsepRegisterMLTensor=(z,Q,ye)=>S.registerMLTensor(z,Q,ye),d.jsepCreateMLContext=z=>S.createMLContext(z),d.jsepRegisterMLConstant=(z,Q,ye,Ye,nt)=>S.registerMLConstant(z,Q,ye,Ye,nt,d.Fb)}};var fe,he,Me=Object.assign({},d),Ae=(l,g)=>{throw g},Le="";(j||K)&&(K?Le=self.location.href:typeof document<"u"&&document.currentScript&&(Le=document.currentScript.src),Ms&&(Le=Ms),Le=Le.startsWith("blob:")?"":Le.substr(0,Le.replace(/[?#].*/,"").lastIndexOf("/")+1),K&&(he=l=>{var g=new XMLHttpRequest;return g.open("GET",l,!1),g.responseType="arraybuffer",g.send(null),new Uint8Array(g.response)}),fe=(l,g,S)=>{var z=new XMLHttpRequest;z.open("GET",l,!0),z.responseType="arraybuffer",z.onload=()=>{z.status==200||z.status==0&&z.response?g(z.response):S()},z.onerror=S,z.send(null)});var et,dt=console.log.bind(console),Pt=console.error.bind(console),qt=dt,Bt=Pt;if(Object.assign(d,Me),Me=null,ee){let l=function(g){try{var S=g.data,z=S.cmd;if(z==="load"){let Q=[];self.onmessage=ye=>Q.push(ye),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ye of Q)l(ye);self.onmessage=l};for(let ye of S.handlers)d[ye]&&!d[ye].proxy||(d[ye]=(...Ye)=>{postMessage({Nb:"callHandler",pc:ye,args:Ye})},ye=="print"&&(qt=d[ye]),ye=="printErr"&&(Bt=d[ye]));yt=S.wasmMemory,Ss(),At(S.wasmModule)}else if(z==="run"){Lh(S.pthread_ptr,0,0,1,0,0),kh(S.pthread_ptr),r_(),wm(),ts||(gf(),ts=!0);try{n_(S.start_routine,S.arg)}catch(Q){if(Q!="unwind")throw Q}}else z==="cancel"?Wa()&&eh(-1):S.target!=="setimmediate"&&(z==="checkMailbox"?ts&&Wp():z&&(Bt(`worker: received unknown command ${z}`),Bt(S)))}catch(Q){throw yf(),Q}};var At,ts=!1;Bt=function(...g){g=g.join(" "),console.error(g)},self.alert=function(...g){postMessage({Nb:"alert",text:g.join(" "),rc:Wa()})},d.instantiateWasm=(g,S)=>new Promise(z=>{At=Q=>{Q=new WebAssembly.Instance(Q,mm()),S(Q),z()}}),self.onunhandledrejection=g=>{throw g.reason||g},self.onmessage=l}d.wasmBinary&&(et=d.wasmBinary);var yt,Ht,ps,Ut,Qt,gs,ot,Et,hs,js,Qs,Nr,gn,jr=!1;function Ss(){var l=yt.buffer;d.HEAP8=Ut=new Int8Array(l),d.HEAP16=gs=new Int16Array(l),d.HEAPU8=Qt=new Uint8Array(l),d.HEAPU16=ot=new Uint16Array(l),d.HEAP32=Et=new Int32Array(l),d.HEAPU32=hs=new Uint32Array(l),d.HEAPF32=js=new Float32Array(l),d.HEAPF64=gn=new Float64Array(l),d.HEAP64=Qs=new BigInt64Array(l),d.HEAPU64=Nr=new BigUint64Array(l)}if(!ee){if(!((yt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof te))throw Bt("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");Ss()}var sr=[],Fn=[],gh=[],Wi=0,Vc=null;function um(){if(--Wi==0&&Vc){var l=Vc;Vc=null,l()}}function ii(l){throw Bt(l="Aborted("+l+")"),jr=!0,ps=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),k(l),l}var yh,dm=l=>l.startsWith("data:application/octet-stream;base64,"),cm=l=>l.startsWith("file://");function pm(l){if(l==yh&&et)return new Uint8Array(et);if(he)return he(l);throw"both async and sync fetching of the wasm failed"}function hm(l,g,S){return function(z){if(!et&&(j||K)){if(typeof fetch=="function"&&!cm(z))return fetch(z,{credentials:"same-origin"}).then(Q=>{if(!Q.ok)throw`failed to load wasm binary file at '${z}'`;return Q.arrayBuffer()}).catch(()=>pm(z));if(fe)return new Promise((Q,ye)=>{fe(z,Ye=>Q(new Uint8Array(Ye)),ye)})}return Promise.resolve().then(()=>pm(z))}(l).then(z=>WebAssembly.instantiate(z,g)).then(S,z=>{Bt(`failed to asynchronously prepare wasm: ${z}`),ii(z)})}function mm(){return{a:{O:s_,Aa:t_,b:o_,aa:xm,B:Em,qa:Cm,Y:$m,_:km,ra:Im,oa:Am,ha:Om,na:Fm,L:Dm,Z:Lm,W:zm,pa:Bm,X:Rm,va:a_,F:l_,Q:u_,P:c_,E:h_,u:m_,q:f_,G:__,A:x_,R:T_,ua:P_,ka:E_,U:C_,ba:S_,H:$_,ja:kh,ta:k_,t:I_,Ba:A_,x:D_,o:L_,m:B_,c:Sh,n:R_,k:U_,w:V_,p:W_,f:G_,s:K_,l:H_,e:q_,j:Q_,i:X_,g:Y_,d:J_,ea:Z_,fa:eg,ga:tg,ca:Zm,da:ef,T:sg,h:rg,D:ng,I:ig,M:og,y:ag,sa:lg,V:ug,v:sf,z:dg,N:cg,S:pg,za:hg,ya:mg,la:of,ma:af,$:xh,C:lf,K:uf,ia:df,J:cf,a:yt,xa:vh,wa:mf,r:gg}}}var wh={916868:(l,g,S,z,Q)=>{if(d===void 0||!d.Fb)return 1;if((l=Xs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=d.Fb.get(l)))return 2;if(g=Number(g>>>0),S=Number(S>>>0),z=Number(z>>>0),g+S>l.byteLength)return 3;try{let ye=l.subarray(g,g+S);switch(Q){case 0:n().set(ye,z>>>0);break;case 1:d.dc(z,ye);break;default:return 4}return 0}catch{return 4}},917583:(l,g,S)=>{d.ec(l,n().subarray(g>>>0,g+S>>>0))},917646:()=>d.bc(),917687:l=>{d.Pb(l)},917723:()=>{d.Wb()},917754:()=>{d.Xb()},917783:()=>{d.ac()},917808:l=>d.Vb(l),917841:l=>d.Zb(l),917873:(l,g,S)=>{d.Ob(Number(l),Number(g),Number(S),!0)},917936:(l,g,S)=>{d.Ob(Number(l),Number(g),Number(S))},917993:()=>typeof wasmOffsetConverter<"u",918050:l=>{d.kb("Abs",l,void 0)},918101:l=>{d.kb("Neg",l,void 0)},918152:l=>{d.kb("Floor",l,void 0)},918205:l=>{d.kb("Ceil",l,void 0)},918257:l=>{d.kb("Reciprocal",l,void 0)},918315:l=>{d.kb("Sqrt",l,void 0)},918367:l=>{d.kb("Exp",l,void 0)},918418:l=>{d.kb("Erf",l,void 0)},918469:l=>{d.kb("Sigmoid",l,void 0)},918524:(l,g,S)=>{d.kb("HardSigmoid",l,{alpha:g,beta:S})},918603:l=>{d.kb("Log",l,void 0)},918654:l=>{d.kb("Sin",l,void 0)},918705:l=>{d.kb("Cos",l,void 0)},918756:l=>{d.kb("Tan",l,void 0)},918807:l=>{d.kb("Asin",l,void 0)},918859:l=>{d.kb("Acos",l,void 0)},918911:l=>{d.kb("Atan",l,void 0)},918963:l=>{d.kb("Sinh",l,void 0)},919015:l=>{d.kb("Cosh",l,void 0)},919067:l=>{d.kb("Asinh",l,void 0)},919120:l=>{d.kb("Acosh",l,void 0)},919173:l=>{d.kb("Atanh",l,void 0)},919226:l=>{d.kb("Tanh",l,void 0)},919278:l=>{d.kb("Not",l,void 0)},919329:(l,g,S)=>{d.kb("Clip",l,{min:g,max:S})},919398:l=>{d.kb("Clip",l,void 0)},919450:(l,g)=>{d.kb("Elu",l,{alpha:g})},919508:l=>{d.kb("Gelu",l,void 0)},919560:l=>{d.kb("Relu",l,void 0)},919612:(l,g)=>{d.kb("LeakyRelu",l,{alpha:g})},919676:(l,g)=>{d.kb("ThresholdedRelu",l,{alpha:g})},919746:(l,g)=>{d.kb("Cast",l,{to:g})},919804:l=>{d.kb("Add",l,void 0)},919855:l=>{d.kb("Sub",l,void 0)},919906:l=>{d.kb("Mul",l,void 0)},919957:l=>{d.kb("Div",l,void 0)},920008:l=>{d.kb("Pow",l,void 0)},920059:l=>{d.kb("Equal",l,void 0)},920112:l=>{d.kb("Greater",l,void 0)},920167:l=>{d.kb("GreaterOrEqual",l,void 0)},920229:l=>{d.kb("Less",l,void 0)},920281:l=>{d.kb("LessOrEqual",l,void 0)},920340:(l,g,S,z,Q)=>{d.kb("ReduceMean",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},920515:(l,g,S,z,Q)=>{d.kb("ReduceMax",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},920689:(l,g,S,z,Q)=>{d.kb("ReduceMin",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},920863:(l,g,S,z,Q)=>{d.kb("ReduceProd",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},921038:(l,g,S,z,Q)=>{d.kb("ReduceSum",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},921212:(l,g,S,z,Q)=>{d.kb("ReduceL1",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},921385:(l,g,S,z,Q)=>{d.kb("ReduceL2",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},921558:(l,g,S,z,Q)=>{d.kb("ReduceLogSum",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},921735:(l,g,S,z,Q)=>{d.kb("ReduceSumSquare",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},921915:(l,g,S,z,Q)=>{d.kb("ReduceLogSumExp",l,{keepDims:!!g,noopWithEmptyAxes:!!S,axes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},922095:l=>{d.kb("Where",l,void 0)},922148:(l,g,S)=>{d.kb("Transpose",l,{perm:g?Array.from(o().subarray(Number(g)>>>0,Number(S)>>>0)):[]})},922272:(l,g,S,z)=>{d.kb("DepthToSpace",l,{blocksize:g,mode:Xs(S),format:z?"NHWC":"NCHW"})},922405:(l,g,S,z)=>{d.kb("DepthToSpace",l,{blocksize:g,mode:Xs(S),format:z?"NHWC":"NCHW"})},922538:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:g,dilations:[S],group:z,kernelShape:[Q],pads:[ye,Ye],strides:[nt],wIsConst:()=>!!r()[Ct>>>0],outputPadding:Vt?Array.from(o().subarray(Number(Vt)>>>0,Number(ms)>>>0)):[],outputShape:xs?Array.from(o().subarray(Number(xs)>>>0,Number(He)>>>0)):[],activation:Xs(ls)})},922971:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:g,dilations:Array.from(o().subarray(Number(S)>>>0,2+(Number(S)>>>0)>>>0)),group:z,kernelShape:Array.from(o().subarray(Number(Q)>>>0,2+(Number(Q)>>>0)>>>0)),pads:Array.from(o().subarray(Number(ye)>>>0,4+(Number(ye)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Ye)>>>0,2+(Number(Ye)>>>0)>>>0)),wIsConst:()=>!!r()[wt>>>0],outputPadding:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],outputShape:ms?Array.from(o().subarray(Number(ms)>>>0,Number(xs)>>>0)):[],activation:Xs(He)})},923632:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:g,dilations:[S],group:z,kernelShape:[Q],pads:[ye,Ye],strides:[nt],wIsConst:()=>!!r()[Ct>>>0],outputPadding:Vt?Array.from(o().subarray(Number(Vt)>>>0,Number(ms)>>>0)):[],outputShape:xs?Array.from(o().subarray(Number(xs)>>>0,Number(He)>>>0)):[],activation:Xs(ls)})},924065:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:g,dilations:Array.from(o().subarray(Number(S)>>>0,2+(Number(S)>>>0)>>>0)),group:z,kernelShape:Array.from(o().subarray(Number(Q)>>>0,2+(Number(Q)>>>0)>>>0)),pads:Array.from(o().subarray(Number(ye)>>>0,4+(Number(ye)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Ye)>>>0,2+(Number(Ye)>>>0)>>>0)),wIsConst:()=>!!r()[wt>>>0],outputPadding:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],outputShape:ms?Array.from(o().subarray(Number(ms)>>>0,Number(xs)>>>0)):[],activation:Xs(He)})},924726:(l,g)=>{d.kb("GlobalAveragePool",l,{format:g?"NHWC":"NCHW"})},924817:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:g,ceil_mode:S,count_include_pad:z,storage_order:Q,dilations:ye?Array.from(o().subarray(Number(ye)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(o().subarray(Number(ms)>>>0,Number(xs)>>>0)):[]})},925296:(l,g)=>{d.kb("GlobalAveragePool",l,{format:g?"NHWC":"NCHW"})},925387:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:g,ceil_mode:S,count_include_pad:z,storage_order:Q,dilations:ye?Array.from(o().subarray(Number(ye)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(o().subarray(Number(ms)>>>0,Number(xs)>>>0)):[]})},925866:(l,g)=>{d.kb("GlobalMaxPool",l,{format:g?"NHWC":"NCHW"})},925953:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:g,ceil_mode:S,count_include_pad:z,storage_order:Q,dilations:ye?Array.from(o().subarray(Number(ye)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(o().subarray(Number(ms)>>>0,Number(xs)>>>0)):[]})},926428:(l,g)=>{d.kb("GlobalMaxPool",l,{format:g?"NHWC":"NCHW"})},926515:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:g,ceil_mode:S,count_include_pad:z,storage_order:Q,dilations:ye?Array.from(o().subarray(Number(ye)>>>0,Number(Ye)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],strides:ms?Array.from(o().subarray(Number(ms)>>>0,Number(xs)>>>0)):[]})},926990:(l,g,S,z,Q)=>{d.kb("Gemm",l,{alpha:g,beta:S,transA:z,transB:Q})},927094:l=>{d.kb("MatMul",l,void 0)},927148:(l,g,S,z)=>{d.kb("ArgMax",l,{keepDims:!!g,selectLastIndex:!!S,axis:z})},927256:(l,g,S,z)=>{d.kb("ArgMin",l,{keepDims:!!g,selectLastIndex:!!S,axis:z})},927364:(l,g)=>{d.kb("Softmax",l,{axis:g})},927427:(l,g)=>{d.kb("Concat",l,{axis:g})},927487:(l,g,S,z,Q)=>{d.kb("Split",l,{axis:g,numOutputs:S,splitSizes:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},927643:l=>{d.kb("Expand",l,void 0)},927697:(l,g)=>{d.kb("Gather",l,{axis:Number(g)})},927768:(l,g)=>{d.kb("GatherElements",l,{axis:Number(g)})},927847:(l,g)=>{d.kb("GatherND",l,{batch_dims:Number(g)})},927926:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt)=>{d.kb("Resize",l,{antialias:g,axes:S?Array.from(o().subarray(Number(S)>>>0,Number(z)>>>0)):[],coordinateTransformMode:Xs(Q),cubicCoeffA:ye,excludeOutside:Ye,extrapolationValue:nt,keepAspectRatioPolicy:Xs(wt),mode:Xs(Ct),nearestMode:Xs(Vt)})},928288:(l,g,S,z,Q,ye,Ye)=>{d.kb("Slice",l,{starts:g?Array.from(o().subarray(Number(g)>>>0,Number(S)>>>0)):[],ends:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[],axes:ye?Array.from(o().subarray(Number(ye)>>>0,Number(Ye)>>>0)):[]})},928552:l=>{d.kb("Tile",l,void 0)},928604:(l,g,S)=>{d.kb("InstanceNormalization",l,{epsilon:g,format:S?"NHWC":"NCHW"})},928718:(l,g,S)=>{d.kb("InstanceNormalization",l,{epsilon:g,format:S?"NHWC":"NCHW"})},928832:l=>{d.kb("Range",l,void 0)},928885:(l,g)=>{d.kb("Einsum",l,{equation:Xs(g)})},928966:(l,g,S,z,Q)=>{d.kb("Pad",l,{mode:g,value:S,pads:z?Array.from(o().subarray(Number(z)>>>0,Number(Q)>>>0)):[]})},929109:(l,g,S,z,Q,ye)=>{d.kb("BatchNormalization",l,{epsilon:g,momentum:S,spatial:!!Q,trainingMode:!!z,format:ye?"NHWC":"NCHW"})},929278:(l,g,S,z,Q,ye)=>{d.kb("BatchNormalization",l,{epsilon:g,momentum:S,spatial:!!Q,trainingMode:!!z,format:ye?"NHWC":"NCHW"})},929447:(l,g,S)=>{d.kb("CumSum",l,{exclusive:Number(g),reverse:Number(S)})},929544:(l,g,S)=>{d.kb("DequantizeLinear",l,{axis:g,blockSize:S})},929634:(l,g,S,z,Q)=>{d.kb("GridSample",l,{align_corners:g,mode:Xs(S),padding_mode:Xs(z),format:Q?"NHWC":"NCHW"})},929804:(l,g,S,z,Q)=>{d.kb("GridSample",l,{align_corners:g,mode:Xs(S),padding_mode:Xs(z),format:Q?"NHWC":"NCHW"})},929974:(l,g,S,z,Q,ye,Ye,nt,wt)=>{d.kb("Attention",l,{numHeads:g,isUnidirectional:S,maskFilterValue:z,scale:Q,doRotary:ye,qkvHiddenSizes:Ye?Array.from(o().subarray(Number(nt)>>>0,Number(nt)+Ye>>>0)):[],pastPresentShareBuffer:!!wt})},930246:l=>{d.kb("BiasAdd",l,void 0)},930301:l=>{d.kb("BiasSplitGelu",l,void 0)},930362:l=>{d.kb("FastGelu",l,void 0)},930418:(l,g,S,z,Q,ye,Ye,nt,wt,Ct,Vt,ms,xs,He,ls,Us)=>{d.kb("Conv",l,{format:ms?"NHWC":"NCHW",auto_pad:g,dilations:S?Array.from(o().subarray(Number(S)>>>0,Number(z)>>>0)):[],group:Q,kernel_shape:ye?Array.from(o().subarray(Number(ye)>>>0,Number(Ye)>>>0)):[],pads:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],strides:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Vt)>>>0)):[],w_is_const:()=>!!r()[Number(xs)>>>0],activation:Xs(He),activation_params:ls?Array.from(m().subarray(Number(ls)>>>0,Number(Us)>>>0)):[]})},931002:l=>{d.kb("Gelu",l,void 0)},931054:(l,g,S,z,Q,ye,Ye,nt,wt)=>{d.kb("GroupQueryAttention",l,{numHeads:g,kvNumHeads:S,scale:z,softcap:Q,doRotary:ye,rotaryInterleaved:Ye,smoothSoftmax:nt,localWindowSize:wt})},931271:(l,g,S,z)=>{d.kb("LayerNormalization",l,{axis:g,epsilon:S,simplified:!!z})},931382:(l,g,S,z)=>{d.kb("LayerNormalization",l,{axis:g,epsilon:S,simplified:!!z})},931493:(l,g,S,z,Q,ye)=>{d.kb("MatMulNBits",l,{k:g,n:S,accuracyLevel:z,bits:Q,blockSize:ye})},931620:(l,g,S,z,Q,ye)=>{d.kb("MultiHeadAttention",l,{numHeads:g,isUnidirectional:S,maskFilterValue:z,scale:Q,doRotary:ye})},931779:(l,g)=>{d.kb("QuickGelu",l,{alpha:g})},931843:(l,g,S,z,Q)=>{d.kb("RotaryEmbedding",l,{interleaved:!!g,numHeads:S,rotaryEmbeddingDim:z,scale:Q})},931982:(l,g,S)=>{d.kb("SkipLayerNormalization",l,{epsilon:g,simplified:!!S})},932084:(l,g,S)=>{d.kb("SkipLayerNormalization",l,{epsilon:g,simplified:!!S})},932186:(l,g,S,z)=>{d.kb("GatherBlockQuantized",l,{gatherAxis:g,quantizeAxis:S,blockSize:z})},932307:l=>{d.$b(l)},932341:(l,g)=>d.cc(Number(l),Number(g),d.Gb.hc,d.Gb.errors)};function t_(l,g,S){return qm(async()=>{await d.Yb(Number(l),Number(g),Number(S))})}function s_(){return typeof wasmOffsetConverter<"u"}function bh(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var Mh=l=>{l.terminate(),l.onmessage=()=>{}},fm=l=>{oi.length==0&&(Mm(),bm(oi[0]));var g=oi.pop();if(!g)return 6;Ki.push(g),yn[l.Bb]=g,g.Bb=l.Bb;var S={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return g.postMessage(S,l.nc),0},Gi=0,Ns=(l,g,...S)=>{for(var z=2*S.length,Q=Rh(),ye=Bh(8*z),Ye=ye>>>3,nt=0;nt>>0]=wt)}return l=wf(l,0,z,ye,g),th(Q),l};function vh(l){if(ee)return Ns(0,1,l);if(ps=l,!(0{if(ps=l,ee)throw _m(l),"unwind";vh(l)},oi=[],Ki=[],gm=[],yn={},ym=l=>{var g=l.Bb;delete yn[g],oi.push(l),Ki.splice(Ki.indexOf(l),1),l.Bb=0,zh(g)};function wm(){gm.forEach(l=>l())}var bm=l=>new Promise(g=>{l.onmessage=Q=>{var ye=(Q=Q.data).cmd;if(Q.targetThread&&Q.targetThread!=Wa()){var Ye=yn[Q.targetThread];Ye?Ye.postMessage(Q,Q.transferList):Bt(`Internal error! Worker sent a message "${ye}" to target pthread ${Q.targetThread}, but that thread no longer exists!`)}else ye==="checkMailbox"?Wp():ye==="spawnThread"?fm(Q):ye==="cleanupThread"?ym(yn[Q.thread]):ye==="killThread"?(Q=Q.thread,ye=yn[Q],delete yn[Q],Mh(ye),zh(Q),Ki.splice(Ki.indexOf(ye),1),ye.Bb=0):ye==="cancelThread"?yn[Q.thread].postMessage({cmd:"cancel"}):ye==="loaded"?(l.loaded=!0,g(l)):ye==="alert"?alert(`Thread ${Q.threadId}: ${Q.text}`):Q.target==="setimmediate"?l.postMessage(Q):ye==="callHandler"?d[Q.handler](...Q.args):ye&&Bt(`worker sent an unknown command ${ye}`)},l.onerror=Q=>{throw Bt(`worker sent an error! ${Q.filename}:${Q.lineno}: ${Q.message}`),Q};var S,z=[];for(S of[])d.hasOwnProperty(S)&&z.push(S);l.postMessage({cmd:"load",handlers:z,wasmMemory:yt,wasmModule:Ht})});function Mm(){var l=new Worker(import.meta.url.startsWith("file:")?new URL(s("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),s.b):new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});oi.push(l)}var Vp=l=>{for(;0{var l=Wa(),g=u()[l+52>>>2>>>0];l=u()[l+56>>>2>>>0],Mf(g,g-l),th(g)},n_=(l,g)=>{Gi=0,l=vf(l,g),0>>=0);throw g>>>=0,S>>>=0,u()[z.Kb+16>>>2>>>0]=0,u()[z.Kb+4>>>2>>>0]=g,u()[z.Kb+8>>>2>>>0]=S,l}function vm(l,g,S,z){return ee?Ns(2,1,l,g,S,z):xm(l,g,S,z)}function xm(l,g,S,z){if(l>>>=0,g>>>=0,S>>>=0,z>>>=0,te===void 0)return Bt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Q=[];return ee&&Q.length===0?vm(l,g,S,z):(l={ic:S,Bb:l,Rb:z,nc:Q},ee?(l.Nb="spawnThread",postMessage(l,Q),0):fm(l))}var Tm=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Pm=(l,g,S)=>{var z=(g>>>=0)+S;for(S=g;l[S]&&!(S>=z);)++S;if(16(Q=(240&Q)==224?(15&Q)<<12|ye<<6|Ye:(7&Q)<<18|ye<<12|Ye<<6|63&l[g++])?z+=String.fromCharCode(Q):(Q-=65536,z+=String.fromCharCode(55296|Q>>10,56320|1023&Q))}}else z+=String.fromCharCode(Q)}return z},Xs=(l,g)=>(l>>>=0)?Pm(n(),l,g):"";function Em(l,g,S){return ee?Ns(3,1,l,g,S):0}function Cm(l,g){if(ee)return Ns(4,1,l,g)}var Th=l=>{for(var g=0,S=0;S=z?g++:2047>=z?g+=2:55296<=z&&57343>=z?(g+=4,++S):g+=3}return g},Sm=(l,g,S,z)=>{if(!(0>>=0;z=S+z-1;for(var ye=0;ye=Ye&&(Ye=65536+((1023&Ye)<<10)|1023&l.charCodeAt(++ye)),127>=Ye){if(S>=z)break;g[S++>>>0]=Ye}else{if(2047>=Ye){if(S+1>=z)break;g[S++>>>0]=192|Ye>>6}else{if(65535>=Ye){if(S+2>=z)break;g[S++>>>0]=224|Ye>>12}else{if(S+3>=z)break;g[S++>>>0]=240|Ye>>18,g[S++>>>0]=128|Ye>>12&63}g[S++>>>0]=128|Ye>>6&63}g[S++>>>0]=128|63&Ye}}return g[S>>>0]=0,S-Q},Ua=(l,g,S)=>Sm(l,n(),g,S);function $m(l,g){if(ee)return Ns(5,1,l,g)}function km(l,g,S){if(ee)return Ns(6,1,l,g,S)}function Im(l,g,S){return ee?Ns(7,1,l,g,S):0}function Am(l,g){if(ee)return Ns(8,1,l,g)}function Om(l,g,S){if(ee)return Ns(9,1,l,g,S)}function Fm(l,g,S,z){if(ee)return Ns(10,1,l,g,S,z)}function Dm(l,g,S,z){if(ee)return Ns(11,1,l,g,S,z)}function Lm(l,g,S,z){if(ee)return Ns(12,1,l,g,S,z)}function zm(l){if(ee)return Ns(13,1,l)}function Bm(l,g){if(ee)return Ns(14,1,l,g)}function Rm(l,g,S){if(ee)return Ns(15,1,l,g,S)}var Nm,ai,a_=()=>{ii("")},wn=l=>{for(var g="";n()[l>>>0];)g+=Nm[n()[l++>>>0]];return g},Ph={},Eh={};function Dn(l,g,S={}){if(!("argPackAdvance"in g))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(z,Q,ye={}){var Ye=Q.name;if(!z)throw new ai(`type "${Ye}" must have a positive integer typeid pointer`);if(Eh.hasOwnProperty(z)){if(ye.Tb)return;throw new ai(`Cannot register type '${Ye}' twice`)}Eh[z]=Q,Ph.hasOwnProperty(z)&&(Q=Ph[z],delete Ph[z],Q.forEach(nt=>nt()))}(l,g,S)}var jm=(l,g,S)=>{switch(g){case 1:return S?z=>r()[z>>>0]:z=>n()[z>>>0];case 2:return S?z=>i()[z>>>1>>>0]:z=>a()[z>>>1>>>0];case 4:return S?z=>o()[z>>>2>>>0]:z=>u()[z>>>2>>>0];case 8:return S?z=>Qs[z>>>3]:z=>Nr[z>>>3];default:throw new TypeError(`invalid integer width (${g}): ${l}`)}};function l_(l,g,S){S>>>=0,Dn(l>>>=0,{name:g=wn(g>>>0),fromWireType:z=>z,toWireType:function(z,Q){if(typeof Q!="bigint"&&typeof Q!="number")throw Q=Q===null?"null":(z=typeof Q)=="object"||z==="array"||z==="function"?Q.toString():""+Q,new TypeError(`Cannot convert "${Q}" to ${this.name}`);return typeof Q=="number"&&(Q=BigInt(Q)),Q},argPackAdvance:li,readValueFromPointer:jm(g,S,g.indexOf("u")==-1),Eb:null})}var li=8;function u_(l,g,S,z){Dn(l>>>=0,{name:g=wn(g>>>0),fromWireType:function(Q){return!!Q},toWireType:function(Q,ye){return ye?S:z},argPackAdvance:li,readValueFromPointer:function(Q){return this.fromWireType(n()[Q>>>0])},Eb:null})}var Ch=[],Ln=[];function Sh(l){9<(l>>>=0)&&--Ln[l+1]==0&&(Ln[l]=void 0,Ch.push(l))}var Ir=l=>{if(!l)throw new ai("Cannot use deleted val. handle = "+l);return Ln[l]},Ur=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let g=Ch.pop()||Ln.length;return Ln[g]=l,Ln[g+1]=1,g}};function $h(l){return this.fromWireType(u()[l>>>2>>>0])}var d_={name:"emscripten::val",fromWireType:l=>{var g=Ir(l);return Sh(l),g},toWireType:(l,g)=>Ur(g),argPackAdvance:li,readValueFromPointer:$h,Eb:null};function c_(l){return Dn(l>>>0,d_)}var p_=(l,g)=>{switch(g){case 4:return function(S){return this.fromWireType(m()[S>>>2>>>0])};case 8:return function(S){return this.fromWireType(f()[S>>>3>>>0])};default:throw new TypeError(`invalid float width (${g}): ${l}`)}};function h_(l,g,S){S>>>=0,Dn(l>>>=0,{name:g=wn(g>>>0),fromWireType:z=>z,toWireType:(z,Q)=>Q,argPackAdvance:li,readValueFromPointer:p_(g,S),Eb:null})}function m_(l,g,S,z,Q){if(l>>>=0,S>>>=0,g=wn(g>>>0),Q===-1&&(Q=4294967295),Q=nt=>nt,z===0){var ye=32-8*S;Q=nt=>nt<>>ye}var Ye=g.includes("unsigned")?function(nt,wt){return wt>>>0}:function(nt,wt){return wt};Dn(l,{name:g,fromWireType:Q,toWireType:Ye,argPackAdvance:li,readValueFromPointer:jm(g,S,z!==0),Eb:null})}function f_(l,g,S){function z(ye){var Ye=u()[ye>>>2>>>0];return ye=u()[ye+4>>>2>>>0],new Q(r().buffer,ye,Ye)}var Q=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][g];Dn(l>>>=0,{name:S=wn(S>>>0),fromWireType:z,argPackAdvance:li,readValueFromPointer:z},{Tb:!0})}function __(l,g){l>>>=0;var S=(g=wn(g>>>0))==="std::string";Dn(l,{name:g,fromWireType:function(z){var Q=u()[z>>>2>>>0],ye=z+4;if(S)for(var Ye=ye,nt=0;nt<=Q;++nt){var wt=ye+nt;if(nt==Q||n()[wt>>>0]==0){if(Ye=Xs(Ye,wt-Ye),Ct===void 0)var Ct=Ye;else Ct+="\0",Ct+=Ye;Ye=wt+1}}else{for(Ct=Array(Q),nt=0;nt>>0]);Ct=Ct.join("")}return Mn(z),Ct},toWireType:function(z,Q){Q instanceof ArrayBuffer&&(Q=new Uint8Array(Q));var ye=typeof Q=="string";if(!(ye||Q instanceof Uint8Array||Q instanceof Uint8ClampedArray||Q instanceof Int8Array))throw new ai("Cannot pass non-string to std::string");var Ye=S&&ye?Th(Q):Q.length,nt=Zp(4+Ye+1),wt=nt+4;if(u()[nt>>>2>>>0]=Ye,S&&ye)Ua(Q,wt,Ye+1);else if(ye)for(ye=0;ye>>0]=Ct}else for(ye=0;ye>>0]=Q[ye];return z!==null&&z.push(Mn,nt),nt},argPackAdvance:li,readValueFromPointer:$h,Eb(z){Mn(z)}})}var Um=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,g_=(l,g)=>{for(var S=l>>1,z=S+g/2;!(S>=z)&&a()[S>>>0];)++S;if(32<(S<<=1)-l&&Um)return Um.decode(n().slice(l,S));for(S="",z=0;!(z>=g/2);++z){var Q=i()[l+2*z>>>1>>>0];if(Q==0)break;S+=String.fromCharCode(Q)}return S},y_=(l,g,S)=>{if(S??(S=2147483647),2>S)return 0;var z=g;S=(S-=2)<2*l.length?S/2:l.length;for(var Q=0;Q>>1>>>0]=ye,g+=2}return i()[g>>>1>>>0]=0,g-z},w_=l=>2*l.length,b_=(l,g)=>{for(var S=0,z="";!(S>=g/4);){var Q=o()[l+4*S>>>2>>>0];if(Q==0)break;++S,65536<=Q?(Q-=65536,z+=String.fromCharCode(55296|Q>>10,56320|1023&Q)):z+=String.fromCharCode(Q)}return z},M_=(l,g,S)=>{if(g>>>=0,S??(S=2147483647),4>S)return 0;var z=g;S=z+S-4;for(var Q=0;Q=ye&&(ye=65536+((1023&ye)<<10)|1023&l.charCodeAt(++Q)),o()[g>>>2>>>0]=ye,(g+=4)+4>S)break}return o()[g>>>2>>>0]=0,g-z},v_=l=>{for(var g=0,S=0;S=z&&++S,g+=4}return g};function x_(l,g,S){if(l>>>=0,g>>>=0,S=wn(S>>>=0),g===2)var z=g_,Q=y_,ye=w_,Ye=nt=>a()[nt>>>1>>>0];else g===4&&(z=b_,Q=M_,ye=v_,Ye=nt=>u()[nt>>>2>>>0]);Dn(l,{name:S,fromWireType:nt=>{for(var wt,Ct=u()[nt>>>2>>>0],Vt=nt+4,ms=0;ms<=Ct;++ms){var xs=nt+4+ms*g;ms!=Ct&&Ye(xs)!=0||(Vt=z(Vt,xs-Vt),wt===void 0?wt=Vt:(wt+="\0",wt+=Vt),Vt=xs+g)}return Mn(nt),wt},toWireType:(nt,wt)=>{if(typeof wt!="string")throw new ai(`Cannot pass non-string to C++ string type ${S}`);var Ct=ye(wt),Vt=Zp(4+Ct+g);return u()[Vt>>>2>>>0]=Ct/g,Q(wt,Vt+4,Ct+g),nt!==null&&nt.push(Mn,Vt),Vt},argPackAdvance:li,readValueFromPointer:$h,Eb(nt){Mn(nt)}})}function T_(l,g){Dn(l>>>=0,{Ub:!0,name:g=wn(g>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var P_=()=>1;function E_(l){Lh(l>>>0,!K,1,!j,131072,!1),wm()}var Vm=l=>{if(!jr)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(o(),l>>>2,l).value.then(Wp),l+=128,Atomics.store(o(),l>>>2,1))}var Wp=()=>{var l=Wa();l&&(kh(l),Vm(bf))};function C_(l,g){(l>>>=0)==g>>>0?setTimeout(Wp):ee?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=yn[l])&&l.postMessage({cmd:"checkMailbox"})}var Ih=[];function S_(l,g,S,z,Q){for(g>>>=0,z/=2,Ih.length=z,S=Q>>>0>>>3,Q=0;Q>>0];return(g?wh[g]:yg[l])(...Ih)}function $_(l){l>>>=0,ee?postMessage({cmd:"cleanupThread",thread:l}):ym(yn[l])}function k_(l){}var Gp=(l,g)=>{var S=Eh[l];if(S===void 0)throw l=_f(l),S=wn(l),Mn(l),new ai(`${g} has unknown type ${S}`);return S},Wm=(l,g,S)=>{var z=[];return l=l.toWireType(z,S),z.length&&(u()[g>>>2>>>0]=Ur(z)),l};function I_(l,g,S){return g>>>=0,S>>>=0,l=Ir(l>>>0),g=Gp(g,"emval::as"),Wm(g,S,l)}function A_(l,g){return g>>>=0,l=Ir(l>>>0),(g=Gp(g,"emval::as")).toWireType(null,l)}var Kp=l=>{try{l()}catch(g){ii(g)}},ui=0,bn=null,Gm=0,Hp=[],Km={},Hm={},O_=0,Ah=null,F_=[];function qm(l){return function(g){if(!jr){if(ui===0){var S=!1,z=!1;g((Q=0)=>{if(!jr&&(Gm=Q,S=!0,z)){ui=2,Kp(()=>Pf(bn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),Q=!1;try{var ye=function(){var wt=o()[bn+8>>>2>>>0];return wt=jt[Hm[wt]],--Gi,wt()}()}catch(wt){ye=wt,Q=!0}var Ye=!1;if(!bn){var nt=Ah;nt&&(Ah=null,(Q?nt.reject:nt.resolve)(ye),Ye=!0)}if(Q&&!Ye)throw ye}}),z=!0,S||(ui=1,bn=function(){var Q=Zp(65548),ye=Q+12;u()[Q>>>2>>>0]=ye,u()[Q+4>>>2>>>0]=ye+65536,ye=Hp[0];var Ye=Km[ye];return Ye===void 0&&(Ye=O_++,Km[ye]=Ye,Hm[Ye]=ye),ye=Ye,o()[Q+8>>>2>>>0]=ye,Q}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Kp(()=>xf(bn)))}else ui===2?(ui=0,Kp(Ef),Mn(bn),bn=null,F_.forEach(Vm)):ii(`invalid state: ${ui}`);return Gm}}(g=>{l().then(g)})}function D_(l){return l>>>=0,qm(()=>(l=Ir(l)).then(Ur))}var qp=[];function L_(l,g,S,z){return S>>>=0,z>>>=0,(l=qp[l>>>0])(null,g=Ir(g>>>0),S,z)}var z_={},Qp=l=>{var g=z_[l];return g===void 0?wn(l):g};function B_(l,g,S,z,Q){return S>>>=0,z>>>=0,Q>>>=0,(l=qp[l>>>0])(g=Ir(g>>>0),g[S=Qp(S)],z,Q)}var Qm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function R_(l){return(l>>>=0)==0?Ur(Qm()):(l=Qp(l),Ur(Qm()[l]))}var N_=l=>{var g=qp.length;return qp.push(l),g},j_=(l,g)=>{for(var S=Array(l),z=0;z>>2>>>0],"parameter "+z);return S},Xm=(l,g)=>Object.defineProperty(g,"name",{value:l});function U_(l,g,S){var z=(g=j_(l,g>>>0)).shift();l--;var Q=`return function (obj, func, destructorsRef, args) { +`,ye=0,Ye=[];S===0&&Ye.push("obj");for(var nt=["retType"],wt=[z],Ct=0;CtVt.name).join(", ")}) => ${z.name}>`,N_(Xm(S,l))}function V_(l){return l=Qp(l>>>0),Ur(d[l])}function W_(l,g){return g>>>=0,l=Ir(l>>>0),g=Ir(g),Ur(l[g])}function G_(l){9<(l>>>=0)&&(Ln[l+1]+=1)}function K_(){return Ur([])}function H_(l){l=Ir(l>>>0);for(var g=Array(l.length),S=0;S>>0))}function Q_(){return Ur({})}function X_(l){for(var g=Ir(l>>>=0);g.length;){var S=g.pop();g.pop()(S)}Sh(l)}function Y_(l,g,S){g>>>=0,S>>>=0,l=Ir(l>>>0),g=Ir(g),S=Ir(S),l[g]=S}function J_(l,g){return g>>>=0,l=(l=Gp(l>>>0,"_emval_take_value")).readValueFromPointer(g),Ur(l)}function Z_(l,g){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[g>>>2>>>0]=l.getUTCSeconds(),o()[g+4>>>2>>>0]=l.getUTCMinutes(),o()[g+8>>>2>>>0]=l.getUTCHours(),o()[g+12>>>2>>>0]=l.getUTCDate(),o()[g+16>>>2>>>0]=l.getUTCMonth(),o()[g+20>>>2>>>0]=l.getUTCFullYear()-1900,o()[g+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[g+28>>>2>>>0]=l}var Va=l=>l%4==0&&(l%100!=0||l%400==0),Ym=[0,31,60,91,121,152,182,213,244,274,305,335],Jm=[0,31,59,90,120,151,181,212,243,273,304,334];function eg(l,g){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[g>>>2>>>0]=l.getSeconds(),o()[g+4>>>2>>>0]=l.getMinutes(),o()[g+8>>>2>>>0]=l.getHours(),o()[g+12>>>2>>>0]=l.getDate(),o()[g+16>>>2>>>0]=l.getMonth(),o()[g+20>>>2>>>0]=l.getFullYear()-1900,o()[g+24>>>2>>>0]=l.getDay();var S=(Va(l.getFullYear())?Ym:Jm)[l.getMonth()]+l.getDate()-1|0;o()[g+28>>>2>>>0]=S,o()[g+36>>>2>>>0]=-60*l.getTimezoneOffset(),S=new Date(l.getFullYear(),6,1).getTimezoneOffset();var z=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(S!=z&&l.getTimezoneOffset()==Math.min(z,S)),o()[g+32>>>2>>>0]=l}function tg(l){l>>>=0;var g=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),S=o()[l+32>>>2>>>0],z=g.getTimezoneOffset(),Q=new Date(g.getFullYear(),6,1).getTimezoneOffset(),ye=new Date(g.getFullYear(),0,1).getTimezoneOffset(),Ye=Math.min(ye,Q);return 0>S?o()[l+32>>>2>>>0]=+(Q!=ye&&Ye==z):0>>2>>>0]=g.getDay(),S=(Va(g.getFullYear())?Ym:Jm)[g.getMonth()]+g.getDate()-1|0,o()[l+28>>>2>>>0]=S,o()[l>>>2>>>0]=g.getSeconds(),o()[l+4>>>2>>>0]=g.getMinutes(),o()[l+8>>>2>>>0]=g.getHours(),o()[l+12>>>2>>>0]=g.getDate(),o()[l+16>>>2>>>0]=g.getMonth(),o()[l+20>>>2>>>0]=g.getYear(),l=g.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function Zm(l,g,S,z,Q,ye,Ye){return ee?Ns(16,1,l,g,S,z,Q,ye,Ye):-52}function ef(l,g,S,z,Q,ye){if(ee)return Ns(17,1,l,g,S,z,Q,ye)}function sg(l,g,S,z){l>>>=0,g>>>=0,S>>>=0,z>>>=0;var Q=new Date().getFullYear(),ye=new Date(Q,0,1),Ye=new Date(Q,6,1);Q=ye.getTimezoneOffset();var nt=Ye.getTimezoneOffset(),wt=Math.max(Q,nt);u()[l>>>2>>>0]=60*wt,o()[g>>>2>>>0]=+(Q!=nt),ye=(l=Ct=>Ct.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ye),Ye=l(Ye),nt{Oh.length=0;for(var S;S=n()[l++>>>0];){var z=S!=105;g+=(z&=S!=112)&&g%8?4:0,Oh.push(S==112?u()[g>>>2>>>0]:S==106?Qs[g>>>3]:S==105?o()[g>>>2>>>0]:f()[g>>>3>>>0]),g+=z?8:4}return Oh};function rg(l,g,S){return l>>>=0,g=tf(g>>>0,S>>>0),wh[l](...g)}function ng(l,g,S){return l>>>=0,g=tf(g>>>0,S>>>0),wh[l](...g)}var ig=()=>{},og=()=>Date.now();function ag(l,g){return Bt(Xs(l>>>0,g>>>0))}var sf,lg=()=>{throw Gi+=1,"unwind"};function ug(){return 4294901760}sf=()=>performance.timeOrigin+performance.now();var dg=()=>navigator.hardwareConcurrency;function cg(){return ii("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function pg(l){l>>>=0;var g=n().length;if(l<=g||4294901760=S;S*=2){var z=g*(1+.2/S);z=Math.min(z,l+100663296);var Q=Math;z=Math.max(l,z);e:{Q=(Q.min.call(Q,4294901760,z+(65536-z%65536)%65536)-yt.buffer.byteLength+65535)/65536;try{yt.grow(Q),Ss();var ye=1;break e}catch{}ye=void 0}if(ye)return!0}return!1}var Xp=()=>(ii("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Wc={},rf=l=>{l.forEach(g=>{Xp()})};function hg(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),rf(l),Wc.Qb=Xp(),Wc.fc=l,Wc.Qb}function mg(l,g,S){if(l>>>=0,g>>>=0,Wc.Qb==l)var z=Wc.fc;else(z=Error().stack.toString().split(` +`))[0]=="Error"&&z.shift(),rf(z);for(var Q=3;z[Q]&&Xp()!=l;)++Q;for(l=0;l>>2>>>0]=Xp();return l}var Fh,Dh={},nf=()=>{if(!Fh){var l,g={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",_:"./this.program"};for(l in Dh)Dh[l]===void 0?delete g[l]:g[l]=Dh[l];var S=[];for(l in g)S.push(`${l}=${g[l]}`);Fh=S}return Fh};function of(l,g){if(ee)return Ns(18,1,l,g);l>>>=0,g>>>=0;var S=0;return nf().forEach((z,Q)=>{var ye=g+S;for(Q=u()[l+4*Q>>>2>>>0]=ye,ye=0;ye>>0]=z.charCodeAt(ye);r()[Q>>>0]=0,S+=z.length+1}),0}function af(l,g){if(ee)return Ns(19,1,l,g);l>>>=0,g>>>=0;var S=nf();u()[l>>>2>>>0]=S.length;var z=0;return S.forEach(Q=>z+=Q.length+1),u()[g>>>2>>>0]=z,0}function lf(l){return ee?Ns(20,1,l):52}function uf(l,g,S,z){return ee?Ns(21,1,l,g,S,z):52}function df(l,g,S,z){return ee?Ns(22,1,l,g,S,z):70}var fg=[null,[],[]];function cf(l,g,S,z){if(ee)return Ns(23,1,l,g,S,z);g>>>=0,S>>>=0,z>>>=0;for(var Q=0,ye=0;ye>>2>>>0],nt=u()[g+4>>>2>>>0];g+=8;for(var wt=0;wt>>0],Vt=fg[l];Ct===0||Ct===10?((l===1?qt:Bt)(Pm(Vt,0)),Vt.length=0):Vt.push(Ct)}Q+=nt}return u()[z>>>2>>>0]=Q,0}var pf=[31,29,31,30,31,30,31,31,30,31,30,31],hf=[31,28,31,30,31,30,31,31,30,31,30,31],_g=(l,g)=>{r().set(l,g>>>0)};function mf(l,g,S,z){function Q(He,ls,Us){for(He=typeof He=="number"?He.toString():He||"";He.lengthSf?-1:0Hi-He.getDate())){He.setDate(He.getDate()+ls);break}ls-=Hi-He.getDate()+1,He.setDate(1),11>Us?He.setMonth(Us+1):(He.setMonth(0),He.setFullYear(He.getFullYear()+1))}return Us=new Date(He.getFullYear()+1,0,4),ls=nt(new Date(He.getFullYear(),0,4)),Us=nt(Us),0>=Ye(ls,He)?0>=Ye(Us,He)?He.getFullYear()+1:He.getFullYear():He.getFullYear()-1}l>>>=0,g>>>=0,S>>>=0,z>>>=0;var Ct=u()[z+40>>>2>>>0];for(var Vt in z={lc:o()[z>>>2>>>0],kc:o()[z+4>>>2>>>0],Ib:o()[z+8>>>2>>>0],Mb:o()[z+12>>>2>>>0],Jb:o()[z+16>>>2>>>0],Db:o()[z+20>>>2>>>0],vb:o()[z+24>>>2>>>0],Cb:o()[z+28>>>2>>>0],sc:o()[z+32>>>2>>>0],jc:o()[z+36>>>2>>>0],mc:Ct?Xs(Ct):""},S=Xs(S),Ct={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})S=S.replace(new RegExp(Vt,"g"),Ct[Vt]);var ms="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),xs="January February March April May June July August September October November December".split(" ");for(Vt in Ct={"%a":He=>ms[He.vb].substring(0,3),"%A":He=>ms[He.vb],"%b":He=>xs[He.Jb].substring(0,3),"%B":He=>xs[He.Jb],"%C":He=>ye((He.Db+1900)/100|0,2),"%d":He=>ye(He.Mb,2),"%e":He=>Q(He.Mb,2," "),"%g":He=>wt(He).toString().substring(2),"%G":wt,"%H":He=>ye(He.Ib,2),"%I":He=>((He=He.Ib)==0?He=12:12{for(var ls=0,Us=0;Us<=He.Jb-1;ls+=(Va(He.Db+1900)?pf:hf)[Us++]);return ye(He.Mb+ls,3)},"%m":He=>ye(He.Jb+1,2),"%M":He=>ye(He.kc,2),"%n":()=>` +`,"%p":He=>0<=He.Ib&&12>He.Ib?"AM":"PM","%S":He=>ye(He.lc,2),"%t":()=>" ","%u":He=>He.vb||7,"%U":He=>ye(Math.floor((He.Cb+7-He.vb)/7),2),"%V":He=>{var ls=Math.floor((He.Cb+7-(He.vb+6)%7)/7);if(2>=(He.vb+371-He.Cb-2)%7&&ls++,ls)ls==53&&((Us=(He.vb+371-He.Cb)%7)==4||Us==3&&Va(He.Db)||(ls=1));else{ls=52;var Us=(He.vb+7-He.Cb-1)%7;(Us==4||Us==5&&Va(He.Db%400-1))&&ls++}return ye(ls,2)},"%w":He=>He.vb,"%W":He=>ye(Math.floor((He.Cb+7-(He.vb+6)%7)/7),2),"%y":He=>(He.Db+1900).toString().substring(2),"%Y":He=>He.Db+1900,"%z":He=>{var ls=0<=(He=He.jc);return He=Math.abs(He)/60,(ls?"+":"-")+("0000"+(He/60*100+He%60)).slice(-4)},"%Z":He=>He.mc,"%%":()=>"%"},S=S.replace(/%%/g,"\0\0"),Ct)S.includes(Vt)&&(S=S.replace(new RegExp(Vt,"g"),Ct[Vt](z)));return Vt=function(He){var ls=Array(Th(He)+1);return Sm(He,ls,0,ls.length),ls}(S=S.replace(/\0\0/g,"%")),Vt.length>g?0:(_g(Vt,l),Vt.length-1)}function gg(l,g,S,z){return mf(l>>>0,g>>>0,S>>>0,z>>>0)}ee||function(){for(var l=d.numThreads-1;l--;)Mm();sr.unshift(()=>{Wi++,function(g){ee?g():Promise.all(oi.map(bm)).then(g)}(()=>um())})}();for(var ff=Array(256),Yp=0;256>Yp;++Yp)ff[Yp]=String.fromCharCode(Yp);Nm=ff,ai=d.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},d.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},Ln.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>Ln.length/2-5-Ch.length;var yg=[vh,_m,vm,Em,Cm,$m,km,Im,Am,Om,Fm,Dm,Lm,zm,Bm,Rm,Zm,ef,of,af,lf,uf,df,cf],jt=function(){function l(S,z){return jt=S.exports,jt=function(){var Q=jt,ye={};for(let[Ye,nt]of Object.entries(Q))ye[Ye]=typeof nt=="function"?(...wt)=>{Hp.push(Ye);try{return nt(...wt)}finally{jr||(Hp.pop(),bn&&ui===1&&Hp.length===0&&(ui=0,Gi+=1,Kp(Tf),typeof Fibers<"u"&&Fibers.tc()))}}:nt;return ye}(),jt=function(){var Q=jt,ye=nt=>wt=>nt(wt)>>>0,Ye=nt=>()=>nt()>>>0;return(Q=Object.assign({},Q)).Da=ye(Q.Da),Q.gb=Ye(Q.gb),Q.ib=ye(Q.ib),Q.emscripten_main_runtime_thread_id=Ye(Q.emscripten_main_runtime_thread_id),Q.tb=ye(Q.tb),Q.ub=Ye(Q.ub),Q}(),gm.push(jt.jb),Fn.unshift(jt.Ca),Ht=z,um(),jt}var g=mm();if(Wi++,d.instantiateWasm)try{return d.instantiateWasm(g,l)}catch(S){Bt(`Module.instantiateWasm callback failed with error: ${S}`),k(S)}return yh||(yh=d.locateFile?dm("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",Le):Le+"ort-wasm-simd-threaded.jsep.wasm":new URL(s("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),s.b).href),function(S,z){var Q=yh;return et||typeof WebAssembly.instantiateStreaming!="function"||dm(Q)||cm(Q)||typeof fetch!="function"?hm(Q,S,z):fetch(Q,{credentials:"same-origin"}).then(ye=>WebAssembly.instantiateStreaming(ye,S).then(z,function(Ye){return Bt(`wasm streaming compile failed: ${Ye}`),Bt("falling back to ArrayBuffer instantiation"),hm(Q,S,z)}))}(g,function(S){l(S.instance,S.module)}).catch(k),{}}(),_f=l=>(_f=jt.Da)(l),gf=()=>(gf=jt.Ea)();d._OrtInit=(l,g)=>(d._OrtInit=jt.Fa)(l,g),d._OrtGetLastError=(l,g)=>(d._OrtGetLastError=jt.Ga)(l,g),d._OrtCreateSessionOptions=(l,g,S,z,Q,ye,Ye,nt,wt,Ct)=>(d._OrtCreateSessionOptions=jt.Ha)(l,g,S,z,Q,ye,Ye,nt,wt,Ct),d._OrtAppendExecutionProvider=(l,g)=>(d._OrtAppendExecutionProvider=jt.Ia)(l,g),d._OrtAddFreeDimensionOverride=(l,g,S)=>(d._OrtAddFreeDimensionOverride=jt.Ja)(l,g,S),d._OrtAddSessionConfigEntry=(l,g,S)=>(d._OrtAddSessionConfigEntry=jt.Ka)(l,g,S),d._OrtReleaseSessionOptions=l=>(d._OrtReleaseSessionOptions=jt.La)(l),d._OrtCreateSession=(l,g,S)=>(d._OrtCreateSession=jt.Ma)(l,g,S),d._OrtReleaseSession=l=>(d._OrtReleaseSession=jt.Na)(l),d._OrtGetInputOutputCount=(l,g,S)=>(d._OrtGetInputOutputCount=jt.Oa)(l,g,S),d._OrtGetInputName=(l,g)=>(d._OrtGetInputName=jt.Pa)(l,g),d._OrtGetOutputName=(l,g)=>(d._OrtGetOutputName=jt.Qa)(l,g),d._OrtFree=l=>(d._OrtFree=jt.Ra)(l),d._OrtCreateTensor=(l,g,S,z,Q,ye)=>(d._OrtCreateTensor=jt.Sa)(l,g,S,z,Q,ye),d._OrtGetTensorData=(l,g,S,z,Q)=>(d._OrtGetTensorData=jt.Ta)(l,g,S,z,Q),d._OrtReleaseTensor=l=>(d._OrtReleaseTensor=jt.Ua)(l),d._OrtCreateRunOptions=(l,g,S,z)=>(d._OrtCreateRunOptions=jt.Va)(l,g,S,z),d._OrtAddRunConfigEntry=(l,g,S)=>(d._OrtAddRunConfigEntry=jt.Wa)(l,g,S),d._OrtReleaseRunOptions=l=>(d._OrtReleaseRunOptions=jt.Xa)(l),d._OrtCreateBinding=l=>(d._OrtCreateBinding=jt.Ya)(l),d._OrtBindInput=(l,g,S)=>(d._OrtBindInput=jt.Za)(l,g,S),d._OrtBindOutput=(l,g,S,z)=>(d._OrtBindOutput=jt._a)(l,g,S,z),d._OrtClearBoundOutputs=l=>(d._OrtClearBoundOutputs=jt.$a)(l),d._OrtReleaseBinding=l=>(d._OrtReleaseBinding=jt.ab)(l),d._OrtRunWithBinding=(l,g,S,z,Q)=>(d._OrtRunWithBinding=jt.bb)(l,g,S,z,Q),d._OrtRun=(l,g,S,z,Q,ye,Ye,nt)=>(d._OrtRun=jt.cb)(l,g,S,z,Q,ye,Ye,nt),d._OrtEndProfiling=l=>(d._OrtEndProfiling=jt.db)(l),d._JsepOutput=(l,g,S)=>(d._JsepOutput=jt.eb)(l,g,S),d._JsepGetNodeName=l=>(d._JsepGetNodeName=jt.fb)(l);var Jp,Wa=()=>(Wa=jt.gb)(),Mn=d._free=l=>(Mn=d._free=jt.hb)(l),Zp=d._malloc=l=>(Zp=d._malloc=jt.ib)(l),Lh=(l,g,S,z,Q,ye)=>(Lh=jt.lb)(l,g,S,z,Q,ye),yf=()=>(yf=jt.mb)(),wf=(l,g,S,z,Q)=>(wf=jt.nb)(l,g,S,z,Q),zh=l=>(zh=jt.ob)(l),eh=l=>(eh=jt.pb)(l),bf=()=>(bf=jt.qb)(),Mf=(l,g)=>(Mf=jt.rb)(l,g),th=l=>(th=jt.sb)(l),Bh=l=>(Bh=jt.tb)(l),Rh=()=>(Rh=jt.ub)(),vf=d.dynCall_ii=(l,g)=>(vf=d.dynCall_ii=jt.wb)(l,g),xf=l=>(xf=jt.xb)(l),Tf=()=>(Tf=jt.yb)(),Pf=l=>(Pf=jt.zb)(l),Ef=()=>(Ef=jt.Ab)();function Cf(){0Rh(),d.stackRestore=l=>th(l),d.stackAlloc=l=>Bh(l),d.setValue=function(l,g,S="i8"){switch(S.endsWith("*")&&(S="*"),S){case"i1":case"i8":r()[l>>>0]=g;break;case"i16":i()[l>>>1>>>0]=g;break;case"i32":o()[l>>>2>>>0]=g;break;case"i64":Qs[l>>>3]=BigInt(g);break;case"float":m()[l>>>2>>>0]=g;break;case"double":f()[l>>>3>>>0]=g;break;case"*":u()[l>>>2>>>0]=g;break;default:ii(`invalid type for setValue: ${S}`)}},d.getValue=function(l,g="i8"){switch(g.endsWith("*")&&(g="*"),g){case"i1":case"i8":return r()[l>>>0];case"i16":return i()[l>>>1>>>0];case"i32":return o()[l>>>2>>>0];case"i64":return Qs[l>>>3];case"float":return m()[l>>>2>>>0];case"double":return f()[l>>>3>>>0];case"*":return u()[l>>>2>>>0];default:ii(`invalid type for getValue: ${g}`)}},d.UTF8ToString=Xs,d.stringToUTF8=Ua,d.lengthBytesUTF8=Th,Vc=function l(){Jp||Cf(),Jp||(Vc=l)},Cf(),d.PTR_SIZE=4,N}),zs=$s,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&$s()}),Ar,sn,Vs,Cr,Nt,rn,Or,Fr,nn,fr,Vr,Dr,Wr,Gr=_(()=>{qe(),Ar=typeof location>"u"?void 0:location.origin,sn=()=>{var e;return(e=import.meta.url)!=null&&e.startsWith("file:")?new URL(new URL(s("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),s.b).href,Ar).href:import.meta.url},Vs=sn(),Cr=()=>{if(Vs&&!Vs.startsWith("blob:"))return Vs.substring(0,Vs.lastIndexOf("/")+1)},Nt=(e,t)=>{try{let r=t??Vs;return(r?new URL(e,r):new URL(e)).origin===Ar}catch{return!1}},rn=(e,t)=>{let r=t??Vs;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Or=(e,t)=>`${t??"./"}${e}`,Fr=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},nn=async e=>(await import(e)).default,fr=(kt(),b(at)).default,Vr=async()=>{if(!Vs)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nt(Vs))return[void 0,fr()];let e=await Fr(Vs);return[e,fr(e)]},Dr=(ar(),b(is)).default,Wr=async(e,t,r)=>{if(!e&&!t&&Dr&&Vs&&Nt(Vs))return[void 0,Dr];{let n="ort-wasm-simd-threaded.jsep.mjs",i=e??rn(n,t),a=r&&i&&!Nt(i,t),o=a?await Fr(i):i??Or(n,t);return[a?o:void 0,await nn(o)]}}}),cr,it,xt,Ft,Ws,Kr,Lr,vs,pr=_(()=>{Gr(),it=!1,xt=!1,Ft=!1,Ws=()=>{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}},Kr=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Lr=async e=>{if(it)return Promise.resolve();if(xt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ft)throw new Error("previous call to 'initializeWebAssembly()' failed.");xt=!0;let t=e.initTimeout,r=e.numThreads;if(!Kr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ws();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let i=e.wasmPaths,a=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,u=(o==null?void 0:o.href)??o,m=i==null?void 0:i.wasm,f=(m==null?void 0:m.href)??m,$=e.wasmBinary,[k,d]=await Wr(u,a,r>1),N=!1,j=[];if(t>0&&j.push(new Promise(K=>{setTimeout(()=>{N=!0,K()},t)})),j.push(new Promise((K,ee)=>{let te={numThreads:r};if($)te.wasmBinary=$;else if(f||a)te.locateFile=J=>f??a+J;else if(u&&u.indexOf("blob:")!==0)te.locateFile=J=>new URL(J,u).href;else if(k){let J=Cr();J&&(te.locateFile=fe=>J+fe)}d(te).then(J=>{xt=!1,it=!0,cr=J,K(),k&&URL.revokeObjectURL(k)},J=>{xt=!1,Ft=!0,ee(J)})})),await Promise.race(j),N)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},vs=()=>{if(it&&cr)return cr;throw new Error("WebAssembly is not initialized yet.")}}),Fs,Sr,ss,Tn=_(()=>{pr(),Fs=(e,t)=>{let r=vs(),n=r.lengthBytesUTF8(e)+1,i=r._malloc(n);return r.stringToUTF8(e,i,n),t.push(i),i},Sr=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([i,a])=>{let o=t?t+i:i;if(typeof a=="object")Sr(a,o+".",r,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}`)})},ss=e=>{let t=vs(),r=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let a=Number(t.getValue(i,n===4?"i32":"i64")),o=t.getValue(i+n,"*"),u=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}}}),Hr,di=_(()=>{pr(),Tn(),Hr=e=>{let t=vs(),r=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=Fs(e.tag,n)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),r===0&&ss("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Sr(e.extra,"",new WeakSet,(o,u)=>{let m=Fs(o,n),f=Fs(u,n);t._OrtAddRunConfigEntry(r,m,f)!==0&&ss(`Can't set a run config entry: ${o} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(o=>t._free(o)),a}}}),Bn,Rn,Nn,qr,jn,ci=_(()=>{pr(),Tn(),Bn=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}`)}},Rn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Nn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},qr=(e,t,r)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let o=n==null?void 0:n.deviceType;if(o){let u=Fs("deviceType",r),m=Fs(o,r);vs()._OrtAddSessionConfigEntry(e,u,m)!==0&&ss(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let o=n;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let u=Fs("preferredLayout",r),m=Fs(o.preferredLayout,r);vs()._OrtAddSessionConfigEntry(e,u,m)!==0&&ss(`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=Fs(i,r);vs()._OrtAppendExecutionProvider(e,a)!==0&&ss(`Can't append execution provider: ${i}.`)}},jn=e=>{let t=vs(),r=0,n=[],i=e||{};Nn(i);try{let a=Bn(i.graphOptimizationLevel??"all"),o=Rn(i.executionMode??"sequential"),u=typeof i.logId=="string"?Fs(i.logId,n):0,m=i.logSeverityLevel??2;if(!Number.isInteger(m)||m<0||m>4)throw new Error(`log serverity level is not valid: ${m}`);let f=i.logVerbosityLevel??0;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log verbosity level is not valid: ${f}`);let $=typeof i.optimizedModelFilePath=="string"?Fs(i.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,u,m,f,$),r===0&&ss("Can't create session options."),i.executionProviders&&qr(r,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let k=Fs("enableGraphCapture",n),d=Fs(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,k,d)!==0&&ss(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[k,d]of Object.entries(i.freeDimensionOverrides)){if(typeof k!="string")throw new Error(`free dimension override name must be a string: ${k}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let N=Fs(k,n);t._OrtAddFreeDimensionOverride(r,N,d)!==0&&ss(`Can't set a free dimension override: ${k} - ${d}.`)}return i.extra!==void 0&&Sr(i.extra,"",new WeakSet,(k,d)=>{let N=Fs(k,n),j=Fs(d,n);t._OrtAddSessionConfigEntry(r,N,j)!==0&&ss(`Can't set a session config entry: ${k} - ${d}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&ss("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Qr,wr,hr,Pn,on,En,Cn,Sn,Lt=_(()=>{Qr=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}`)}},wr=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}`)}},hr=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((i,a)=>i*a,1);return r>0?Math.ceil(n*r):void 0},Pn=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}`)}},on=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}`)}},En=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Cn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Sn=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}`)}}}),$n,Un=_(()=>{qe(),$n=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let m=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:m,maximum:m}).buffer}else throw u}let o=0;for(;;){let{done:u,value:m}=await i.read();if(u)break;let f=m.byteLength;new Uint8Array(a,o,f).set(m),o+=f}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Vn,Wn,Xr,Gn,kn,Kn,os,Ee=_(()=>{Lt(),Vn=["V","I","W","E","F"],Wn=(e,t)=>{console.log(`[${Vn[e]},${new Date().toISOString()}]${t}`)},kn=(e,t)=>{Xr=e,Gn=t},Kn=(e,t)=>{let r=on(e),n=on(Xr);r>=n&&Wn(r,typeof t=="function"?t():t)},os=(...e)=>{Gn&&Kn(...e)}}),C,Y=_(()=>{Lt(),C=(e,t)=>new(Pn(t))(e)}),de=_(()=>{}),xe,Ie,Xe,ht,gt,ft,Tt,Kt,fs,us=_(()=>{Ee(),de(),xe=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]]),Ie=[],Xe=e=>Math.ceil(Number(e)/16)*16,ht=e=>{for(let t=0;tgt++,Tt=async(e,t,r,n)=>{let i=Xe(r),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let m=n();return m.set(new Uint8Array(u,0,r)),m}else return new Uint8Array(u.slice(0,r))}finally{a.destroy()}},Kt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of xe)Ie.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let r=t.buffer,n=t.byteOffset,i=t.byteLength,a=Xe(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),m=u.getMappedRange();new Uint8Array(m).set(new Uint8Array(r,n,i)),u.unmap();let f=this.backend.device.createCommandEncoder();f.copyBufferToBuffer(u,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([f.finish()]),u.destroy(),os("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=Xe(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[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=ft();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 r=ht(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let u=(i?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let o={id:ft(),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,r=this.storageCache.get(t);if(!r){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return os("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(e,t){let r=this.storageCache.get(Number(e));if(!r)throw new Error("data does not exist");await Tt(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=xe.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(os("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.storageCache=new Map)}},fs=(...e)=>new Kt(...e)}),Ds,zt,rs=_(()=>{Ds=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}},zt=e=>new Ds(e)}),lr,Gs,ze,rr,zr,ks,er,Ot=_(()=>{lr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Gs=class{static calcShape(e,t,r=!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(r){if(n<2||i<2)return;let u=lr.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[o[a-2],o[a-1]]=u}for(let u=r?3:1;u<=a;u++){let m=n-u<0?1:e[n-u],f=i-u<0?1:t[i-u];if(m!==f&&m>1&&f>1)return;let $=Math.max(m,f);if(m&&f)o[a-u]=Math.max(m,f);else{if($>1)return;o[a-u]=0}}return o}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let i=1;i<=r;i++)if(e[r-i]!==1&&e[r-i]!==t[n-i])return!1;return!0}},ze=class nh{static size(t){return nh.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let i=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){i[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");i[a]=1,r/=t[a],a--}for(a--;a>=0;a--)i[a]=t[a];return i}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return nh.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return nh.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let i=1;for(let a=r;a=0;--i)n[i]=n[i+1]*t[i+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((i,a)=>i+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,i)=>n===r[i])}},rr=class qc{static adjustPoolAttributes(t,r,n,i,a,o){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||o[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,i,a,o,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.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 m=0;m{Lt(),Ot(),dr=64,br=(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}`)}},_s=(e,t=1)=>{let r=br(e,t);return typeof r=="string"?r:r[0]},Is=(e,t=1)=>{let r=br(e,t);return typeof r=="string"?r:r[1]},bt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:ze.computeStrides(r)})}),t},Xt=e=>e%4===0?4:e%2===0?2:1,Bs=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,As=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Ks=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,$t=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,an=(e,t,r,n,i)=>{let a=typeof r=="number",o=a?r:r.length,u=[...new Array(o).keys()],m=o<2?"u32":o<=4?`vec${o}`:`array`,f=br(t,i),$=typeof f=="string"?f:f[1],k=typeof f=="string"?f:f[0],d={indices:m,value:$,storage:k,tensor:t},N=ot=>typeof ot=="string"?ot:`${ot}u`,j={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},K=a?"uniforms.":"",ee=`${K}${e}_shape`,te=`${K}${e}_strides`,J="";for(let ot=0;ot ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${J} + return indices; + }`,he=ot=>(j.offsetToIndices=!0,o<2?ot:`o2i_${e}(${ot})`),Me=[];if(o>=2)for(let ot=o-1;ot>=0;ot--)Me.push(`${$t(te,ot,o)} * (indices[${ot}])`);let Ae=o<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${Me.join("+")}; + }`,Le=ot=>(j.indicesToOffset=!0,o<2?ot:`i2o_${e}(${ot})`),et=(...ot)=>o===0?"0u":`${d.indices}(${ot.map(N).join(",")})`,dt=(ot,Et)=>o<2?`${ot}`:`${$t(ot,Et,o)}`,Pt=(ot,Et,hs)=>o<2?`${ot}=${hs};`:`${$t(ot,Et,o)}=${hs};`,qt={},Bt=(ot,Et)=>{j.broadcastedIndicesToOffset=!0;let hs=`${Et.name}broadcastedIndicesTo${e}Offset`;if(hs in qt)return`${hs}(${ot})`;let js=[];for(let Qs=o-1;Qs>=0;Qs--){let Nr=Et.indicesGet("outputIndices",Qs+Et.rank-o);js.push(`${dt(te,Qs)} * (${Nr} % ${dt(ee,Qs)})`)}return qt[hs]=`fn ${hs}(outputIndices: ${Et.type.indices}) -> u32 { + return ${js.length>0?js.join("+"):"0u"}; + }`,`${hs}(${ot})`},At=(ot,Et)=>(()=>{if(d.storage===d.value)return`${e}[${ot}]=${Et};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${ot}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${ot}]=vec2(u32(${Et}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),ts=ot=>(()=>{if(d.storage===d.value)return`${e}[${ot}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${ot}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${ot}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${ot}] & 0xFFu), bool(${e}[${ot}] & 0xFF00u), bool(${e}[${ot}] & 0xFF0000u), bool(${e}[${ot}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),yt=o<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${$} { + return ${ts(`i2o_${e}(indices)`)}; + }`,Ht=o<2?"":(()=>{let ot=u.map(hs=>`d${hs}: u32`).join(", "),Et=u.map(hs=>`d${hs}`).join(", ");return` + fn get_${e}(${ot}) -> ${$} { + return get_${e}ByIndices(${et(Et)}); + }`})(),ps=(...ot)=>{if(ot.length!==o)throw new Error(`indices length must be ${o}`);let Et=ot.map(N).join(",");return o===0?ts("0u"):o===1?ts(Et[0]):(j.get=!0,j.getByIndices=!0,j.indicesToOffset=!0,`get_${e}(${Et})`)},Ut=ot=>o<2?ts(ot):(j.getByIndices=!0,j.indicesToOffset=!0,`get_${e}ByIndices(${ot})`),Qt=o<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${$}) { + ${At(`i2o_${e}(indices)`,"value")} + }`,gs=o<2?"":(()=>{let ot=u.map(hs=>`d${hs}: u32`).join(", "),Et=u.map(hs=>`d${hs}`).join(", ");return` + fn set_${e}(${ot}, value: ${$}) { + set_${e}ByIndices(${et(Et)}, value); + }`})();return{impl:()=>{let ot=[],Et=!1;return j.offsetToIndices&&(ot.push(fe),Et=!0),j.indicesToOffset&&(ot.push(Ae),Et=!0),j.broadcastedIndicesToOffset&&(Object.values(qt).forEach(hs=>ot.push(hs)),Et=!0),j.set&&(ot.push(gs),Et=!0),j.setByIndices&&(ot.push(Qt),Et=!0),j.get&&(ot.push(Ht),Et=!0),j.getByIndices&&(ot.push(yt),Et=!0),!a&&Et&&ot.unshift(`const ${ee} = ${d.indices}(${r.join(",")});`,`const ${te} = ${d.indices}(${ze.computeStrides(r).join(",")});`),ot.join(` +`)},type:d,offsetToIndices:he,indicesToOffset:Le,broadcastedIndicesToOffset:Bt,indices:et,indicesGet:dt,indicesSet:Pt,set:(...ot)=>{if(ot.length!==o+1)throw new Error(`indices length must be ${o}`);let Et=ot[o];if(typeof Et!="string")throw new Error("value must be string");let hs=ot.slice(0,o).map(N).join(",");return o===0?At("0u",Et):o===1?At(hs[0],Et):(j.set=!0,j.setByIndices=!0,j.indicesToOffset=!0,`set_${e}(${hs}, ${Et})`)},setByOffset:At,setByIndices:(ot,Et)=>o<2?At(ot,Et):(j.setByIndices=!0,j.indicesToOffset=!0,`set_${e}ByIndices(${ot}, ${Et});`),get:ps,getByOffset:ts,getByIndices:Ut,usage:n,name:e,strides:te,shape:ee,rank:o}},Qe=(e,t,r,n=1)=>an(e,t,r,"input",n),It=(e,t,r,n=1)=>an(e,t,r,"output",n),Ha=(e,t,r)=>an(e,t,r,"atomicOutput",1),Qi=(e,t,r,n=1)=>an(e,t,r,"internal",n),qa=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=dr){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let 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*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${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 r=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,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?r:`vec${n}<${r}>`;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])}},Qa=(e,t)=>new qa(e,t)}),Xa,Xi,Yi,Ya,Ja,Ji,_r,Za,Zi,Yr=_(()=>{Lt(),Ot(),rs(),Jt(),Xa=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Xi=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Yi=(e,t)=>ze.sortBasedOnPerm(e,Xi(e.length,t)),Ya=(e,t,r,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let i=0;i{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,i=Xi(n,t),a=Yi(e.dims,i),o=e.dims,u=a,m=n<2||Ji(i,e.dims),f;if(m)return f=j=>{let K=Qe("input",r,o,4),ee=It("output",r,u,4);return` + ${j.registerUniform("output_size","u32").declareVariables(K,ee)} + ${j.mainStart()} + ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let j=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(j/64/4)},programUniforms:[{type:12,data:Math.ceil(j/4)}]}},getShaderSource:f};let{newShape:$,newPerm:k}=Ja(e.dims,i),d=ze.areEqual(k,[2,3,1]),N=ze.areEqual(k,[3,1,2]);if($.length===2||d||N){o=d?[$[0],$[1]*$[2]]:N?[$[0]*$[1],$[2]]:$,u=[o[1],o[0]];let j=16;return f=K=>{let ee=Qe("a",r,o.length),te=It("output",r,u.length);return` + ${K.registerUniform("output_size","u32").declareVariables(ee,te)} + var tile : array, ${j}>; + ${K.mainStart([j,j,1])} + let stride = (uniforms.output_shape[1] - 1) / ${j} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${j}u + local_id.x; + let input_row = workgroup_id_x * ${j}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${ee.getByIndices(`${ee.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${j}u + local_id.x; + let output_row = workgroup_id_y * ${j}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${te.setByIndices(`${te.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let K=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/j),y:Math.ceil(u[0]/j)},programUniforms:[{type:12,data:K},...bt(o,u)]}},getShaderSource:f}}return f=j=>{let K=Qe("a",r,o.length),ee=It("output",r,u.length);return` + ${j.registerUniform("output_size","u32").declareVariables(K,ee)} + + ${Ya(i,n,K,ee)} + + ${j.mainStart()} + ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${ee.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${ee.setByOffset("global_idx",K.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let j=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:[{type:12,data:j},...bt(o,u)]}},getShaderSource:f}},Za=(e,t)=>{Xa(e.inputs,t.perm),e.compute(_r(e.inputs[0],t.perm))},Zi=e=>zt({perm:e.perm})}),pi,el,tl,sl,rl,nl,il,ol,eo,al,gr,ln,ll,Jc,ul,Zc,dl,to,cl,pl,hl,ep=_(()=>{Lt(),Ot(),Jt(),fi(),Yr(),pi={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"},el={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"},tl={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},sl={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},rl=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,i]},il=(e,t)=>{let r=e.length+t.length,n=[],i=0;for(let a=0;a{for(let r=0;r{let r=[];if(!ol(e,t)){for(let n=0;nr.push(n))}return r},al=(e,t,r,n,i,a,o)=>{let u=r[0].dims,m=ze.size(a),f=ze.size(o),$=Qe("_A",r[0].dataType,u),k=It("output",i,a),d=64;m===1&&(d=256);let N=` + var aBestValues : array; + `,j=K=>` + ${K.registerUniform("reduceSize","u32").declareVariables($,k)} + ${N} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${K.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${tl[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${$.getByOffset("offset + k")}); + bestValue = ${pi[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${el[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${k.setByOffset("outputIndex",`${n==="mean"?`${k.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${k.type.storage}(${sl[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${d}`,inputDependencies:["type"]},getShaderSource:j,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:m},programUniforms:[{type:12,data:f}]})}},gr=(e,t,r,n)=>{let i=e.inputs.length===1?r:so(e.inputs,r),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((N,j)=>j));let o=ze.normalizeAxes(a,e.inputs[0].dims.length),u=o,m=e.inputs[0],f=eo(u,e.inputs[0].dims.length);f.length>0&&(m=e.compute(_r(e.inputs[0],f),{inputs:[0],outputs:[-1]})[0],u=rl(u.length,m.dims.length));let[$,k]=nl(m.dims,u),d=$;i.keepDims&&(d=il($,o)),e.compute(al(t,i.cacheKey,[m],n,e.inputs[0].dataType,d,k),{inputs:[m]})},ln=(e,t)=>{gr(e,"ReduceMeanShared",t,"mean")},ll=(e,t)=>{gr(e,"ReduceL1Shared",t,"l1")},Jc=(e,t)=>{gr(e,"ReduceL2Shared",t,"l2")},ul=(e,t)=>{gr(e,"ReduceLogSumExpShared",t,"logSumExp")},Zc=(e,t)=>{gr(e,"ReduceMaxShared",t,"max")},dl=(e,t)=>{gr(e,"ReduceMinShared",t,"min")},to=(e,t)=>{gr(e,"ReduceProdShared",t,"prod")},cl=(e,t)=>{gr(e,"ReduceSumShared",t,"sum")},pl=(e,t)=>{gr(e,"ReduceSumSquareShared",t,"sumSquare")},hl=(e,t)=>{gr(e,"ReduceLogSumShared",t,"logSum")}}),Mr,hi,mi,so,vr,ro,ml,fl,no,_l,gl,io,yl,wl,oo,xr,bl,ao,Ml,vl,lo,xl,Tl,uo,Pl,El,fi=_(()=>{Lt(),Ot(),rs(),Jt(),ep(),Mr=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.")},hi=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],mi=(e,t,r,n,i,a,o=!1,u=!1)=>{let m=[],f=r[0].dims,$=f.length,k=ze.normalizeAxes(i,$),d=!u&&k.length===0;f.forEach((K,ee)=>{d||k.indexOf(ee)>=0?o&&m.push(1):m.push(K)});let N=m.length,j=ze.size(m);return{name:e,shaderCache:t,getShaderSource:K=>{let ee=[],te=Qe("_A",r[0].dataType,$),J=It("output",a,N),fe=n(te,J,k),he=fe[2];for(let Me=0,Ae=0;Me<$;Me++)d||k.indexOf(Me)>=0?(o&&Ae++,he=`for(var j${Me}: u32 = 0; j${Me} < ${f[Me]}; j${Me}++) { + ${fe[2].includes("last_index")?`let last_index = j${Me};`:""} + ${te.indicesSet("input_indices",Me,`j${Me}`)} + ${he} + }`):(ee.push(`${te.indicesSet("input_indices",Me,J.indicesGet("output_indices",Ae))};`),Ae++);return` + + ${K.registerUniform("output_size","u32").declareVariables(te,J)} + + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${te.type.indices}; + let output_indices = ${J.offsetToIndices("global_idx")}; + + ${ee.join(` +`)} + ${fe[0]} // init ops for reduce max/min + ${fe[1]} + ${he} + ${fe[3]} + ${fe.length===4?J.setByOffset("global_idx","value"):fe.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:[{type:12,data:j},...bt(f,m)]})}},so=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),zt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},vr=(e,t,r,n)=>{let i=e.inputs,a=i.length===1?r:so(i,r);e.compute(mi(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?hi:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},ro=(e,t)=>{Mr(e.inputs),vr(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},ml=(e,t)=>{Mr(e.inputs),vr(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},fl=(e,t)=>{Mr(e.inputs),vr(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},no=(e,t)=>{Mr(e.inputs),vr(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},_l=(e,t)=>{Mr(e.inputs),vr(e,"ReduceMax",t,(r,n,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(r.indicesSet("input_indices",o,0));return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},gl=(e,t)=>{Mr(e.inputs),vr(e,"ReduceMean",t,(r,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(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},io=(e,t)=>{Mr(e.inputs),vr(e,"ReduceMin",t,(r,n,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(`input_indices[${o}] = 0;`);return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},yl=(e,t)=>{Mr(e.inputs),vr(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},wl=(e,t)=>{Mr(e.inputs),vr(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},oo=(e,t)=>{Mr(e.inputs),vr(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},xr=(e,t,r)=>{if(t.length===0)return r;let n=1,i=1;for(let a=0;a1024},bl=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?gl(e,t):ln(e,t)},ao=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ml(e,t):ll(e,t)},Ml=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?fl(e,t):Jc(e,t)},vl=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?no(e,t):ul(e,t)},lo=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_l(e,t):Zc(e,t)},xl=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?io(e,t):dl(e,t)},Tl=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?yl(e,t):to(e,t)},uo=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wl(e,t):cl(e,t)},Pl=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?oo(e,t):pl(e,t)},El=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):hl(e,t)}}),co,Cl,po,ho,tp=_(()=>{Lt(),rs(),fi(),co=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.")},Cl=(e,t)=>{co(e.inputs);let r=(n,i,a)=>{let o=[];for(let u=0;u=0||a.length===0)&&o.push(`input_indices[${u}] = 0;`);return[`${o.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(mi("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},po=(e,t)=>{co(e.inputs);let r=(n,i,a)=>{let o=[];for(let u=0;u=0||a.length===0)&&o.push(`input_indices[${u}] = 0;`);return[`${o.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(mi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ho=e=>zt(e)}),mo,_i,Sl,fo,$l,Hn,_o,kl,go=_(()=>{Lt(),Ot(),de(),Jt(),mo=(e,t)=>{let r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],u=e[5];if(o&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let m=r.dims[0],f=r.dims[1],$=r.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]!==$)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 k=i.dims[0]/3,d=k,N=d;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let fe of t.qkvHiddenSizes)if(fe%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");k=t.qkvHiddenSizes[0],d=t.qkvHiddenSizes[1],N=t.qkvHiddenSizes[2]}let j=f;if(k!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==k+d+N)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let K=0;if(o){if(d!==N)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]!==m)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==d/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(K=o.dims[3])}let ee=j+K,te=-1,J=0;if(a)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==m||u.dims[1]!==t.numHeads||u.dims[2]!==f||u.dims[3]!==ee)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:f,pastSequenceLength:K,kvSequenceLength:j,totalSequenceLength:ee,maxSequenceLength:te,inputHiddenSize:$,hiddenSize:k,vHiddenSize:N,headSize:Math.floor(k/t.numHeads),vHeadSize:Math.floor(N/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:J,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},_i=(e,t,r)=>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; + } + `:` + ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,Sl=(e,t,r,n,i,a,o,u)=>{let m=Xt(o?1:a),f=64,$=a/m;${let J=It("x",e.dataType,e.dims,m),fe=[J],he=o?Qe("seq_lens",o.dataType,o.dims):void 0;he&&fe.push(he);let Me=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;Me&&fe.push(Me);let Ae=Is(e.dataType),Le=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${te.registerUniforms(Le).declareVariables(...fe)} + ${te.mainStart([f,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; + ${_i(he,Me,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${f}) * 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 = ${j}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${j}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(m){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: ${m}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${f}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${j}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${j}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(m){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: ${m}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${f}; 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] = ${J.type.value}(${Ae}(1.0) / ${Ae}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${j}(x[offset + i]); + x[offset + i] = ${J.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] = ${J.type.value}(${Ae}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${f};${N};${m}`,inputDependencies:K},getShaderSource:ee,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/f),y:i,z:t*r},programUniforms:d})}},fo=(e,t,r,n,i,a,o,u,m)=>{let f=o+a.kvSequenceLength,$=[a.batchSize,a.numHeads,a.sequenceLength,f],k=e>1&&n,d=a.kvNumHeads?a.kvNumHeads:a.numHeads,N=k?[a.batchSize,d,f,a.headSize]:void 0,j=a.nReps?a.nReps:1,K=a.scale===0?1/Math.sqrt(a.headSize):a.scale,ee=Xt(a.headSize),te=a.headSize/ee,J=12,fe={x:Math.ceil(f/J),y:Math.ceil(a.sequenceLength/J),z:a.batchSize*a.numHeads},he=[{type:12,data:a.sequenceLength},{type:12,data:te},{type:12,data:f},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:K},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:j}],Me=k&&n&&ze.size(n.dims)>0,Ae=["type","type"];Me&&Ae.push("type"),i&&Ae.push("type"),u&&Ae.push("type"),m&&Ae.push("type");let Le=[{dims:$,dataType:t.dataType,gpuDataType:0}];k&&Le.push({dims:N,dataType:t.dataType,gpuDataType:0});let et=dt=>{let Pt=Qe("q",t.dataType,t.dims,ee),qt=Qe("key",r.dataType,r.dims,ee),Bt=[Pt,qt];if(Me){let Qt=Qe("past_key",n.dataType,n.dims,ee);Bt.push(Qt)}i&&Bt.push(Qe("attention_bias",i.dataType,i.dims));let At=u?Qe("seq_lens",u.dataType,u.dims):void 0;At&&Bt.push(At);let ts=m?Qe("total_sequence_length_input",m.dataType,m.dims):void 0;ts&&Bt.push(ts);let yt=It("output",t.dataType,$),Ht=[yt];k&&Ht.push(It("present_key",t.dataType,N,ee));let ps=Is(1,ee),Ut=[{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 = ${J}u; + + var tileQ: array<${Pt.type.storage}, ${J*J}>; + var tileK: array<${Pt.type.storage}, ${J*J}>; + ${dt.registerUniforms(Ut).declareVariables(...Bt,...Ht)} + ${dt.mainStart([J,J,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${j===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${j===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; + ${_i(At,ts,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${Me&&k?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${k?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${ps}(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&&k?` + 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]; + }`} + ${k?`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 += ${ps}(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(ee){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: ${ee}`)}})()}; + output[outputIdx] = ${yt.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${ee};${i!==void 0};${n!==void 0};${e}`,inputDependencies:Ae},getRunData:()=>({outputs:Le,dispatchGroup:fe,programUniforms:he}),getShaderSource:et}},$l=(e,t,r,n,i,a,o=void 0,u=void 0)=>{let m=a+i.kvSequenceLength,f=i.nReps?i.nReps:1,$=i.vHiddenSize*f,k=e>1&&n,d=i.kvNumHeads?i.kvNumHeads:i.numHeads,N=k?[i.batchSize,d,m,i.headSize]:void 0,j=[i.batchSize,i.sequenceLength,$],K=12,ee={x:Math.ceil(i.vHeadSize/K),y:Math.ceil(i.sequenceLength/K),z:i.batchSize*i.numHeads},te=[{type:12,data:i.sequenceLength},{type:12,data:m},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:$},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:f}],J=k&&n&&ze.size(n.dims)>0,fe=["type","type"];J&&fe.push("type"),o&&fe.push("type"),u&&fe.push("type");let he=[{dims:j,dataType:t.dataType,gpuDataType:0}];k&&he.push({dims:N,dataType:t.dataType,gpuDataType:0});let Me=Ae=>{let Le=Qe("probs",t.dataType,t.dims),et=Qe("v",r.dataType,r.dims),dt=[Le,et];J&&dt.push(Qe("past_value",n.dataType,n.dims));let Pt=o?Qe("seq_lens",o.dataType,o.dims):void 0;o&&dt.push(Pt);let qt=u?Qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&dt.push(qt);let Bt=[It("output",t.dataType,j)];k&&Bt.push(It("present_value",t.dataType,N));let At=[{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 = ${K}u; + var tileQ: array<${Le.type.value}, ${K*K}>; + var tileV: array<${Le.type.value}, ${K*K}>; + ${Ae.registerUniforms(At).declareVariables(...dt,...Bt)} + ${Ae.mainStart([K,K,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${f===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; + ${_i(Pt,qt,!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 + ${J&&k?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${k?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${Le.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${J&&k?` + 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]; + }`} + ${k?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:fe},getRunData:()=>({outputs:he,dispatchGroup:ee,programUniforms:te}),getShaderSource:Me}},Hn=(e,t,r,n,i,a,o,u,m,f,$=void 0,k=void 0)=>{let d=Math.min(e.outputCount,1+(o?1:0)+(u?1:0)),N=d>1?f.pastSequenceLength:0,j=N+f.kvSequenceLength,K=m&&ze.size(m.dims)>0?m:void 0,ee=[t,r];d>1&&o&&ze.size(o.dims)>0&&ee.push(o),K&&ee.push(K),$&&ee.push($),k&&ee.push(k);let te=e.compute(fo(d,t,r,o,K,f,N,$,k),{inputs:ee,outputs:d>1?[-1,1]:[-1]})[0];e.compute(Sl(te,f.batchSize,f.numHeads,N,f.sequenceLength,j,$,k),{inputs:$&&k?[te,$,k]:[te],outputs:[]});let J=[te,n];d>1&&u&&ze.size(u.dims)>0&&J.push(u),$&&J.push($),k&&J.push(k),e.compute($l(d,te,n,u,f,N,$,k),{inputs:J,outputs:d>1?[0,2]:[0]})},_o=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o=12,u={x:Math.ceil(t.headSize/o),y:Math.ceil(t.sequenceLength/o),z:t.batchSize*t.numHeads},m=[e.inputs[0],e.inputs[1],e.inputs[2]],f=[{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=>{let d=It("output_q",m[0].dataType,r),N=It("output_k",m[0].dataType,r),j=It("output_v",m[0].dataType,r),K=Qe("input",m[0].dataType,m[0].dims),ee=Qe("weight",m[1].dataType,m[1].dims),te=Qe("bias",m[2].dataType,m[2].dims),J=K.type.storage,fe=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${o}u; + var tileInput: array<${J}, ${o*o}>; + var tileWeightQ: array<${J}, ${o*o}>; + var tileWeightK: array<${J}, ${o*o}>; + var tileWeightV: array<${J}, ${o*o}>; + ${k.registerUniforms(fe).declareVariables(K,ee,te,d,N,j)} + ${k.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 = ${J}(0); + var valueK = ${J}(0); + var valueV = ${J}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:f}),getShaderSource:$},{inputs:m,outputs:[-1,-1,-1]})},kl=(e,t)=>{let r=mo(e.inputs,t),[n,i,a]=_o(e,r);return Hn(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),yo,Il,Al,wo,sp=_(()=>{Re(),Lt(),Ot(),rs(),Jt(),yo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,i,a)=>{let o=i.length;if(o!==n.length)throw new Error(`${a}: num dimensions != ${o}`);i.forEach((u,m)=>{if(u!==n[m])throw new Error(`${a}: dim[${m}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Il=(e,t)=>{let{epsilon:r,spatial:n,format:i}=t,a=e[0].dims,o=n?Xt(a[a.length-1]):1,u=i==="NHWC"&&a.length>1?o:1,m=ze.size(a)/o,f=n,$=f?a.length:a,k=Qe("x",e[0].dataType,e[0].dims,o),d=Qe("scale",e[1].dataType,e[1].dims,u),N=Qe("bias",e[2].dataType,e[2].dims,u),j=Qe("inputMean",e[3].dataType,e[3].dims,u),K=Qe("inputVar",e[4].dataType,e[4].dims,u),ee=It("y",e[0].dataType,$,o),te=()=>{let fe="";if(n)fe=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")fe=` + ${ee.indicesSet("outputIndices","0","0")} + let cOffset = ${ee.indicesToOffset("outputIndices")};`;else{fe=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let he=1;he` + const epsilon = ${r}; + ${fe.registerUniform("outputSize","u32").declareVariables(k,d,N,j,K,ee)} + ${fe.mainStart()} + ${fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${ee.offsetToIndices(`global_idx * ${o}`)}; + ${te()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${N.getByOffset("cOffset")}; + let inputMean = ${j.getByOffset("cOffset")}; + let inputVar = ${K.getByOffset("cOffset")}; + let x = ${k.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${ee.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${o}`,inputDependencies:f?["rank","type","type","type","type"]:void 0},getShaderSource:J,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:f?[{type:12,data:m},...bt(a)]:[{type:12,data:m}]})}},Al=e=>zt(e),wo=(e,t)=>{let{inputs:r,outputCount:n}=e,i=Al({...t,outputCount:n});if(L.webgpu.validateInputContent&&yo(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Il(r,i))}}),Ol,bo,Fl,rp=_(()=>{Ot(),Jt(),Ol=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")},bo=e=>{let t=e[0].dims,r=e[0].dims[2],n=ze.size(t)/4,i=e[0].dataType,a=Qe("input",i,t,4),o=Qe("bias",i,[r],4),u=Qe("residual",i,t,4),m=It("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:f=>` + const channels = ${r}u / 4; + ${f.declareVariables(a,o,u,m)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${o.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${m.setByOffset("global_idx","value")} + }`}},Fl=e=>{Ol(e.inputs),e.compute(bo(e.inputs))}}),Mo,ds,Dl,vo,Ll,zl,xo,Bl,Rl,To,Nl,jl,Po,Ul,Vl,Eo,qn,Wl,gi,Gl,Co,Kl,Hl,So,ql,Ql,$o,Xl,Yl,ko,Jl,Zl,Io,eu,tu,yi,su,Ao,wi,ru,nu,iu,ou,Oo,au,Fo=_(()=>{Lt(),Ot(),rs(),Jt(),Mo=(e,t,r,n,i,a,o)=>{let u=Math.ceil(t/4),m="";typeof i=="string"?m=`${i}(a)`:m=i("a");let f=Qe("inputData",r,[u],4),$=It("outputData",n,[u],4),k=[{name:"vec_size",type:"u32"}];return o&&k.push(...o),` + ${e.registerUniforms(k).declareVariables(f,$)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${f.getByOffset("global_idx")}; + ${$.setByOffset("global_idx",m)} + }`},ds=(e,t,r,n,i,a=e.dataType,o,u)=>{let m=[{type:12,data:Math.ceil(ze.size(e.dims)/4)}];return o&&m.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:f=>Mo(f,ze.size(e.dims),e.dataType,a,r,n,u),getRunData:f=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(ze.size(f[0].dims)/64/4)},programUniforms:m})}},Dl=e=>{e.compute(ds(e.inputs[0],"Abs","abs"))},vo=e=>{e.compute(ds(e.inputs[0],"Acos","acos"))},Ll=e=>{e.compute(ds(e.inputs[0],"Acosh","acosh"))},zl=e=>{e.compute(ds(e.inputs[0],"Asin","asin"))},xo=e=>{e.compute(ds(e.inputs[0],"Asinh","asinh"))},Bl=e=>{e.compute(ds(e.inputs[0],"Atan","atan"))},Rl=e=>{e.compute(ds(e.inputs[0],"Atanh","atanh"))},To=e=>zt(e),Nl=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ds(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},jl=e=>{let t,r,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,r=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return zt({min:t,max:r})},Po=(e,t)=>{let r=t||jl(e.inputs),n=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Ul=e=>{e.compute(ds(e.inputs[0],"Ceil","ceil"))},Vl=e=>{e.compute(ds(e.inputs[0],"Cos","cos"))},Eo=e=>{e.compute(ds(e.inputs[0],"Cosh","cosh"))},qn=e=>zt(e),Wl=(e,t)=>{let r=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${r}(${t.alpha}); + + fn elu_f32(a: ${r}) -> ${r} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},gi=(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)); +}`,Gl=e=>{let t=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,gi(t)))},Co=e=>{e.compute(ds(e.inputs[0],"Exp","exp"))},Kl=e=>{e.compute(ds(e.inputs[0],"Floor","floor"))},Hl=e=>{let t=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,gi(t)))},So=(e,t)=>{let r=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},ql=e=>{e.compute(ds(e.inputs[0],"Not",t=>`!${t}`))},Ql=e=>{e.compute(ds(e.inputs[0],"Neg",t=>`-${t}`))},$o=e=>{e.compute(ds(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Xl=e=>{let t=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Yl=e=>{e.compute(ds(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ko=e=>zt(e),Jl=(e,t)=>{let r=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Zl=e=>{e.compute(ds(e.inputs[0],"Sin","sin"))},Io=e=>{e.compute(ds(e.inputs[0],"Sinh","sinh"))},eu=e=>{e.compute(ds(e.inputs[0],"Sqrt","sqrt"))},tu=e=>{e.compute(ds(e.inputs[0],"Tan","tan"))},yi=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,su=e=>{e.compute(ds(e.inputs[0],"Tanh",yi))},Ao=(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 ${yi("v")}; +} +`,wi=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,ru=e=>{let t=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"FastGelu",wi,Ao(t),void 0,e.inputs[0].dataType))},nu=(e,t)=>{let r=Is(e.inputs[0].dataType);return e.compute(ds(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},iu=e=>{e.compute(ds(e.inputs[0],"Log","log"))},ou=(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; +} +`,Oo=e=>`quick_gelu_impl(${e})`,au=(e,t)=>{let r=Is(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"QuickGelu",Oo,ou(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),lu,uu,Do,np=_(()=>{Ot(),Jt(),Fo(),lu=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")},uu=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Qe("input",e[0].dataType,e[0].dims,4),n=Qe("bias",e[0].dataType,[e[0].dims[2]],4),i=It("output",e[0].dataType,t,4),a=ze.size(t)/4,o=_s(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(r,n,i)} + + ${gi(o)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Do=e=>{lu(e.inputs),e.compute(uu(e.inputs))}}),du,cu,Tr,Lo,pu,hu,mu,fu,zo,_u,gu,Bo,yu,ip=_(()=>{Lt(),Ot(),Jt(),du=(e,t,r,n,i,a,o,u,m,f,$,k)=>{let d,N;typeof u=="string"?d=N=(J,fe)=>`${u}((${J}),(${fe}))`:typeof u=="function"?d=N=u:(d=u.scalar,N=u.vector);let j=It("outputData",$,n.length,4),K=Qe("aData",m,t.length,4),ee=Qe("bData",f,r.length,4),te;if(i)if(a){let J=ze.size(t)===1,fe=ze.size(r)===1,he=t.length>0&&t[t.length-1]%4===0,Me=r.length>0&&r[r.length-1]%4===0;J||fe?te=j.setByOffset("global_idx",N(J?`${K.type.value}(${K.getByOffset("0")}.x)`:K.getByOffset("global_idx"),fe?`${ee.type.value}(${ee.getByOffset("0")}.x)`:ee.getByOffset("global_idx"))):te=` + let outputIndices = ${j.offsetToIndices("global_idx * 4u")}; + let offsetA = ${K.broadcastedIndicesToOffset("outputIndices",j)}; + let offsetB = ${ee.broadcastedIndicesToOffset("outputIndices",j)}; + ${j.setByOffset("global_idx",N(o||he?K.getByOffset("offsetA / 4u"):`${K.type.value}(${K.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||Me?ee.getByOffset("offsetB / 4u"):`${ee.type.value}(${ee.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else te=j.setByOffset("global_idx",N(K.getByOffset("global_idx"),ee.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let J=(fe,he,Me="")=>{let Ae=`aData[indexA${he}][componentA${he}]`,Le=`bData[indexB${he}][componentB${he}]`;return` + let outputIndices${he} = ${j.offsetToIndices(`global_idx * 4u + ${he}u`)}; + let offsetA${he} = ${K.broadcastedIndicesToOffset(`outputIndices${he}`,j)}; + let offsetB${he} = ${ee.broadcastedIndicesToOffset(`outputIndices${he}`,j)}; + let indexA${he} = offsetA${he} / 4u; + let indexB${he} = offsetB${he} / 4u; + let componentA${he} = offsetA${he} % 4u; + let componentB${he} = offsetB${he} % 4u; + ${fe}[${he}] = ${Me}(${d(Ae,Le)}); + `};$===9?te=` + var data = vec4(0); + ${J("data",0,"u32")} + ${J("data",1,"u32")} + ${J("data",2,"u32")} + ${J("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:te=` + ${J("outputData[global_idx]",0)} + ${J("outputData[global_idx]",1)} + ${J("outputData[global_idx]",2)} + ${J("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(K,ee,j)} + + ${k??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${te} + }`},cu=(e,t,r,n,i,a,o=r.dataType)=>{let u=r.dims.map(K=>Number(K)??1),m=n.dims.map(K=>Number(K)??1),f=!ze.areEqual(u,m),$=u,k=ze.size(u),d=!1,N=!1,j=[f];if(f){let K=Gs.calcShape(u,m,!1);if(!K)throw new Error("Can't perform binary op on the given tensors");$=K.slice(),k=ze.size($);let ee=ze.size(u)===1,te=ze.size(m)===1,J=u.length>0&&u[u.length-1]%4===0,fe=m.length>0&&m[m.length-1]%4===0;j.push(ee),j.push(te),j.push(J),j.push(fe);let he=1;for(let Me=1;Me<$.length;Me++){let Ae=u[u.length-Me],Le=m[m.length-Me];if(Ae===Le)he*=Ae;else break}he%4===0?(N=!0,d=!0):(ee||te||J||fe)&&(d=!0)}else d=!0;return j.push(d),{name:e,shaderCache:{hint:t+j.map(K=>K.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:K=>du(K,u,m,$,d,f,N,i,r.dataType,n.dataType,o,a),getRunData:()=>({outputs:[{dims:$,dataType:o}],dispatchGroup:{x:Math.ceil(k/64/4)},programUniforms:[{type:12,data:Math.ceil(ze.size($)/4)},...bt(u,m,$)]})}},Tr=(e,t,r,n,i,a)=>{e.compute(cu(t,i??"",e.inputs[0],e.inputs[1],r,n,a))},Lo=e=>{Tr(e,"Add",(t,r)=>`${t}+${r}`)},pu=e=>{Tr(e,"Div",(t,r)=>`${t}/${r}`)},hu=e=>{Tr(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},mu=e=>{Tr(e,"Mul",(t,r)=>`${t}*${r}`)},fu=e=>{let t=Qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Tr(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},zo=e=>{Tr(e,"Sub",(t,r)=>`${t}-${r}`)},_u=e=>{Tr(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},gu=e=>{Tr(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Bo=e=>{Tr(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},yu=e=>{Tr(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Ro,wu,bu,No,Mu,vu,xu=_(()=>{Lt(),Ot(),rs(),Jt(),Ro=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],i=n.dataType,a=n.dims.length;e.forEach((o,u)=>{if(u!==r){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((m,f)=>{if(f!==t&&m!==n.dims[f])throw new Error("non concat dimensions must match")})}})},wu=(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; + }`,bu=(e,t)=>{let r=e.length,n=[];for(let i=0;i{let i=ze.size(r),a=new Array(e.length),o=new Array(e.length),u=0,m=[],f=[],$=[{type:12,data:i}];for(let K=0;K`uniforms.sizeInConcatAxis${K}`).join(","),j=K=>` + + ${(()=>{K.registerUniform("outputSize","u32");for(let ee=0;ee(${N}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${bu(o,k)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:$}),getShaderSource:j}},Mu=(e,t)=>{let r=e.inputs,n=r[0].dims,i=ze.normalizeAxis(t.axis,n.length);Ro(r,i);let a=n.slice();a[i]=r.reduce((u,m)=>u+(m.dims.length>i?m.dims[i]:0),0);let o=r.filter(u=>ze.size(u.dims)>0);e.compute(No(o,i,a,r[0].dataType),{inputs:o})},vu=e=>zt({axis:e.axis})}),un,dn,Br,jo,cn=_(()=>{Lt(),Ot(),un=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},dn=(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})},Br=(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"})},jo=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=(e==null?void 0:e.activation_params)||[ks,er];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),Hs,Uo,Vo=_(()=>{Hs=(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.`)}},Uo=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),Wo,op=_(()=>{Wo=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)); +} +`}),Qn,Go,bi=_(()=>{Lt(),Ot(),Jt(),cn(),Qn=(e,t,r,n,i)=>{let a=n-r;return` + ${Array.from({length:r}).map((o,u)=>` + if (${$t(t.shape,u,t.rank)} != 1) { + ${t.indicesSet(e,u,$t(i,u+a,n))} + } else { + ${t.indicesSet(e,u,0)} + }`).join("")} +`},Go=(e,t,r,n,i=!1,a)=>{let o=e[0].dims,u=e[1].dims,m=o[o.length-2],f=u[u.length-1],$=o[o.length-1],k=Xt(f),d=Xt($),N=Xt(m),j=ze.size(r)/k/N,K=e.length>2,ee=n?n.slice(0,-2):r.slice(0,-2),te=[ze.size(ee),m,f],J=[{type:12,data:j},{type:12,data:m},{type:12,data:f},{type:12,data:$}];dn(t,J),J.push(...bt(ee,o,u)),K&&J.push(...bt(e[2].dims)),J.push(...bt(te));let fe=he=>{let Me=Qi("batch_dims",e[0].dataType,ee.length),Ae=Qe("a",e[0].dataType,o.length,d),Le=Qe("b",e[1].dataType,u.length,k),et=It("output",e[0].dataType,te.length,k),dt=_s(et.type.tensor),Pt=un(t,et.type.value,dt),qt=[Ae,Le],Bt="";if(K){let yt=i?k:1;qt.push(Qe("bias",e[2].dataType,e[2].dims.length,yt)),Bt=`${i?`value += bias[col / ${yt}];`:`value += ${et.type.value}(bias[row + i]);`}`}let At=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Br(t,At);let ts=()=>{let yt=`var a_data: ${Ae.type.value};`;for(let Ht=0;Ht; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${ts()} + } + for (var i = 0u; i < ${N}u; i++) { + var value = values[i]; + ${Bt} + ${Pt} + let cur_indices = ${et.type.indices}(batch, row + i, col); + let offset = ${et.indicesToOffset("cur_indices")}; + ${et.setByOffset(`offset / ${k}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${k};${d};${N};${i}`,inputDependencies:K?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:J}),getShaderSource:fe}}}),Tu,Pu,Ko,Mi,Eu,Ho,qo,vi,Qo=_(()=>{Lt(),Ot(),Jt(),cn(),bi(),Vo(),Tu=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${t?", batchIndices":""}); + `,Pu=(e,t)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Ko=(e,t,r="f32",n,i=!1,a=32,o=!1,u=32)=>{let m=t[1]*e[1],f=t[0]*e[0],$=i?m:a,k=i?a:m,d=$/t[0],N=a/t[1];if(!((i&&d===4&&e[1]===4||!i&&(d===3||d===4))&&$%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${d} must be 3 or 4. + tileAWidth ${$} 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, ${$/d}>, ${k}>; +var mm_Bsub: array, ${f/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${o?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${m}; + + let num_tiles = ${o?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${N}; + 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; + ${Tu(i,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${N}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Pu(i,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Mi=(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":""}); + `,Eu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ho=(e,t,r="f32",n,i=!1,a=32,o=!1,u=32,m=!1)=>{let f=e[1]*t[1],$=e[0]*t[0],k=i?f:a,d=i?a:f;if(!(d%t[1]===0&&k%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let N=d/t[1],j=k/t[0],K=a/t[1],ee=m?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${f}; + let globalColStart = i32(workgroupId.x) * ${$}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { + ${Mi(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 < ${$}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${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) * ${f}; + +let tileRowA = i32(localId.y) * ${N}; +let tileColA = i32(localId.x) * ${j}; +let tileRowB = i32(localId.y) * ${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 innerRow = 0; innerRow < ${N}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${j}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Mi(i,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${K}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${Eu(i)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${d}>; + var mm_Bsub : array, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${o?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${o?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${ee} + } +`},qo=(e,t,r,n,i=!1)=>{let[a,o,u,m]=n,f=_s(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Hs(e,f)} { + var value = ${Hs(e,f)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${o.type.indices}; + ${Qn("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}) -> ${Hs(e,f)} { + var value = ${Hs(e,f)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${u.type.indices}; + ${Qn("bIndices",u,u.rank-2,a.rank,"batchIndices")} + ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} + ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Hs(e,f)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${i?"bias[colIn]":`${Hs(e,f)}(bias[row])`};`:""} + ${r} + ${m.setByIndices("vec3(coords)","value")} + } + } + `},vi=(e,t,r,n,i=!1,a)=>{let o=e[0].dims,u=e[1].dims,m=o.slice(0,-2),f=u.slice(0,-2),$=n?n.slice(0,-2):r.slice(0,-2),k=ze.size($),d=o[o.length-2],N=o[o.length-1],j=u[u.length-1],K=N%4===0&&j%4===0,ee=d<=8?[4,1,1]:[4,4,1],te=[8,8,1],J=[Math.ceil(j/te[0]/ee[0]),Math.ceil(d/te[1]/ee[1]),Math.ceil(k/te[2]/ee[2])],fe=K?4:1,he=[...m,d,N/fe],Me=he.length,Ae=[...f,N,j/fe],Le=Ae.length,et=[k,d,j/fe],dt=[{type:6,data:d},{type:6,data:j},{type:6,data:N}];dn(t,dt),dt.push(...bt($,he,Ae));let Pt=["rank","rank"],qt=e.length>2;qt&&(dt.push(...bt(e[2].dims)),Pt.push("rank")),dt.push(...bt(et));let Bt=At=>{let ts=$.length,yt=Qi("batchDims",e[0].dataType,ts,1),Ht=_s(e[0].dataType),ps=Qe("a",e[0].dataType,Me,fe),Ut=Qe("b",e[1].dataType,Le,fe),Qt=It("result",e[0].dataType,et.length,fe),gs=[ps,Ut];if(qt){let Qs=i?fe:1;gs.push(Qe("bias",e[2].dataType,e[2].dims.length,Qs))}let ot=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Br(t,ot);let Et=_s(Qt.type.tensor),hs=un(t,Qt.type.value,Et),js=qo(fe,qt,hs,[yt,ps,Ut,Qt],i);return` + ${At.registerUniforms(ot).registerInternalVariables(yt).declareVariables(...gs,Qt)} + ${js} + ${K?Ko(ee,te,Ht,yt):Ho(ee,te,Ht,yt)} + `};return{name:"MatMul",shaderCache:{hint:`${ee};${t.activation};${K};${i}`,inputDependencies:Pt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:J[0],y:J[1],z:J[2]},programUniforms:dt}),getShaderSource:Bt}}}),Xo,Cu,ap=_(()=>{Lt(),Ee(),Jt(),cn(),Vo(),op(),Qo(),Xo=(e,t,r,n,i=!1,a,o=4,u=4,m=4,f="f32")=>{let $=dt=>{switch(dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${f}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${dt} is not supported.`)}},k=dt=>{switch(dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${dt} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,N=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,j=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",K=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",ee=e?"row":"col",te=e?"col":"row",J=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${ee} / outWidth; + let outCol = ${ee} % outWidth; + + let WRow = ${te} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${te} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${te} % inChannels; + var resData = ${Hs(o,f)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${j} && xCol >= 0 && xCol < ${K}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${$(o)} + } + return resData;`,fe=e?t&&n?` + let col = colIn * ${o}; + ${J}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${J} + } + return ${Hs(o,f)}(0.0);`:n&&r?` + let col = colIn * ${o}; + ${J}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${J} + } + return ${Hs(o,f)}(0.0);`,he=e?n&&r?k(u):` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${k(u)} + } + return ${Hs(u,f)}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${k(u)} + } + return ${Hs(u,f)}(0.0);`,Me=Hs(m,f),Ae=Hs(e?o:u,f),Le=Hs(e?u:o,f),et=un(a,Me,f);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ae} { + ${e?fe:he} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Le} { + ${e?he:fe} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { + let col = colIn * ${m}; + 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])"}; + ${N} + ${Uo(i)} + ${et} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Cu=(e,t,r,n,i,a,o,u,m)=>{let f=t.format==="NHWC",$=f?e[0].dims[3]:e[0].dims[1],k=r[0],d=f?r[2]:r[3],N=f?r[1]:r[2],j=f?r[3]:r[1],K=f&&($%4===0||$%3===0)&&j%4===0,ee=f?j:d*N,te=f?d*N:j,J=[8,8,1],fe=n<=8?[4,1,1]:[4,4,1],he=[Math.ceil(ee/J[0]/fe[0]),Math.ceil(te/J[1]/fe[1]),Math.ceil(k/J[2]/fe[2])];os("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${he}`);let Me=K?f&&$%4!==0?3:4:1,Ae=J[1]*fe[1],Le=J[0]*fe[0],et=Math.max(J[0]*Me,J[1]),dt=n%Ae===0,Pt=i%Le===0,qt=a%et===0,Bt=K?[Me,4,4]:[1,1,1],At=[{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}];dn(t,At),At.push(...bt(e[0].dims,e[1].dims));let ts=["rank","rank"];o&&(At.push(...bt(e[2].dims)),ts.push("rank")),At.push(...bt(r));let yt=Ht=>{let ps=[{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}];Br(t,ps);let Ut=K?4:1,Qt=_s(e[0].dataType),gs=` + fn setOutputAtIndex(flatIndex : i32, value : ${K?`vec4<${Qt}>`:Qt}) { + result[flatIndex] = ${K?`vec4<${Qt}>`:Qt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${K?`vec4<${Qt}>`:Qt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${K?"/ 4":""}, value); + }`,ot=Qe("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Et=Qe("w",e[1].dataType,e[1].dims.length,Ut),hs=[ot,Et],js=It("result",e[0].dataType,r.length,Ut);if(o){let Qs=Qe("bias",e[2].dataType,e[2].dims.length,Ut);hs.push(Qs),gs+=` + fn getBiasByOutputCoords(coords : vec4) -> ${K?`vec4<${Qt}>`:Qt} { + return bias[coords.${f?"w":"y"}${K?"/ 4":""}]; + }`}return` + ${Wo("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 }; + ${Ht.registerUniforms(ps).declareVariables(...hs,js)} + ${gs} + ${Xo(f,dt,Pt,qt,o,t,Bt[0],Bt[1],Bt[2],Qt)} + ${K?Ko(fe,J,Qt,void 0,!f,et):Ho(fe,J,Qt,void 0,!f,et,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${K};${dt};${Pt};${qt};${Ae};${Le};${et}`,inputDependencies:ts},getRunData:()=>({outputs:[{dims:m?m(r):r,dataType:e[0].dataType}],dispatchGroup:{x:he[0],y:he[1],z:he[2]},programUniforms:At}),getShaderSource:yt}}}),Yo,Jo,Xn,Zo,ea,Su,ta,$u,lp=_(()=>{Lt(),Ee(),Ot(),Jt(),cn(),Vo(),Yo=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Xn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Zo=(e,t,r,n=1)=>{let i=Xn(t,n);return Math.floor((e[0]*(r-1)-r+i)/2)},ea=(e,t,r,n,i)=>{i==null&&(i=Zo(e,t[0],n[0]));let a=[0,0,0,r];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},Su=(e,t,r,n,i,a,o,u,m,f)=>{let $,k,d,N;if(e==="VALID"&&(e=0),typeof e=="number"){$={top:e,bottom:e,left:e,right:e,front:e,back:e};let j=ea([t,r,n,1],[u,m,f],1,[i,a,o],e);k=j[0],d=j[1],N=j[2]}else if(Array.isArray(e)){if(!e.every((K,ee,te)=>K===te[0]))throw Error(`Unsupported padding parameter: ${e}`);$={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let j=ea([t,r,n,1],[u,m,f],1,[i,a,o],e[0]);k=j[0],d=j[1],N=j[2]}else if(e==="SAME_UPPER"){k=Math.ceil(t/i),d=Math.ceil(r/a),N=Math.ceil(n/o);let j=(k-1)*i+u-t,K=(d-1)*a+m-r,ee=(N-1)*o+f-n,te=Math.floor(j/2),J=j-te,fe=Math.floor(K/2),he=K-fe,Me=Math.floor(ee/2),Ae=ee-Me;$={top:fe,bottom:he,left:Me,right:Ae,front:te,back:J}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:$,outDepth:k,outHeight:d,outWidth:N}},ta=(e,t,r,n,i,a=!1,o="channelsLast")=>{let u,m,f,$,k;if(o==="channelsLast")[u,m,f,$,k]=e;else if(o==="channelsFirst")[u,k,m,f,$]=e;else throw new Error(`Unknown dataFormat ${o}`);let[d,,N,j,K]=t,[ee,te,J]=Jo(r),[fe,he,Me]=Jo(n),Ae=Xn(N,fe),Le=Xn(j,he),et=Xn(K,Me),{padInfo:dt,outDepth:Pt,outHeight:qt,outWidth:Bt}=Su(i,m,f,$,ee,te,J,Ae,Le,et),At=a?d*k:d,ts=[0,0,0,0,0];return o==="channelsFirst"?ts=[u,At,Pt,qt,Bt]:o==="channelsLast"&&(ts=[u,Pt,qt,Bt,At]),{batchSize:u,dataFormat:o,inDepth:m,inHeight:f,inWidth:$,inChannels:k,outDepth:Pt,outHeight:qt,outWidth:Bt,outChannels:At,padInfo:dt,strideDepth:ee,strideHeight:te,strideWidth:J,filterDepth:N,filterHeight:j,filterWidth:K,effectiveFilterDepth:Ae,effectiveFilterHeight:Le,effectiveFilterWidth:et,dilationDepth:fe,dilationHeight:he,dilationWidth:Me,inShape:e,outShape:ts,filterShape:t}},$u=(e,t,r,n,i,a)=>{let o=a==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],m={x:r.map((ee,te)=>te)},f=[Math.ceil(Yo(m.x.map(ee=>r[ee]))/u[0]),1,1];os("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${f}`);let $=1,k=ze.size(r),d=[{type:12,data:k},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];dn(t,d),d.push(...bt(e[0].dims,e[1].dims));let N=["rank","rank"],j=e.length===3;j&&(d.push(...bt(e[2].dims)),N.push("rank")),d.push(...bt(r));let K=ee=>{let te=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Br(t,te);let J=1,fe=_s(e[0].dataType),he=Qe("x",e[0].dataType,e[0].dims.length,$),Me=Qe("W",e[1].dataType,e[1].dims.length,J),Ae=[he,Me],Le=It("result",e[0].dataType,r.length,J),et="";if(j){let qt=Qe("bias",e[2].dataType,e[2].dims.length,J);Ae.push(qt),et+=` + fn getBiasByOutputCoords(coords : array) -> ${fe} { + return bias[${o?$t("coords",4,5):$t("coords",1,5)}]; + }`}let dt=Hs($,fe),Pt=un(t,dt,fe);return` + ${et} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${he.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")}; + } + ${ee.registerUniforms(te).declareVariables(...Ae,Le)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Le.offsetToIndices("global_idx")}; + let batch = ${$t("coords",0,he.rank)}; + let d2 = ${o?$t("coords",he.rank-1,he.rank):$t("coords",1,he.rank)}; + let xFRCCorner = vec3(${o?$t("coords",1,he.rank):$t("coords",2,he.rank)}, + ${o?$t("coords",2,he.rank):$t("coords",3,he.rank)}, + ${o?$t("coords",3,he.rank):$t("coords",4,he.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${o?$t("uniforms.x_shape",1,he.rank):$t("uniforms.x_shape",2,he.rank)}; + let xShapeZ = ${o?$t("uniforms.x_shape",2,he.rank):$t("uniforms.x_shape",3,he.rank)}; + let xShapeW = ${o?$t("uniforms.x_shape",3,he.rank):$t("uniforms.x_shape",4,he.rank)}; + let xShapeU = ${o?$t("uniforms.x_shape",4,he.rank):$t("uniforms.x_shape",1,he.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); + } + } + } + } + ${j?"value = value + getBiasByOutputCoords(coords)":""}; + ${Pt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${$};${j}`,inputDependencies:N},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:f[0],y:f[1],z:f[2]},programUniforms:d}),getShaderSource:K}}}),ku,Iu,sa=_(()=>{Lt(),Ot(),Jt(),cn(),ku=(e,t,r,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",o=e[0].dims,u=e[1].dims,m=t.format==="NHWC",f=m?r[3]:r[1],$=f/t.group,k=m&&$>=4?Xt(f):1,d=ze.size(r)/k,N=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:$}];dn(t,N),N.push(...bt(o,[u[0],u[1],u[2],u[3]/k]));let j=i?["rank","rank","rank"]:["rank","rank"];N.push(...bt([r[0],r[1],r[2],r[3]/k]));let K=ee=>{let te=It("output",e[0].dataType,r.length,k),J=_s(te.type.tensor),fe=un(t,te.type.value,J),he=Qe("x",e[0].dataType,o.length),Me=Qe("w",e[1].dataType,u.length,k),Ae=[he,Me];i&&Ae.push(Qe("b",e[2].dataType,e[2].dims,k));let Le=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Br(t,Le);let et=m?` + 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 = ${he.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 = ${he.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${ee.registerUniforms(Le).declareVariables(...Ae,te)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${te.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${m?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${m?1:2}], outputIndices[${m?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${k} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${m?2:1}]; + + var value: ${te.type.value} = ${te.type.value}(0); + ${et} + ${a} + ${fe} + ${te.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${k}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:N}),getShaderSource:K}},Iu=(e,t,r,n)=>{let i=e.length>2,a=Xt(r[3]),o=Xt(r[2]),u=ze.size(r)/a/o,m=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],f=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],$=[r[0],r[1],r[2],r[3]/a],k=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];dn(t,k),k.push(...bt(m,f,$));let d=(o-1)*t.strides[1]+f[1],N=j=>{let K=It("output",e[0].dataType,$.length,a),ee=_s(K.type.tensor),te=un(t,K.type.value,ee),J=Qe("x",e[0].dataType,m.length,a),fe=Qe("w",e[1].dataType,f.length,a),he=[J,fe];i&&he.push(Qe("b",e[2].dataType,e[2].dims,a));let Me=i?"value += b[output_channel];":"",Ae=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Br(t,Ae),` + ${j.registerUniforms(Ae).declareVariables(...he,K)} + ${j.mainStart()} + ${j.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<${J.type.value}, ${d}>; + var values: array<${K.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 < ${f[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${d}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${J.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${J.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${f[1]}; w_width++) { + let w_val = ${fe.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${o}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${o}u; i++) { + var value = values[i]; + ${Me} + ${te} + ${K.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${o};${d};${f[0]};${f[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:k}),getShaderSource:N}}}),Au,xi,Ou,Ti,ra,Pi,Fu,Du,Ei,up=_(()=>{Ot(),ap(),lp(),Qo(),sa(),cn(),bi(),Yr(),Au=(e,t,r,n,i,a)=>{let o=e[0],u=e.slice(a?1:2,a?3:4),m=u.length,f=t[0],$=t.slice(2).map((d,N)=>d+(d-1)*(r[N]-1)),k=u.map((d,N)=>d+n[N]+n[N+m]).map((d,N)=>Math.floor((d-$[N]+i[N])/i[N]));return k.splice(0,0,o),k.splice(a?3:1,0,f),k},xi=[2,3,1,0],Ou=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let 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")},Ti=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=jo(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,o=e.kernel_shape,u=e.pads,m=e.strides,f=e.w_is_const();return{autoPad:n,format:r,dilations:i,group:a,kernelShape:o,pads:u,strides:m,wIsConst:f,...t,cacheKey:`${e.format};${t.activation};`}},Pi=(e,t,r,n)=>{let i=r.format==="NHWC",a=Au(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,i);if(r.group!==1){let Ae=[t[0]];if(i){let Le=e.kernelCustomData.wT??e.compute(_r(t[1],xi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Le),Ae.push(Le)}else Ae.push(t[1]);t.length===3&&Ae.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(Iu(Ae,r,a,n),{inputs:Ae}):e.compute(ku(Ae,r,a,n),{inputs:Ae});return}let o=t.length===3,u=t[0].dims[i?1:2],m=t[0].dims[i?2:3],f=t[0].dims[i?3:1],$=t[1].dims[2],k=t[1].dims[3],d=a[i?1:2],N=a[i?2:3],j=a[i?3:1],K=i&&$===u&&k===m&&r.pads[0]===0&&r.pads[1]===0;if(K||$===1&&k===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Ae=a[0],Le,et,dt,Pt=[];if(i){let At=e.kernelCustomData.wT??e.compute(_r(t[1],xi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=At),K){let ts=u*m*f;Le=t[0].reshape([1,Ae,ts]),et=At.reshape([1,ts,j]),dt=[1,Ae,j]}else Le=t[0].reshape([Ae,u*m,f]),et=At.reshape([1,f,j]),dt=[Ae,d*N,j];Pt.push(Le),Pt.push(et)}else Le=t[0].reshape([Ae,f,u*m]),et=t[1].reshape([1,j,f]),dt=[Ae,j,d*N],Pt.push(et),Pt.push(Le);o&&Pt.push(t[2]);let qt=dt[2],Bt=Pt[0].dims[Pt[0].dims.length-1];qt<8&&Bt<8?e.compute(Go(Pt,r,a,dt,i,n),{inputs:Pt}):e.compute(vi(Pt,r,a,dt,i,n),{inputs:Pt});return}let ee=!0,te=e.kernelCustomData.wT??e.compute(_r(t[1],xi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let J=[t[0],te];o&&J.push(t[2]);let fe=i?d*N:j,he=i?j:d*N,Me=$*k*f;e.compute(Cu(J,r,a,fe,he,Me,o,ee,n),{inputs:J})},Fu=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),o=[1].concat(t.dilations),u=[1].concat(t.kernelShape),m=Ti({...t,pads:i,strides:a,dilations:o,kernelShape:u},n);Pi(e,n,m,f=>r?[f[0],f[2],f[3]]:[f[0],f[1],f[3]])},Du=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",i=Ti(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,o=ta(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute($u(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],n))},Ei=(e,t)=>{if(Ou(e.inputs,t),e.inputs[0].dims.length===3)Fu(e,t);else if(e.inputs[0].dims.length===5)Du(e,e.inputs,t);else{let r=Ti(t,e.inputs);Pi(e,e.inputs,r)}}}),Lu,dp=_(()=>{Lt(),Ee(),Ot(),Jt(),Lu=(e,t,r)=>{let n=e.length>2,i=t.outputShape,a=t.format==="NHWC",o=t.group,u=e[1].dims,m=u[2]/o,f=u[3],$=a?Xt(m):1,k=a?Xt(f):1,d=a?f===1?$:k:1,N=ze.size(i)/k,j=[Math.ceil(N/64),1,1];os("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${j}`);let K=["rank","rank"],ee=[t.strides[0],t.strides[1]],te=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],J=[t.dilations[0],t.dilations[1]],fe=[te[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),te[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],he=[fe[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),fe[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Me=[{type:12,data:N},{type:12,data:ee},{type:12,data:te},{type:12,data:J},{type:12,data:fe},{type:6,data:he},{type:12,data:m},{type:12,data:f},...bt(e[0].dims,e[1].dims)];n&&(Me.push(...bt(e[2].dims)),K.push("rank")),Me.push(...bt(i));let Ae=Le=>{let et=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:ee.length},{name:"filter_dims",type:"u32",length:te.length},{name:"dilations",type:"u32",length:te.length},{name:"effective_filter_dims",type:"u32",length:fe.length},{name:"pads",type:"i32",length:he.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],dt=_s(e[0].dataType),Pt=a?1:2,qt=a?2:3,Bt=a?3:1,At=Qe("W",e[1].dataType,e[1].dims.length,d),ts=Qe("Dy",e[0].dataType,e[0].dims.length,$),yt=[ts,At];n&&yt.push(Qe("bias",e[2].dataType,[i[Bt]].length,k));let Ht=It("result",e[0].dataType,i.length,k),ps=()=>{let Qt="";if($===1)Qt+=` + let w_offset = ${At.indicesToOffset(`${At.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${At.getByOffset(`w_offset / ${d}`)}; + dotProd = dotProd + xValue * wValue;`;else if(f===1)Qt+=` + let wValue = ${At.getByOffset(`${At.indicesToOffset(`${At.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${d}`)}; + dotProd = dotProd + dot(xValue, wValue);`;else for(let gs=0;gs<$;gs++)Qt+=` + let wValue${gs} = ${At.getByOffset(`${At.indicesToOffset(`${At.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${gs}, wOutChannel)`)} / ${d}`)}; + dotProd = dotProd + xValue[${gs}] * wValue${gs};`;return Qt},Ut=` + let outputIndices = ${Ht.offsetToIndices(`global_idx * ${k}`)}; + let batch = ${Ht.indicesGet("outputIndices",0)}; + let d1 = ${Ht.indicesGet("outputIndices",Bt)}; + let r = ${Ht.indicesGet("outputIndices",Pt)}; + let c = ${Ht.indicesGet("outputIndices",qt)}; + 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 = ${Ht.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${dt}(dyRCorner) + ${dt}(wR)) / ${dt}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${dt}(uniforms.Dy_shape[${Pt}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${dt}(dyCCorner) + ${dt}(wC)) / ${dt}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${dt}(uniforms.Dy_shape[${qt}]) || + 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 + ${$}) { + let xValue = ${a?ts.getByOffset(`${ts.indicesToOffset(`${ts.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${$}`):ts.get("batch","inputChannel","idyR","idyC")}; + ${ps()} + inputChannel = inputChannel + ${$}; + } + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${n?` + bias[d1 / ${k}]`:""}; + ${Ht.setByOffset("global_idx","value")}; + `;return` + ${Le.registerUniforms(et).declareVariables(...yt,Ht)} + ${Le.mainStart()} + ${Le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${Ut}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${$}${d}${k}${f===1}`,inputDependencies:K},getRunData:()=>({dispatchGroup:{x:j[0],y:j[1],z:j[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:Me}),getShaderSource:Ae}}}),zu,na,Bu,ia,oa,Ru,aa,la,Nu,cp=_(()=>{dp(),cn(),Yr(),zu=(e,t,r,n,i,a)=>(e-1)*t+r+(n-1)*i+1-a,na=(e,t,r,n,i)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[i]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[i]=a)},Bu=(e,t,r,n,i,a,o,u,m,f)=>{let $=e.length-2,k=f.length===0;m.length<$&&m.push(...Array($-m.length).fill(0));let d=e[0],N=t[u?3:1]*i;for(let j=0,K=e.length-$-(u?1:0);j<$;++j,++K){let ee=e[K],te=k?ee*o[j]:f[j],J=zu(ee,o[j],a[j],t[K],r[j],te);na(J,n,a,j,j+$),k&&f.push(o[j]*(ee-1)+m[j]+(t[K]-1)*r[j]+1-a[j]-a[j+$])}f.splice(0,0,d),f.splice(u?3:1,0,N)},ia=(e,t)=>{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((k,d)=>k*d,1)===0){r.length=0;for(let k=2;kk+d,0)===0){let k=t[0].dims.length-2;m=new Array(k).fill(1)}let f=e.strides.slice();if(f.reduce((k,d)=>k+d,0)===0){let k=t[0].dims.length-2;f=new Array(k).fill(1)}Bu(u,r,m,e.autoPad,e.group,i,f,n,o,a);let $=Object.assign({},e);return Object.assign($,{kernelShape:r,pads:i,outputPadding:o,outputShape:a,dilations:m,strides:f}),$},oa=e=>{let t=jo(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,o=e.kernelShape,u=e.pads,m=e.strides,f=e.wIsConst(),$=e.outputPadding,k=e.outputShape;return{autoPad:n,format:r,dilations:i,group:a,kernelShape:o,outputPadding:$,outputShape:k,pads:u,strides:m,wIsConst:f,...t,cacheKey:`${e.format};${t.activation};`}},Ru=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((o,u)=>o+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((o,u)=>o+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((o,u)=>o+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((o,u)=>o+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},aa=(e,t,r,n)=>{let i=e.kernelCustomData.wT??e.compute(_r(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let a=[t[0],i];t.length===3&&a.push(t[2]),e.compute(Lu(a,r,n),{inputs:a})},la=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let m=t.outputPadding;m=[0].concat(m);let f=ia({...t,pads:u,strides:o,dilations:a,kernelShape:i,outputPadding:m},n);aa(e,n,f,$=>r?[$[0],$[2],$[3]]:[$[0],$[1],$[3]])},Nu=(e,t)=>{if(Ru(e.inputs,t),e.inputs[0].dims.length===3)la(e,t);else{let r=ia(t,e.inputs);aa(e,e.inputs,r)}}}),ua,ju,Uu,pp=_(()=>{Lt(),Ot(),rs(),Jt(),ua=(e,t,r,n)=>{let i=ze.size(t),a=t.length,o=Qe("input",e,a),u=It("output",e,a),m=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),f=ze.normalizeAxis(m,a),$=k=>{let d=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,N=$t("uniforms.input_shape","uniforms.axis",a),j=n.reverse?d+(n.exclusive?" + 1":""):"0",K=n.reverse?N:d+(n.exclusive?"":" + 1");return` + ${k.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,u)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${j}; + let last : i32 = ${K}; + for (var i : i32 = first; i < last; i++) { + ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${o.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:f},...bt(t,t)]}),getShaderSource:$}},ju=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(ua(n,r,i,t),{inputs:[0]})},Uu=e=>{let t=e.exclusive===1,r=e.reverse===1;return zt({exclusive:t,reverse:r})}}),Vu,da,Wu,Gu,Ku,hp=_(()=>{Lt(),Ot(),rs(),Jt(),Vu=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.")},da=(e,t,r,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r,n,i,a,o,u,m=t.format==="NHWC",f=t.blocksize,$=t.mode==="DCR";m?([r,n,i,a]=e.dims,o=$?[r,n,i,f,f,a/f**2]:[r,n,i,a/f**2,f,f],u=$?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=$?[r,f,f,a/f**2,n,i]:[r,a/f**2,f,f,n,i],u=$?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let k=e.reshape(o),d=k.dims.length,N=e.dataType,j=Qe("a",N,d),K=It("output",N,d),ee=te=>` + ${te.registerUniform("output_size","u32").declareVariables(j,K)} + + ${da(u,d,j,K)} + + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${K.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${K.setByOffset("global_idx",j.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:te=>{let J=m?[r,n*f,i*f,a/f**2]:[r,a/f**2,n*f,i*f],fe=ze.size(J),he=k.dims,Me=ze.sortBasedOnPerm(he,u);return{outputs:[{dims:J,dataType:te[0].dataType}],dispatchGroup:{x:Math.ceil(fe/64)},programUniforms:[{type:12,data:fe},...bt(he,Me)]}},getShaderSource:ee}},Gu=(e,t)=>{Vu(e.inputs),e.compute(Wu(e.inputs[0],t))},Ku=e=>zt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ci,Yn,Si,Hu,qu,ca,Qu,pa,Jr,Xu,Yu,mp=_(()=>{Lt(),Ot(),rs(),Jt(),Ci="[a-zA-Z]|\\.\\.\\.",Yn="("+Ci+")+",Si="^"+Yn+"$",Hu="("+Yn+",)*"+Yn,qu="^"+Hu+"$",ca=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Qu=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(qu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,o)=>{let u=e[o].dims.slice();if(!a.match(RegExp(Si)))throw new Error("Invalid LHS term");let m=this.processTerm(a,!0,u,o);this.lhs.push(m)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,o])=>o.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Yn)))throw new Error("Invalid RHS");(i=n.match(RegExp(Ci,"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,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let i=r.length,a=!1,o=[],u=0;if(!e.match(RegExp(Si))&&!t&&e!=="")throw new Error("Invalid LHS term");let m=e.match(RegExp(Ci,"g")),f=new ca(n);return m==null||m.forEach(($,k)=>{if($==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let d=i-m.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(o=r.slice(u,u+d),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let N=0;Ne+"_max",Jr=(e,t,r,n)=>{let i=e.map(f=>f.length).map((f,$)=>Qe(`input${$}`,t,f)),a=ze.size(n),o=It("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(f=>!r.rhs.symbolToIndices.has(f)),m=f=>{let $=[],k="var prod = 1.0;",d="var sum = 0.0;",N="sum += prod;",j=[],K=[],ee=[],te=[],J=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((he,Me)=>{var Ae;if(r.rhs.symbolToIndices.has(Me)){let Le=(Ae=r.rhs.symbolToIndices.get(Me))==null?void 0:Ae[0];Le!==void 0&&r.lhs.forEach((et,dt)=>{if(he.inputIndices.includes(dt)){let Pt=et.symbolToIndices.get(Me);if(Pt===void 0)throw new Error("Invalid symbol error");Pt.forEach(qt=>{$.push(`${i[dt].indicesSet(`input${dt}Indices`,qt,o.indicesGet("outputIndices",Le))}`)})}})}else r.lhs.forEach((Le,et)=>{if(he.inputIndices.includes(et)){let dt=Le.symbolToIndices.get(Me);if(dt===void 0)throw new Error("Invalid symbol error");dt.forEach(Pt=>{j.push(`${i[et].indicesSet(`input${et}Indices`,Pt,`${Me}`)}`)}),te.push(`prod *= ${i[et].getByIndices(`input${et}Indices`)};`)}}),K.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${pa(Me)}; ${Me}++) {`),ee.push("}")});let fe=J?[...$,`let sum = ${i.map((he,Me)=>he.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...$,d,...K,...j,k,...te,N,...ee];return` + ${f.registerUniforms(u.map(he=>({name:`${pa(he)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${o.offsetToIndices("global_idx")}; + ${i.map((he,Me)=>`var input${Me}Indices: ${i[Me].type.indices};`).join(` +`)} + ${fe.join(` +`)}; + ${o.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let f=u.filter(k=>r.symbolToInfo.has(k)).map(k=>{var d;return{type:12,data:((d=r.symbolToInfo.get(k))==null?void 0:d.dimValue)||0}});f.push({type:12,data:a});let $=e.map((k,d)=>[...bt(k)]).reduce((k,d)=>k.concat(d),f);return $.push(...bt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:$}},getShaderSource:m}},Xu=(e,t)=>{let r=new Qu(e.inputs,t.equation),n=r.outputDims,i=e.inputs.map((a,o)=>a.dims);e.compute(Jr(i,e.inputs[0].dataType,r,n))},Yu=e=>{let t=e.equation.replace(/\s+/g,"");return zt({equation:t})}}),Ju,$i,Zu,ed,td,fp=_(()=>{Lt(),Ot(),Jt(),Ju=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let i=0;ie.length>t.length?$i(e,t):$i(t,e),ed=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Zu(t,r),i=e[0].dataType,a=i===9||ze.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4===0?4:1,u=a||n.length>0&&n[n.length-1]%4===0?4:1,m=Math.ceil(ze.size(n)/u),f=k=>{let d=Qe("input",i,t.length,o),N=It("output",i,n.length,u),j;if(i===9){let K=(ee,te,J="")=>` + let outputIndices${te} = ${N.offsetToIndices(`outputOffset + ${te}u`)}; + let offset${te} = ${d.broadcastedIndicesToOffset(`outputIndices${te}`,N)}; + let index${te} = offset${te} / 4u; + let component${te} = offset${te} % 4u; + ${ee}[${te}] = ${J}(${d.getByOffset(`index${te}`)}[component${te}]); + `;j=` + let outputOffset = global_idx * ${u}; + var data = vec4(0); + ${K("data",0,"u32")} + ${K("data",1,"u32")} + ${K("data",2,"u32")} + ${K("data",3,"u32")} + ${N.setByOffset("global_idx","data")} + }`}else j=` + let outputIndices = ${N.offsetToIndices(`global_idx * ${u}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",N)}; + let data = ${N.type.value}(${d.getByOffset(`inputOffset / ${o}`)}); + ${N.setByOffset("global_idx","data")} + }`;return` + ${k.registerUniform("vec_size","u32").declareVariables(d,N)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${j}`},$=[{type:12,data:m},...bt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${o}${u}`,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:$})}},td=e=>{Ju(e.inputs),e.compute(ed(e.inputs),{inputs:[0]})}}),ki,sd,_p=_(()=>{Lt(),Ot(),Jt(),Fo(),ki=e=>{let t=e[0].dataType,r=ze.size(e[0].dims),n=ze.size(e[1].dims),i=n%4===0,a=o=>{let u=Qe("x",t,[1],4),m=Qe("bias",t,[1],4),f=It("y",t,[1],4),$=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],k=N=>` + let bias${N}_offset: u32 = (global_idx * 4 + ${N}) % uniforms.bias_size; + let bias${N} = ${m.getByOffset(`bias${N}_offset / 4`)}[bias${N}_offset % 4];`,d=i?` + let bias = ${m.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${k(0)}${k(1)}${k(2)}${k(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms($).declareVariables(u,m,f)} + + ${Ao(Is(t))} + + ${o.mainStart(dr)} + ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${f.setByOffset("global_idx",wi("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(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/dr/4)}})}},sd=e=>{e.inputs.length<2||ze.size(e.inputs[1].dims)===0?ru(e):e.compute(ki(e.inputs))}}),rd,Jn,nd,id,gp=_(()=>{Lt(),Ot(),rs(),Jt(),rd=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Jn=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=ze.normalizeAxis(t.axis,i),o=r.slice(0);o.splice(a,1,...n);let u=r[a],m=e[0].dataType===9?4:1,f=Math.ceil(ze.size(o)/m),$=[{type:12,data:f},{type:6,data:u},{type:12,data:a},...bt(e[0].dims,e[1].dims,o)],k=d=>{let N=Qe("data",e[0].dataType,e[0].dims.length,m),j=Qe("inputIndices",e[1].dataType,e[1].dims.length),K=It("output",e[0].dataType,o.length,m),ee=J=>{let fe=n.length,he=`var indicesIndices${J} = ${j.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${J}[${Me}]`:`indicesIndices${J}`} = ${o.length>1?`outputIndices${J}[uniforms.axis + ${Me}]`:`outputIndices${J}`};`;he+=` + var idx${J} = ${j.getByIndices(`indicesIndices${J}`)}; + if (idx${J} < 0) { + idx${J} = idx${J} + uniforms.axisDimLimit; + } + var dataIndices${J} : ${N.type.indices}; + `;for(let Me=0,Ae=0;Me1?`dataIndices${J}[${Me}]`:`dataIndices${J}`} = u32(idx${J});`,Ae+=fe):(he+=`${i>1?`dataIndices${J}[${Me}]`:`dataIndices${J}`} = ${o.length>1?`outputIndices${J}[${Ae}]`:`outputIndices${J}`};`,Ae++);return he},te;if(e[0].dataType===9){let J=(fe,he,Me="")=>` + let outputIndices${he} = ${K.offsetToIndices(`outputOffset + ${he}u`)}; + ${ee(he)}; + let offset${he} = ${N.indicesToOffset(`dataIndices${he}`)}; + let index${he} = offset${he} / 4u; + let component${he} = offset${he} % 4u; + ${fe}[${he}] = ${Me}(${N.getByOffset(`index${he}`)}[component${he}]); + `;te=` + let outputOffset = global_idx * ${m}; + var value = vec4(0); + ${J("value",0,"u32")} + ${J("value",1,"u32")} + ${J("value",2,"u32")} + ${J("value",3,"u32")} + ${K.setByOffset("global_idx","value")} + `}else te=` + let outputIndices = ${K.offsetToIndices("global_idx")}; + ${ee("")}; + let value = ${N.getByIndices("dataIndices")}; + ${K.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(N,j,K)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${te} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:$}),getShaderSource:k}},nd=e=>zt({axis:e.axis}),id=(e,t)=>{let r=e.inputs;rd(r),e.compute(Jn(e.inputs,t))}}),od,Ii,ad,yp=_(()=>{Lt(),Ot(),Jt(),od=(e,t,r,n,i,a,o,u,m)=>{let f=[{type:12,data:a},{type:12,data:n},{type:12,data:i},{type:12,data:r},{type:12,data:o},{type:12,data:u},{type:12,data:m}],$=[a];f.push(...bt(t.dims,$));let k=d=>{let N=Qe("indices_data",t.dataType,t.dims.length),j=It("input_slice_offsets_data",12,1,1),K=[N,j],ee=[{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:r.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${d.registerUniforms(ee).declareVariables(...K)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${i.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${r.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}_${r.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:$,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:f}),getShaderSource:k},{inputs:[t],outputs:[-1]})[0]},Ii=(e,t)=>{let r=e.inputs,n=r[0].dims,i=r[0].dataType,a=r[1].dims,o=a[a.length-1],u=ze.sizeToDimension(a,a.length-1),m=ze.sizeFromDimension(n,t.batchDims+o),f=ze.sizeToDimension(n,t.batchDims),$=ze.sizeFromDimension(n,t.batchDims),k=u/f,d=new Array(o),N=m;for(let he=0;hen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let ee=a.slice(0,-1).concat(n.slice(K)),te=ze.size(ee),J=[{type:12,data:te},{type:12,data:m},...bt(r[0].dims,j.dims,ee)],fe=he=>{let Me=Qe("data",r[0].dataType,r[0].dims.length),Ae=Qe("slice_offsets",12,j.dims.length),Le=It("output",r[0].dataType,ee.length);return` + ${he.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,Ae,Le)} + ${he.mainStart()} + ${he.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:ee,dataType:i}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:J}),getShaderSource:fe},{inputs:[r[0],j]})},ad=e=>({batchDims:e.batch_dims,cacheKey:""})}),ld,wp,ud,dd,bp=_(()=>{Lt(),Ot(),rs(),Jt(),ld=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=ze.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],a=e[2],o=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((u,m)=>m===r?Math.ceil(u/n)===a.dims[m]:u===a.dims[m]).reduce((u,m)=>u&&m,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==a.dims.length||!o.dims.map((u,m)=>u===a.dims[m]).reduce((u,m)=>u&&m,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},wp=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,a=ze.normalizeAxis(t.gatherAxis,i),o=ze.normalizeAxis(t.quantizeAxis,i),u=r.slice(0);u.splice(a,1,...n);let m=ze.size(u),f=e[2].dataType,$=e[0].dataType===22,k=[{type:12,data:m},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...bt(...e.map((N,j)=>N.dims),u)],d=N=>{let j=Qe("data",e[0].dataType,e[0].dims.length),K=Qe("inputIndices",e[1].dataType,e[1].dims.length),ee=Qe("scales",e[2].dataType,e[2].dims.length),te=e.length>3?Qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,J=It("output",f,u.length),fe=[j,K,ee];te&&fe.push(te);let he=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${N.registerUniforms(he).declareVariables(...fe,J)} + ${N.mainStart()} + let output_indices = ${J.offsetToIndices("global_idx")}; + var indices_indices = ${K.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${J.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${K.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${J.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${j.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${J.indicesGet("output_indices","i")}; + ${j.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${K.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${r[a]}; + } + ${j.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${J.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${j.indicesSet("data_indices","i","index")}; + } + let data_offset = ${j.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${j.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${$?"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 = ${ee.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${ee.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${ee.getByIndices("scale_indices")}; + ${te?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${te.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${te.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${$?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Is(f)}(quantized_data - zero_point) * scale; + ${J.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((N,j)=>j!==1).map(N=>N.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(N,j)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:f}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:k}),getShaderSource:d}},ud=(e,t)=>{let r=e.inputs;ld(r,t),e.compute(wp(e.inputs,t))},dd=e=>zt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),In,cd,pd,hd,Mp=_(()=>{Lt(),Ot(),rs(),Jt(),In=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.`)},cd=(e,t)=>{let r=e[0].dims,n=e[0].dataType,i=r.length,a=e[1].dims,o=e[1].dataType,u=ze.normalizeAxis(t.axis,i),m=r[u],f=a.slice(0),$=ze.size(f),k=Qe("input",n,i),d=Qe("indicesInput",o,a.length),N=It("output",n,f.length),j=[{type:12,data:$},{type:6,data:m},{type:12,data:u}];return j.push(...bt(r,a,f)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:f,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:j}),getShaderSource:K=>` + ${K.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,d,N)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${N.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${k.type.indices}(outputIndices); + ${k.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${k.getByIndices("inputIndices")}; + + ${N.setByOffset("global_idx","value")}; + }`}},pd=e=>zt({axis:e.axis}),hd=(e,t)=>{let r=e.inputs;In(r),e.compute(cd(e.inputs,t))}}),md,fd,_d,Ai,uh=_(()=>{Lt(),Ot(),Jt(),md=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")},fd=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,o]=zr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[i,a];if(!u)throw new Error("Can't use gemm on the given tensors");let m=16,f=Math.ceil(a/m),$=Math.ceil(i/m),k=!0,d=ze.size(u),N=[{type:12,data:k?f:d},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],j=["type","type"];e.length===3&&(N.push(...bt(e[2].dims)),j.push("rank")),N.push(...bt(u));let K=te=>{let J="";t.transA&&t.transB?J="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?J="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?J="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(J="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let fe=t.alpha===1?"":"value *= uniforms.alpha;",he=Qe("a",e[0].dataType,e[0].dims),Me=Qe("b",e[1].dataType,e[1].dims),Ae=he.type.value,Le=null,et=[he,Me];e.length===3&&(Le=Qe("c",e[2].dataType,e[2].dims.length),et.push(Le));let dt=It("output",e[0].dataType,u.length);et.push(dt);let Pt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${te.registerUniforms(Pt).declareVariables(...et)} + + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Ae}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${J} + } + + ${fe} + ${Le!=null?`let cOffset = ${Le.broadcastedIndicesToOffset("vec2(m, n)",dt)}; value += ${Ae}(uniforms.beta) * ${Le.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},ee=te=>{let J=Qe("a",e[0].dataType,e[0].dims),fe=Qe("b",e[1].dataType,e[1].dims),he=null,Me=[J,fe];e.length===3&&(he=Qe("c",e[2].dataType,e[2].dims.length),Me.push(he));let Ae=It("output",e[0].dataType,u.length);Me.push(Ae);let Le=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],et="",dt="";t.transA&&t.transB?(dt=` + 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] = ${J.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); + } + `,et="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(dt=` + 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] = ${J.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); + } + `,et="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(dt=` + 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] = ${J.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); + } + `,et="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(dt=` + 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] = ${J.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${fe.type.value}(0); + } + `,et="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Pt=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${te.registerUniforms(Le).declareVariables(...Me)} + var tile_a: array, ${m}>; + var tile_b: array, ${m}>; + ${te.mainStart([m,m,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${m}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${m}; + let num_tiles = (uniforms.K - 1) / ${m} + 1; + var k_start = 0u; + var value = ${Ae.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${dt} + k_start = k_start + ${m}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${m}; k++) { + ${et} + } + workgroupBarrier(); + } + + ${Pt} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${he!=null?`let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)",Ae)}; value += ${Ae.type.value}(uniforms.beta) * ${he.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return k?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:f*$},programUniforms:N}),getShaderSource:ee}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:N}),getShaderSource:K}},_d=e=>{let t=e.transA,r=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Ai=(e,t)=>{md(e.inputs),e.compute(fd(e.inputs,t))}}),$r,Rr,pn,hn,gd,ha,yd,wd,ma,bd,Md,fa,vd,xd,_a=_(()=>{Lt(),Ot(),rs(),Jt(),[$r,Rr,pn,hn]=[0,1,2,3],gd=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")},ha=` + 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; + } +`,yd=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; + } +`,wd=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)); + `} + } +`,ma=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); + }`:""} +`,bd=(e,t,r)=>` + 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[${$r}] = batch; + indices[${Rr}] = channel;`+(()=>{switch(r.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${pn}] = u32(r); + indices[${hn}] = u32(c); + } + `;case"border":return` + indices[${pn}] = u32(clamp(r, 0, H - 1)); + indices[${hn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${pn}] = gs_reflect(r, border[1], border[3]); + indices[${hn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,Md=(e,t,r)=>(()=>{switch(r.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${$r}], indices[${Rr}], 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[${$r}], indices[${Rr}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${$r}], indices[${Rr}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${$r}], indices[${Rr}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${$r}], indices[${Rr}], 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[${$r}], indices[${Rr}], 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 ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,fa=(e,t)=>{let r=Qe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=Qe("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[$r,Rr,pn,hn]=[0,3,1,2]);let o=It("output",e[0].dataType,a.length),u=r.type.value,m=ze.size(a),f=[{type:12,data:m},...bt(e[0].dims,n,a)],$=k=>` + ${k.registerUniform("output_size","u32").declareVariables(r,i,o)} + ${ha} + ${yd(u)} + ${wd(t)} + ${ma(t)} + ${bd(r,u,t)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${pn}]); + let W_in = i32(uniforms.x_shape[${hn}]); + + ${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[${$r}], indices[${pn}], indices[${hn}]); + let nxy = ${i.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${Md(o,u,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:k=>{let d=ze.size(a);return{outputs:[{dims:a,dataType:k[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}},getShaderSource:$}},vd=(e,t)=>{gd(e.inputs),e.compute(fa(e.inputs,t))},xd=e=>zt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),ur,Td,Pd,ga,ya,mn,vp,Ed=_(()=>{Lt(),Ot(),rs(),de(),go(),Jt(),Yr(),ur=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Td=(e,t)=>{let r=e[0],n=ur(e,1),i=ur(e,2),a=ur(e,3),o=ur(e,4),u=ur(e,5),m=ur(e,6),f=ur(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let $=r.dims[0],k=r.dims[1],d=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],N=k,j=0,K=0,ee=Math.floor(d/t.numHeads);if(m&&f&&ze.size(m.dims)&&ze.size(f.dims)){if(m.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(m.dims[0]!==$||m.dims[1]!==t.numHeads||m.dims[3]!==ee)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(f.dims[0]!==$||f.dims[1]!==t.numHeads||f.dims[3]!==ee)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(m.dims[2]!==f.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(f.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');j=m.dims[2],K=m.dims[2]}else if(m&&ze.size(m.dims)||f&&ze.size(f.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te;if(n&&ze.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');te=2,N=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==ee)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');te=5,N=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==ee)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');te=0,N=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}if(a&&ze.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let J=j+N,fe=0;if(o&&ze.size(o.dims)>0){fe=8;let Le=o.dims;throw Le.length===1?Le[0]===$?fe=1:Le[0]===3*$+2&&(fe=3):Le.length===2&&Le[0]===$&&Le[1]===J&&(fe=5),fe===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let he=!1,Me=d;if(i&&ze.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.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(N!==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(N!==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],he=!0}}let Ae=!1;if(o&&ze.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(u&&ze.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==$||u.dims[1]!==t.numHeads||u.dims[2]!==k||u.dims[3]!==J)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:$,sequenceLength:k,pastSequenceLength:j,kvSequenceLength:N,totalSequenceLength:J,maxSequenceLength:K,inputHiddenSize:0,hiddenSize:d,vHiddenSize:Me,headSize:ee,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:fe,scale:t.scale,broadcastResPosBias:Ae,passPastInKv:he,qkvFormat:te}},Pd=e=>zt({...e}),ga=zt({perm:[0,2,1,3]}),ya=(e,t,r,n,i,a,o)=>{let u=[n,i,a],m=ze.size(u),f=[{type:12,data:m},{type:12,data:o},{type:12,data:a}],$=k=>{let d=It("qkv_with_bias",t.dataType,u),N=Qe("qkv",t.dataType,u),j=Qe("bias",r.dataType,u),K=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${k.registerUniforms(K).declareVariables(N,j,d)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:f}),getShaderSource:$},{inputs:[t,r],outputs:[-1]})[0]},mn=(e,t,r,n,i,a,o,u)=>{let m=a;if(o&&ze.size(o.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return m=ya(e,a,o,t,n,r*i,u),m=m.reshape([t,n,r,i]),r===1||n===1?m:e.compute(_r(m,ga.perm),{inputs:[m],outputs:[-1]})[0]}else return a.dims.length===3&&(m=a.reshape([t,n,r,i])),r===1||n===1?m:e.compute(_r(m,ga.perm),{inputs:[m],outputs:[-1]})[0]},vp=(e,t)=>{let r=Td(e.inputs,t),n=e.inputs[0],i=ur(e.inputs,1),a=ur(e.inputs,2),o=ur(e.inputs,3),u=ur(e.inputs,4),m=ur(e.inputs,5),f=ur(e.inputs,6),$=ur(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 k=i&&a&&i.dims.length===4&&a.dims.length===4,d=mn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,o,0);if(k)return Hn(e,d,i,a,u,void 0,f,$,m,r);if(!i||!a)throw new Error("key and value must be provided");let N=mn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,o,r.hiddenSize),j=mn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,o,2*r.hiddenSize);Hn(e,d,N,j,u,void 0,f,$,m,r)}}),Cd,wa,Sd,$d,Oi,kd,Id,ba=_(()=>{Lt(),Ot(),rs(),Jt(),Cd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},wa=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),n=r.length),zt({numOutputs:n,axis:t.axis,splitSizes:r})},Sd=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${$t("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,$d=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=ze.size(r),i=e[0].dataType,a=ze.normalizeAxis(t.axis,r.length),o=new Array(t.numOutputs),u=Qe("input",i,r.length),m=new Array(t.numOutputs),f=[],$=[],k=0,d=[{type:12,data:n}];for(let j=0;j` + ${j.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",m.length).declareVariables(u,...o)} + ${Sd(m.length)} + ${$d(o)} + + ${j.mainStart()} + ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${$t("uniforms.size_in_split_axis","output_number - 1u",m.length)}; + ${u.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:N,getRunData:()=>({outputs:f,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d})}},kd=(e,t)=>{Cd(e.inputs);let r=e.inputs.length===1?t:wa(e.inputs,t);e.compute(Oi(e.inputs,r),{inputs:[0]})},Id=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return zt({axis:t,numOutputs:n,splitSizes:r})}}),xp,Tp,Fi,Ma,Pp=_(()=>{rs(),go(),Ed(),ba(),Yr(),xp=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=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(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,m=r.dims[0],f=r.dims[1],$=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],k=f,d=0,N=!n||n.dims.length===0,j=Math.floor(N?$/(t.numHeads+2*t.kvNumHeads):$/t.numHeads);N&&($=j*t.numHeads);let K=a&&a.dims.length!==0,ee=o&&o.dims.length!==0;if(K&&a.dims.length===4&&a.dims[0]===m&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===j)throw new Error("BSNH pastKey/pastValue is not supported");if(K&&ee){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=a.dims[2]}else if(K||ee)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');k=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==j)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.');k=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==j)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}let J=0,fe=!1,he=t.kvNumHeads?j*t.kvNumHeads:$;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(r.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(k!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');he=i.dims[2]}else{if(k!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');he=i.dims[1]*i.dims[3],fe=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==m)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:m,sequenceLength:f,pastSequenceLength:d,kvSequenceLength:k,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:$,vHiddenSize:he,headSize:j,vHeadSize:Math.floor(he/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:J,scale:t.scale,broadcastResPosBias:!1,passPastInKv:fe,qkvFormat:te}},Tp=zt({perm:[0,2,1,3]}),Fi=(e,t,r)=>{let n=t,i=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,i,r.headSize]),n=e.compute(_r(n,Tp.perm),{inputs:[n],outputs:[-1]})[0]),n},Ma=(e,t)=>{var ee;let r=xp(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((ee=e.inputs[1])==null?void 0:ee.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,m=e.inputs.length>4?e.inputs[5]:void 0,f=e.inputs.length>5?e.inputs[6]:void 0,$=r.kvNumHeads?r.kvNumHeads:r.numHeads,k=zt({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,$*r.headSize,$*r.headSize]}),[d,N,j]=!i&&!a?e.compute(Oi([n],k),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],K=mn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,d,void 0,0);Hn(e,K,Fi(e,N,r),Fi(e,j,r),void 0,void 0,o,u,void 0,r,m,f)}}),va,xa,Ad,Od,Fd=_(()=>{Lt(),Ot(),Yr(),Jt(),va=(e,t,r,n,i,a,o,u)=>{let m=Xt(a),f=m===1?"f32":`vec${m}f`,$=m===1?"vec2f":`mat2x${m}f`,k=i*o,d=64;k===1&&(d=256);let N=[i,o,a/m],j=[i,o,2],K=["rank","type","type"],ee=[];ee.push(...bt(N,j));let te=J=>{let fe=Qe("x",t.dataType,3,m),he=Qe("scale",r.dataType,r.dims),Me=Qe("bias",n.dataType,n.dims),Ae=It("output",1,3,2),Le=[fe,he,Me,Ae];return` + var workgroup_shared : array<${$}, ${d}>; + const workgroup_size = ${d}u; + ${J.declareVariables(...Le)} + ${J.mainStart(d)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${f}(0); + var squared_sum = ${f}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${f}(${fe.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${$}(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 = ${Ks("workgroup_shared[0][0]",m)} / f32(hight * ${m}); + let squared_sum_final = ${Ks("workgroup_shared[0][1]",m)} / f32(hight * ${m}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${m};${u};${d}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:j,dataType:1}],dispatchGroup:{x:k},programUniforms:ee}),getShaderSource:te},{inputs:[t,r,n],outputs:[-1]})[0]},xa=(e,t,r)=>{let n=t[0].dims,i=n,a=2,o=n[0],u=n[1],m=ze.sizeFromDimension(n,a),f=Xt(m),$=ze.size(i)/f,k=va(e,t[0],t[1],t[2],o,m,u,r.epsilon),d=[o,u,m/f],N=[o,u],j=["type","none"],K=ee=>{let te=Qe("x",t[0].dataType,d.length,f),J=Qe("scale_shift",1,N.length,2),fe=It("output",t[0].dataType,d.length,f),he=[te,J,fe];return` + ${ee.registerUniform("output_size","u32").declareVariables(...he)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${fe.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${J.getByIndices("vec2(batch, channel)")}; + let value = ${te.getByOffset("global_idx")} * ${fe.type.value}(scale_shift.x) + ${fe.type.value}(scale_shift.y); + ${fe.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${f}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...bt(d,N,d)]}),getShaderSource:K},{inputs:[t[0],k]})},Ad=(e,t,r)=>{let n=t[0].dims,i=n,a=n[0],o=n[n.length-1],u=ze.sizeFromDimension(n,1)/o,m=Xt(o),f=ze.size(i)/m,$=[{type:12,data:u},{type:12,data:Math.floor(o/m)}],k=["type","type"],d=!1,N=[0,n.length-1];for(let te=0;ten[N[J]])),K=va(e,j,t[1],t[2],a,u,o,r.epsilon),ee=te=>{let J=_s(t[0].dataType),fe=m===1?"vec2f":`mat${m}x2f`,he=Le=>{let et=Le===0?"x":"y",dt=m===1?"f32":`vec${m}f`;switch(m){case 1:return`${J}(${dt}(scale.${et}))`;case 2:return`vec2<${J}>(${dt}(scale[0].${et}, scale[1].${et}))`;case 4:return`vec4<${J}>(${dt}(scale[0].${et}, scale[1].${et}, scale[2].${et}, scale[3].${et}))`;default:throw new Error(`Not supported compoents ${m}`)}},Me=Qe("input",t[0].dataType,t[0].dims,m),Ae=It("output",t[0].dataType,i,m);return` + @group(0) @binding(0) var input : array<${Me.type.storage}>; + @group(0) @binding(1) var scale_input : array<${fe}>; + @group(0) @binding(2) var output : array<${Ae.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${te.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${he(0)}, ${he(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${m}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:$}),getShaderSource:ee},{inputs:[t[0],K]})},Od=(e,t)=>{t.format==="NHWC"?Ad(e,e.inputs,t):xa(e,e.inputs,t)}}),Dd,Ld,Ta,Ep=_(()=>{Lt(),Ot(),Jt(),Dd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Ld=(e,t,r)=>{let n=t.simplified,i=e[0].dims,a=e[1],o=!n&&e[2],u=i,m=ze.normalizeAxis(t.axis,i.length),f=ze.sizeToDimension(i,m),$=ze.sizeFromDimension(i,m),k=ze.size(a.dims),d=o?ze.size(o.dims):0;if(k!==$||o&&d!==$)throw new Error(`Size of X.shape()[axis:] == ${$}. + Size of scale and bias (if provided) must match this. + Got scale size of ${k} and bias size of ${d}`);let N=[];for(let Me=0;Me1,J=r>2,fe=Me=>{let Ae=_s(e[0].dataType),Le=[Qe("x",e[0].dataType,e[0].dims,j),Qe("scale",a.dataType,a.dims,j)];o&&Le.push(Qe("bias",o.dataType,o.dims,j)),Le.push(It("output",e[0].dataType,u,j)),te&&Le.push(It("mean_data_output",1,N)),J&&Le.push(It("inv_std_output",1,N));let et=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Me.registerUniforms(et).declareVariables(...Le)} + ${Me.mainStart()} + ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Bs("f32",j)}; + var mean_square_vector = ${Bs("f32",j)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${As(Ae,j,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Ks("mean_vector",j)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Ks("mean_square_vector",j)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${As(Ae,j,"x[j + offset]")}; + let f32scale = ${As(Ae,j,"scale[j]")}; + output[j + offset] = ${Le[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${o?`+ ${As(Ae,j,"bias[j]")}`:""} + ); + } + + ${te?"mean_data_output[global_idx] = mean":""}; + ${J?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},he=[{dims:u,dataType:e[0].dataType}];return te&&he.push({dims:N,dataType:1}),J&&he.push({dims:N,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${j};${r};${n}`,inputDependencies:K},getRunData:()=>({outputs:he,dispatchGroup:{x:Math.ceil(f/64)},programUniforms:ee}),getShaderSource:fe}},Ta=(e,t)=>{Dd(e.inputs),e.compute(Ld(e.inputs,t,e.outputCount))}}),zd,Bd,Cp=_(()=>{Ot(),bi(),Qo(),zd=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.")},Bd=e=>{zd(e.inputs);let t=Gs.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(Go(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=ze.size(e.inputs[0].dims.slice(0,-2)),o=ze.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let u=e.inputs[0].reshape([1,a,n]),m=e.inputs[1].reshape([1,n,r]),f=[1,a,r],$=[u,m];e.compute(vi($,{activation:""},t,f),{inputs:$})}else e.compute(vi(e.inputs,{activation:""},t))}}}),Rd,Nd,jd,Ud,Vd,Wd=_(()=>{Lt(),Ot(),rs(),Jt(),Rd=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,o=e[1];if(!ze.areEqual(o.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(ze.size(u)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let m=e[3].dims,f=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(ze.size(m)!==f)throw new Error("zeroPoints input size error.")}},Nd=(e,t)=>{let r=e[0].dims,n=r.length,i=r[n-2],a=t.k,o=t.n,u=r.slice(0,n-2),m=ze.size(u),f=e[1].dims[2]/4,$=e[0].dataType,k=Xt(t.k),d=Xt(f),N=Xt(o),j=u.concat([i,o]),K=i>1&&o/N%2===0?2:1,ee=ze.size(j)/N/K,te=64,J=[],fe=[m,i,a/k],he=ze.convertShape(e[1].dims).slice();he.splice(-1,1,f/d),J.push(...bt(fe)),J.push(...bt(he)),J.push(...bt(e[2].dims)),e.length===4&&J.push(...bt(ze.convertShape(e[3].dims)));let Me=[m,i,o/N];J.push(...bt(Me));let Ae=Le=>{let et=fe.length,dt=Qe("a",e[0].dataType,et,k),Pt=Qe("b",12,he.length,d),qt=Qe("scales",e[2].dataType,e[2].dims.length),Bt=[dt,Pt,qt],At=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;At&&Bt.push(At);let ts=Me.length,yt=It("output",e[0].dataType,ts,N),Ht=_s(e[0].dataType),ps=(()=>{switch(k){case 1:return`array<${Ht}, 8>`;case 2:return`mat4x2<${Ht}>`;case 4:return`mat2x4<${Ht}>`;default:throw new Error(`${k}-component is not supported.`)}})(),Ut=()=>{let ot=` + // reuse a data + var input_offset = ${dt.indicesToOffset(`${dt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ps}; + for (var j: u32 = 0; j < ${8/k}; j++) { + a_data[j] = ${dt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let Et=0;Et> 4) & b_mask); + b_quantized_values = ${ps}(${Array.from({length:4},(hs,js)=>`${Ht}(b_value_lower[${js}]), ${Ht}(b_value_upper[${js}])`).join(", ")}); + b_dequantized_values = ${k===1?`${ps}(${Array.from({length:8},(hs,js)=>`(b_quantized_values[${js}] - ${At?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${ps}(${Array(8).fill(`${At?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; + workgroup_shared[local_id.x * ${K} + ${Math.floor(Et/N)}]${N>1?`[${Et%N}]`:""} += ${Array.from({length:8/k},(hs,js)=>`${k===1?`a_data[${js}] * b_dequantized_values[${js}]`:`dot(a_data[${js}], b_dequantized_values[${js}])`}`).join(" + ")}; + `;return ot},Qt=()=>{let ot=` + var col_index = col * ${N}; + ${At?` + 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 = ${Ht}(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 = ${At.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${Et} = ${Ht}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return ot},gs=()=>{let ot=`col_index = col * ${N};`;for(let Et=0;Et; + var b_value_upper: vec4; + var b_quantized_values: ${ps}; + var b_dequantized_values: ${ps};`,ot};return` + var workgroup_shared: array<${yt.type.value}, ${K*te}>; + ${Le.declareVariables(...Bt,yt)} + ${Le.mainStart([te,1,1])} + let output_indices = ${yt.offsetToIndices(`(global_idx / ${te}) * ${K}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${te}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/k}; + ${Qt()} + for (var word: u32 = 0; word < ${f}; word += ${d}) { + ${gs()} + for (var i: u32 = 0; i < ${d}; i++) { + ${Ut()} + word_offset += ${8/k}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${K}) { + var output_value: ${yt.type.value} = ${yt.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${te}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${K}; + } + ${yt.setByIndices(`${yt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${k};${d};${N};${K};${te}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:j,dataType:$}],dispatchGroup:{x:ee},programUniforms:J}),getShaderSource:Ae}},jd=(e,t)=>{let r=e[0].dims,n=r.length,i=r[n-2],a=t.k,o=t.n,u=r.slice(0,n-2),m=ze.size(u),f=e[1].dims[2]/4,$=e[0].dataType,k=Xt(t.k),d=Xt(f),N=u.concat([i,o]),j=128,K=o%8===0?8:o%4===0?4:1,ee=j/K,te=ee*d*8,J=te/k,fe=te/t.blockSize,he=ze.size(N)/K,Me=[],Ae=[m,i,a/k],Le=ze.convertShape(e[1].dims).slice();Le.splice(-1,1,f/d),Me.push(...bt(Ae)),Me.push(...bt(Le)),Me.push(...bt(e[2].dims)),e.length===4&&Me.push(...bt(ze.convertShape(e[3].dims)));let et=[m,i,o];Me.push(...bt(et));let dt=Pt=>{let qt=Ae.length,Bt=Qe("a",e[0].dataType,qt,k),At=Qe("b",12,Le.length,d),ts=Qe("scales",e[2].dataType,e[2].dims.length),yt=[Bt,At,ts],Ht=e.length===4?Qe("zero_points",12,e[3].dims.length):void 0;Ht&&yt.push(Ht);let ps=et.length,Ut=It("output",e[0].dataType,ps),Qt=_s(e[0].dataType),gs=()=>{switch(k){case 1:return` + let a_data0 = vec4<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Qt}>(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<${Qt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Qt}>(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(`${k}-component is not supported.`)}};return` + var sub_a: array<${Bt.type.value}, ${J}>; + var inter_results: array, ${K}>; + ${Pt.declareVariables(...yt,Ut)} + ${Pt.mainStart([ee,K,1])} + let output_indices = ${Ut.offsetToIndices(`workgroup_index * ${K}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${fe} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${J}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${J}; a_offset += ${j}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Bt.getByIndices(`${Bt.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Bt.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${fe} + local_id.x; + ${Ht?` + 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 = ${Ht.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Qt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Qt}(8);`} + let scale = ${ts.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${At.getByIndices(`${At.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/k}; + for (var i: u32 = 0; i < ${d}; i++) { + ${gs()} + let b_value = ${d===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${Qt}>(${Array.from({length:4},(ot,Et)=>`${Qt}(b_value_lower[${Et}]), ${Qt}(b_value_upper[${Et}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Qt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ot,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; + word_offset += ${8/k}; + } + workgroupBarrier(); + } + + if (local_idx < ${K}) { + var output_value: ${Ut.type.value} = ${Ut.type.value}(0); + for (var b = 0u; b < ${ee}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Ut.setByIndices(`${Ut.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${k};${d};${ee};${K}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:N,dataType:$}],dispatchGroup:{x:he},programUniforms:Me}),getShaderSource:dt}},Ud=(e,t)=>{Rd(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(jd(e.inputs,t)):e.compute(Nd(e.inputs,t))},Vd=e=>zt(e)}),Gd,Kd,Pa,Hd,qd,ws,Sp,$p,kp,Qd=_(()=>{Lt(),Ot(),Jt(),Gd=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].")}},Kd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,r)}; + if (k < 0) { + break; + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},Pa=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${$t("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${$t("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Hd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + k = i32(${$t("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},qd=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,r)}; + if (k < 0) { + k += i32(${$t("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + k -= i32(${$t("uniforms.x_shape",i,t)}); + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},ws=(e,t,r)=>{switch(r.mode){case 0:return Kd(e,t,r.pads.length);case 1:return Pa(e,t,r.pads.length);case 2:return Hd(e,t,r.pads.length);case 3:return qd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Sp=(e,t)=>{let r=ze.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=ze.size(r),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(...bt(e[0].dims,r));let u=["rank"],m=f=>{let $=It("output",e[0].dataType,r.length),k=Qe("x",e[0].dataType,n.length),d=k.type.value,N=ws($,n.length,t),j=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&j.push({name:"constant_value",type:o?d:"f32"}),` + ${f.registerUniforms(j).declareVariables(k,$)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${$.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${N} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(r)/64)},programUniforms:a}),getShaderSource:m}},$p=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let m=0;ma[Number(m)]=Number(u));let o=[];return a.forEach(u=>o.push(u)),{mode:t.mode,value:n,pads:o}}else return t},kp=(e,t)=>{Gd(e.inputs);let r=$p(e.inputs,t);e.compute(Sp(e.inputs,r),{inputs:[0]})}}),Zn,Ea,Ca,Sa,Di,$a,Ip,ka,Ia,Aa,Ap,Xd,Yd,Jd,Oa,Zd,ec,tc,sc,Op=_(()=>{Re(),Lt(),Ot(),Jt(),Zn=e=>{if(L.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Ea=(e,t,r)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),o=t.kernelShape.slice(),u=t.strides.slice(),m=a?t.dilations.slice():[],f=t.pads.slice();rr.adjustPoolAttributes(r,i,o,u,m,f);let $=rr.computePoolOutputShape(r,i,u,m,o,f,t.autoPad),k=Object.assign({},t);a?Object.assign(k,{kernelShape:o,strides:u,pads:f,dilations:m,cacheKey:t.cacheKey}):Object.assign(k,{kernelShape:o,strides:u,pads:f,cacheKey:t.cacheKey});let d=$.slice();return d.push(d.splice(1,1)[0]),[k,n?d:$]},Ca=(e,t)=>{let r=t.format==="NHWC",n=ze.size(e),i=ze.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],m=t.strides[t.strides.length-1],f=t.pads[t.pads.length/2-1],$=t.pads[t.pads.length-1],k=!!(f+$);a.push({type:12,data:u},{type:12,data:m},{type:12,data:f},{type:12,data:$}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(t.kernelShape.length===2){let N=t.kernelShape[t.kernelShape.length-2],j=t.strides[t.strides.length-2],K=t.pads[t.pads.length/2-2],ee=t.pads[t.pads.length-2];d=!!(K+ee),a.push({type:12,data:N},{type:12,data:j},{type:12,data:K},{type:12,data:ee}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,o,!0,k,d]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=ze.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let m=t.pads.reduce((f,$)=>f+$);return[a,o,!!m,!1,!1]}},Sa=(e,t,r,n,i,a,o,u,m,f,$,k)=>{let d=i.format==="NHWC",N=t.type.value,j=It("output",t.type.tensor,n);if(i.kernelShape.length<=2){let K="",ee="",te="",J=r-(d?2:1);if($?K=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${J}] = indices[${J}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${J}] < 0 || xIndices[${J}] + >= uniforms.x_shape[${J}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:K=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${J}] = indices[${J}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,i.kernelShape.length===2){let fe=r-(d?3:2);k?ee=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${fe}] = indices[${fe}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${fe}] < 0 || xIndices[${fe}] >= uniforms.x_shape[${fe}]) { + pad += i32(uniforms.kw); + continue; + } + `:ee=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${fe}] = indices[${fe}] * uniforms.sh - uniforms.phStart + j; + `,te=` + } + `}return` + ${e.registerUniforms(m).declareVariables(t,j)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${j.offsetToIndices("global_idx")}; + var xIndices = ${j.offsetToIndices("global_idx")}; + + var value = ${N}(${u}); + var pad = 0; + ${ee} + ${K} + ${te} + ${o} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let K=i.kernelShape.length,ee=i.pads.length,te="";return f?te=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:te=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(m).declareVariables(t,j)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${j.offsetToIndices("global_idx")}; + var xIndices = ${j.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${N}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${K-1}u; j++) { + offsets[j] = offset / ${$t("uniforms.kernelStrides","j",K)}; + offset -= offsets[j] * ${$t("uniforms.kernelStrides","j",K)}; + } + offsets[${K-1}] = offset; + + isPad = false; + for (var j = ${r-K}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${$t("uniforms.strides",`j - ${r-K}u`,K)} + + offsets[j - ${r-K}u] - ${$t("uniforms.pads","j - 2u",ee)}; + ${te} + } + ${o} + + output[global_idx] = value; + }`}},Di=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,$a=e=>`${Di(e)};${e.countIncludePad}`,Ip=e=>`${Di(e)};${e.storageOrder};${e.dilations}`,ka=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}),Ia=(e,t,r,n)=>{let[i,a]=Ea(t,n,r),o=Qe("x",t.dataType,t.dims.length),u=o.type.value,m="value += x_val;",f="";i.countIncludePad?f+=`value /= ${u}(uniforms.kernelSize);`:f+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[$,k,d,N,j]=Ca(a,i);$.push(...bt(t.dims,a));let K=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${d};${N};${j}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:$}),getShaderSource:ee=>Sa(ee,o,t.dims.length,a.length,i,m,f,0,k,d,N,j)}},Aa=e=>{let t=e.count_include_pad!==0,r=ka(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:$a(n)}},Ap=(e,t)=>{Zn(e.inputs),e.compute(Ia("AveragePool",e.inputs[0],!1,t))},Xd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Yd=e=>{let t=e.format;return{format:t,...Xd,cacheKey:t}},Jd=(e,t)=>{Zn(e.inputs),e.compute(Ia("GlobalAveragePool",e.inputs[0],!0,t))},Oa=(e,t,r,n)=>{let[i,a]=Ea(t,n,r),o=` + value = max(x_val, value); + `,u="",m=Qe("x",t.dataType,t.dims.length),f=["rank"],[$,k,d,N,j]=Ca(a,i);return $.push(...bt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${d};${N};${j}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:$}),getShaderSource:K=>Sa(K,m,t.dims.length,a.length,i,o,u,t.dataType===10?-65504:-1e5,k,d,N,j)}},Zd=(e,t)=>{Zn(e.inputs),e.compute(Oa("MaxPool",e.inputs[0],!1,t))},ec=e=>{let t=e.storage_order,r=e.dilations,n=ka(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:r,...n,cacheKey:""};return{...i,cacheKey:Ip(i)}},tc=e=>{let t=e.format;return{format:t,...Xd,cacheKey:t}},sc=(e,t)=>{Zn(e.inputs),e.compute(Oa("GlobalMaxPool",e.inputs[0],!0,t))}}),rc,nc,ic,oc,dh=_(()=>{Lt(),Ot(),rs(),Jt(),rc=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((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 r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},nc=(e,t)=>{let r=ze.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,o=e[1].dataType,u=ze.size(a),m=n===3||n===2,f=m?[Math.ceil(ze.size(e[0].dims)/4)]:e[0].dims,$=e[1].dims,k=e.length>2?e[2]:void 0,d=k?m?[Math.ceil(ze.size(k.dims)/4)]:k.dims:void 0,N=$.length===0||$.length===1&&$[0]===1,j=N===!1&&$.length===1,K=Xt(u),ee=N&&(!m||K===4),te=ee?K:1,J=ee&&!m?K:1,fe=Qe("input",m?12:n,f.length,J),he=Qe("scale",o,$.length),Me=k?Qe("zero_point",m?12:n,d.length):void 0,Ae=It("output",o,a.length,te),Le=[fe,he];Me&&Le.push(Me);let et=[f,$];k&&et.push(d);let dt=[{type:12,data:u/te},{type:12,data:r},{type:12,data:t.blockSize},...bt(...et,a)],Pt=qt=>{let Bt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${qt.registerUniforms(Bt).declareVariables(...Le,Ae)} + ${qt.mainStart()} + ${qt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Ae.offsetToIndices("global_idx")}; + + // Set input x + ${m?` + let input = ${fe.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${te===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${fe.getByOffset("global_idx")};`}; + + // Set scale input + ${N?`let scale_value= ${he.getByOffset("0")}`:j?` + let scale_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${he.getByOffset("scale_index")};`:` + var scale_indices: ${he.type.indices} = output_indices; + let index = ${he.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${he.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${he.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Me?N?m?` + 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")}`:j?m?` + let zero_point_index = ${Ae.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 = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Me.getByOffset("zero_point_index")};`:m?` + let zero_point_offset = ${he.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 = ${m?i?"i32":"u32":fe.type.value}(0);`}; + // Compute and write output + ${Ae.setByOffset("global_idx",`${Ae.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Pt,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(u/te/64),y:1,z:1},programUniforms:dt})}},ic=(e,t)=>{rc(e.inputs,t),e.compute(nc(e.inputs,t))},oc=e=>zt({axis:e.axis,blockSize:e.blockSize})}),ac,lc,uc,Fp=_(()=>{Re(),Lt(),Jt(),ac=(e,t,r)=>{let n=e===t,i=et&&r>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},lc=(e,t,r,n)=>{let i=Math.abs(Math.ceil((t-e)/r)),a=[i],o=i,u=[{type:12,data:o},{type:n,data:e},{type:n,data:r},...bt(a)],m=f=>{let $=It("output",n,a.length),k=$.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:k},{name:"delta",type:k}];return` + ${f.registerUniforms(d).declareVariables($)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${k}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:m,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:u})}},uc=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),L.webgpu.validateInputContent&&ac(t,r,n),e.compute(lc(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),dc,cc,Dp,Fa,Lp=_(()=>{Lt(),Ot(),rs(),Jt(),dc=(e,t,r,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}=${r};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:` + ${i}bitcast<${n}>(oldValue) + (${r})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:` + ${i}max(bitcast(oldValue), (${r}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${i}min(bitcast<${n}>(oldValue), (${r}))${a}`;case"mul":return`${i}(bitcast<${n}>(oldValue) * (${r}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},cc=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r,a=1,o=Math.ceil(ze.size(n)/a),u=n[n.length-1],m=ze.sizeFromDimension(r,u),f=[{type:12,data:o},{type:12,data:u},{type:12,data:m},...bt(e[1].dims,e[2].dims,i)],$=k=>{let d=Qe("indices",e[1].dataType,e[1].dims.length),N=Qe("updates",e[2].dataType,e[2].dims.length,a),j=t.reduction!=="none"&&t.reduction!==""?Ha("output",e[0].dataType,i.length):It("output",e[0].dataType,i.length,a);return` + ${k.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(d,N,j)} + ${k.mainStart()} + ${k.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]; + ${dc(t.reduction,"output[data_offset + i]","value",j.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:f}),getShaderSource:$}},Dp=e=>zt({reduction:e.reduction}),Fa=(e,t)=>{e.compute(cc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),pc,hc,mc,Da,fc,_c,gc,yc,wc,bc,Mc,vc,La,xc,Tc,Pc,Ec,Cc,Sc,$c,zp=_(()=>{Lt(),Ot(),rs(),Jt(),pc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},hc=(e,t,r)=>{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(r).fill(1);return t.forEach((i,a)=>n[i]=e[a]),n},mc=(e,t,r,n,i,a)=>{let[o,u,m]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],f=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach($=>a.push($));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach($=>n.push($)),n.length!==0&&n.length!==f&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");pc(n,t),t.axes.length>0&&hc(n,t.axes,f).forEach(($,k)=>n[k]=$)}if(m>0&&e.length>m&&e[m].dims.length===1&&e[m].dims[0]>0&&(e[m].getBigInt64Array().forEach($=>i.push(Number($))),i.length!==0&&i.length!==f&&r>=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>f)throw new Error("Resize requires only of scales or sizes to be specified")},Da=(e,t,r,n)=>` + // 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 big = (${e}) * (${t}); + let whole = ${n}(big / (${r})); + let fract = ${n}(big % (${r})) / ${n}(${r}); + return whole + fract; +`,fc=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${t}(xResized) / ${t}(xScale); + } else { + ${Da("xResized","lengthOriginal","lengthResized",t)} + } + `;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 { + ${Da("xResized","lengthOriginal - 1","lengthResized - 1",t)} + }`;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`)}})()+"}",_c=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",gc=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,o)=>{n[a]=i[o],n[o+r]=i[t.length+o]}),n):i},yc=(e,t,r,n)=>{let i=[];if(r.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]=r[o])}else r.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},wc=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.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},bc=(e,t,r,n,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${$t("uniforms.scales","i",n)}; + var roi_low = ${$t("uniforms.roi","i",i)}; + var roi_hi = ${$t("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${$t("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${$t("uniforms.output_shape","i",r.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Mc=(e,t,r,n,i,a,o)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${$t("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${$t("uniforms.roi","i",a)}; + var roi_hi = ${$t("uniforms.roi",`i + ${r.length}`,a)}; + var input_shape_i = ${$t("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${$t("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${o} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,vc=(e,t)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${$t("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,La=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",xc=(e,t,r,n,i)=>{let[a,o,u,m]=r.length===2?[-1,0,1,-1]:[0,2,3,1],f=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${f} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",o,`max(0, min(row, ${r[o]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; + ${La(e,m,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${f} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${f} = originalIndices[${o}]; + var col:${f} = originalIndices[${u}]; + ${n?`if (row < 0 || row > (${r[o]} - 1) || col < 0 || col > (${r[u]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${r[o]} - 1)); + col = max(0, min(col, ${r[u]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${r.length>2?`u32(originalIndices[${m}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; + var x11: ${f} = getInputValue(batch, channel, row1, col1); + var x12: ${f} = getInputValue(batch, channel, row1, col2); + var x21: ${f} = getInputValue(batch, channel, row2, col1); + var x22: ${f} = getInputValue(batch, channel, row2, col2); + var dx1: ${f} = abs(row - ${f}(row1)); + var dx2: ${f} = abs(${f}(row2) - row); + var dy1: ${f} = abs(col - ${f}(col1)); + var dy2: ${f} = abs(${f}(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); + }`},Tc=(e,t,r,n,i,a,o,u,m,f)=>{let $=r.length===2,[k,d]=$?[0,1]:[2,3],N=e.type.value,j=K=>{let ee=K===k?"row":"col";return` + fn ${ee}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${N} { + var output_index = ${t.indicesGet("output_indices",K)}; + var originalIdx: ${N} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[K]}, + ${n[K]}, ${r[K]}, ${a[K]}, ${a[K]} + ${r.length}); + var fractOriginalIdx: ${N} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${r[K]} - 1))) { + return ${m}; + } + var data: array<${N}, 4> = array<${N}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${ee}: ${N} = originalIdx + ${N}(i); + if (${ee} < 0 || ${ee} >= ${r[K]}) { + ${f?`coefs[i + 1] = 0.0; + continue;`:u?`return ${m};`:`${ee} = max(0, min(${ee}, ${r[K]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",K,`u32(${ee})`)}; + data[i + 1] = ${K===k?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${j(k)}; + ${j(d)}; + fn getCubicInterpolationCoefs(s: ${N}) -> array<${N}, 4> { + var absS = abs(s); + var coeffs: array<${N}, 4> = array<${N}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${N} = 1.0 - absS; + var twoMinusAbsS: ${N} = 2.0 - absS; + var onePlusAbsS: ${N} = 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<${N}, 4>, coefs: array<${N}, 4>) -> ${N} { + var coefsSum: ${N} = 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}) -> ${N} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Pc=(e,t,r,n,i)=>{let[a,o,u,m,f]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],$=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${$} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",o,`max(0, min(depth, ${r[o]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices",m,`max(0, min(width, ${r[m]} - 1))`)}; + ${La(e,f,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${$} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${$} = originalIndices[${o}]; + var height:${$} = originalIndices[${u}]; + var width:${$} = originalIndices[${m}]; + ${n?`if (depth < 0 || depth > (${r[o]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[m]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${r[o]} - 1)); + height = max(0, min(height, ${r[u]} - 1)); + width = max(0, min(width, ${r[m]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${r.length>3?`u32(originalIndices[${f}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${$} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${$} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${$} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${$} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${$} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${$} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${$} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${$} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${$} = abs(depth - ${$}(depth1)); + var dx2: ${$} = abs(${$}(depth2) - depth); + var dy1: ${$} = abs(height - ${$}(height1)); + var dy2: ${$} = abs(${$}(height2) - height); + var dz1: ${$} = abs(width - ${$}(width1)); + var dz2: ${$} = abs(${$}(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); + }`},Ec=(e,t,r,n,i,a)=>{let o=e.dims,u=gc(a,t.axes,o.length),m=yc(o,n,i,t.axes),f=n.slice();n.length===0&&(f=o.map((J,fe)=>J===0?1:m[fe]/J),t.keepAspectRatioPolicy!=="stretch"&&(m=wc(o,f,t)));let $=It("output",e.dataType,m.length),k=Qe("input",e.dataType,o.length),d=ze.size(m),N=o.length===m.length&&o.every((J,fe)=>J===m[fe]),j=t.coordinateTransformMode==="tf_crop_and_resize",K=t.extrapolationValue,ee=k.type.value,te=J=>` + ${N?"":` + ${fc(t.coordinateTransformMode,ee)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${vc(k,o)}; + ${_c(t.nearestMode,r,ee)}; + ${Mc(k,$,o,m,f.length,u.length,j)}; + `;case"linear":return` + ${bc($,o,m,f.length,u.length)}; + ${(()=>{if(o.length===2||o.length===4)return`${xc(k,$,o,j,K)}`;if(o.length===3||o.length===5)return`${Pc(k,$,o,j,K)}`;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`${Tc(k,$,o,m,f,u,t.cubicCoeffA,j,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")}})()}; + `} + ${J.registerUniform("output_size","u32").registerUniform("scales","f32",f.length).registerUniform("roi","f32",u.length).declareVariables(k,$)} + ${J.mainStart()} + ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${N?"output[global_idx] = input[global_idx];":` + let output_indices = ${$.offsetToIndices("global_idx")}; + var input_indices: ${k.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${k.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}|${r}|${f.length>0?t.mode==="cubic"?f:f.length:""}|${i.length>0?i:""}|${u.length>0?u:""}|${N}|${t.mode==="nearest"?o.length:o}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[{dims:m,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:f},{type:1,data:u},...bt(o,m)]})}},Cc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Sc=(e,t)=>{let r=[],n=[],i=[],a=Cc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");mc(e.inputs,t,a,r,n,i),e.compute(Ec(e.inputs[0],t,a,r,n,i),{inputs:[0]})},$c=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,u=e.keepAspectRatioPolicy,m=e.mode,f=e.nearestMode===""?"simple":e.nearestMode;return zt({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:u,mode:m,nearestMode:f})}}),kc,Ic,Ac,Bp=_(()=>{Lt(),Ot(),rs(),Jt(),kc=(e,t)=>{let[r,n,i,a]=e,{numHeads:o,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!ze.areEqual(n.dims,[])&&!ze.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!ze.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let m=r.dims[0],f=r.dims[r.dims.length-2],$=i.dims[0],k=ze.sizeFromDimension(r.dims,1)/f,d=u===0?i.dims[1]*2:k/o;if(u>d)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(m!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(f!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(d/2!==i.dims[1]&&u/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(f>$)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Ic=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],u=ze.sizeFromDimension(e[0].dims,1),m=e[0].dims[e[0].dims.length-2],f=u/m,$=e[2].dims[1],k=i===0?$*2:f/n,d=new Array(o,m,f/k,k-$),N=ze.computeStrides(d),j=[{type:1,data:a},{type:12,data:d},{type:12,data:N},...e[0].dims.length===3?new Array({type:12,data:[u,f,k,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,k,m*k,1]}):[],...bt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],K=ee=>{let te=Qe("input",e[0].dataType,e[0].dims.length),J=Qe("position_ids",e[1].dataType,e[1].dims.length),fe=Qe("cos_cache",e[2].dataType,e[2].dims.length),he=Qe("sin_cache",e[3].dataType,e[3].dims.length),Me=It("output",e[0].dataType,e[0].dims.length);return ee.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:N.length},{name:"input_output_strides",type:"u32",length:N.length}]),` + ${ee.declareVariables(te,J,fe,he,Me)} + + ${ee.mainStart(dr)} + let half_rotary_emb_dim = uniforms.${fe.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${J.broadcastedIndicesToOffset("bsnh.xy",It("",J.type.tensor,2))}; + let position_id = + u32(${J.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); + let j = i + select(half_rotary_emb_dim, 1, ${r}); + let re = ${te.getByOffset("i")} * ${fe.get("position_id","bsnh[3]")} - + ${te.getByOffset("j")} * ${he.get("position_id","bsnh[3]")}; + ${Me.setByOffset("i","re")} + let im = ${te.getByOffset("i")} * ${he.get("position_id","bsnh[3]")} + + ${te.getByOffset("j")} * ${fe.get("position_id","bsnh[3]")}; + ${Me.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${Me.setByOffset("k",te.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:zt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:K,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(d)/dr)},programUniforms:j})}},Ac=(e,t)=>{kc(e.inputs,t),e.compute(Ic(e.inputs,t))}}),Oc,Fc,Rp,Zt=_(()=>{Lt(),Ot(),Jt(),Oc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==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")}},Fc=(e,t,r,n)=>{let i=t.simplified,a=e[0].dims,o=ze.size(a),u=a,m=o,f=a.slice(-1)[0],$=n?a.slice(0,-1).concat(1):[],k=!i&&e.length>3,d=e.length>4,N=n&&r>1,j=n&&r>2,K=r>3,ee=64,te=Xt(f),J=[{type:12,data:m},{type:12,data:te},{type:12,data:f},{type:1,data:t.epsilon}],fe=Me=>{let Ae=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Le=[Qe("x",e[0].dataType,e[0].dims,te),Qe("skip",e[1].dataType,e[1].dims,te),Qe("gamma",e[2].dataType,e[2].dims,te)];k&&Le.push(Qe("beta",e[3].dataType,e[3].dims,te)),d&&Le.push(Qe("bias",e[4].dataType,e[4].dims,te)),Le.push(It("output",e[0].dataType,u,te)),N&&Le.push(It("mean_output",1,$)),j&&Le.push(It("inv_std_output",1,$)),K&&Le.push(It("input_skip_bias_sum",e[0].dataType,u,te));let et=_s(e[0].dataType),dt=_s(1,te);return` + + ${Me.registerUniforms(Ae).declareVariables(...Le)} + var sum_shared : array<${dt}, ${ee}>; + var sum_squared_shared : array<${dt}, ${ee}>; + + ${Me.mainStart([ee,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${ee}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${ee}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${ee-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":et+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${K?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${As(et,te,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${ee}; + 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 = ${Ks("sum",te)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Ks("square_sum",te)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${N?"mean_output[global_idx] = mean;":""} + ${j?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${et}(mean)`}) * + ${et}(inv_std_dev) * gamma[offset1d + i] + ${k?"+ beta[offset1d + i]":""}; + } + }`},he=[{dims:u,dataType:e[0].dataType}];return r>1&&he.push({dims:$,dataType:1}),r>2&&he.push({dims:$,dataType:1}),r>3&&he.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${te};${N};${j};${K}`,inputDependencies:e.map((Me,Ae)=>"type")},getShaderSource:fe,getRunData:()=>({outputs:he,dispatchGroup:{x:Math.ceil(m/f)},programUniforms:J})}},Rp=(e,t)=>{Oc(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(Fc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Dc,Ls,tr,nr,fn,Np,Lc,zc,y=_(()=>{Lt(),Ot(),rs(),Jt(),Dc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Ls=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},tr=(e,t)=>{if(e.length>1){let r=Ls(e,1),n=Ls(e,2),i=Ls(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),zt({starts:r,ends:n,axes:i})}else return t},nr=(e,t,r,n,i)=>{let a=e;return e<0&&(a+=r[n[t]]),i[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},fn=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${$t("uniforms.input_shape","i",r.length)}; + let steps_i = ${$t("uniforms.steps","i",r.length)}; + let signs_i = ${$t("uniforms.signs","i",r.length)}; + let starts_i = ${$t("uniforms.starts","i",r.length)}; + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,Np=(e,t)=>{let r=e[0].dims,n=ze.size(r),i=t.axes.length>0?ze.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=Ls(e,4);a.forEach(te=>te!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((te,J)=>nr(te,J,r,i,a)),u=t.ends.map((te,J)=>nr(te,J,r,i,a));if(i.length!==o.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let te=0;teMath.sign(te));a.forEach((te,J,fe)=>{if(te<0){let he=(u[J]-o[J])/te,Me=o[J],Ae=Me+he*a[J];o[J]=Ae,u[J]=Me,fe[J]=-te}});let f=r.slice(0);i.forEach((te,J)=>{f[te]=Math.ceil((u[te]-o[te])/a[te])});let $={dims:f,dataType:e[0].dataType},k=It("output",e[0].dataType,f.length),d=Qe("input",e[0].dataType,e[0].dims.length),N=ze.size(f),j=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:m.length},{name:"steps",type:"u32",length:a.length}],K=[{type:12,data:N},{type:12,data:o},{type:6,data:m},{type:12,data:a},...bt(e[0].dims,f)],ee=te=>` + ${te.registerUniforms(j).declareVariables(d,k)} + ${fn(d,k,r)} + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${k.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${k.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${m.length}_${o.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[$],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:K})}},Lc=(e,t)=>{Dc(e.inputs,t);let r=tr(e.inputs,t);e.compute(Np(e.inputs,r),{inputs:[0]})},zc=e=>{let t=e.starts,r=e.ends,n=e.axes;return zt({starts:t,ends:r,axes:n})}}),E,V,ge,Fe,De=_(()=>{Lt(),Ot(),rs(),Yr(),Jt(),E=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},V=(e,t)=>{let r=e.inputs[0],n=r.dims,i=ze.size(n),a=n.length,o=ze.normalizeAxis(t.axis,a),u=oet),f[o]=a-1,f[a-1]=o,m=e.compute(_r(r,f),{inputs:[r],outputs:[-1]})[0]):m=r;let $=m.dims,k=$[a-1],d=i/k,N=Xt(k),j=k/N,K=64;d===1&&(K=256);let ee=(Le,et)=>et===4?`max(max(${Le}.x, ${Le}.y), max(${Le}.z, ${Le}.w))`:et===2?`max(${Le}.x, ${Le}.y)`:et===3?`max(max(${Le}.x, ${Le}.y), ${Le}.z)`:Le,te=Qe("x",m.dataType,m.dims,N),J=It("result",m.dataType,m.dims,N),fe=te.type.value,he=_s(m.dataType)==="f32"?`var threadMax = ${fe}(-3.402823e+38f);`:`var threadMax = ${fe}(-65504.0h);`,Me=Le=>` + var rowMaxShared : ${fe}; + var rowSumShared : ${fe}; + var threadShared : array<${fe}, ${K}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${fe} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${fe}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Le.registerUniform("packedCols","i32").declareVariables(te,J)} + ${Le.mainStart(K)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${K}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${he} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${fe}(${ee("threadShared[0]",N)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${fe}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${fe}(${Ks("threadShared[0]",N)}); + } + 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); + } + }`,Ae=e.compute({name:"Softmax",shaderCache:{hint:`${N};${K}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:$,dataType:m.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:j}]}),getShaderSource:Me},{inputs:[m],outputs:[u?-1:0]})[0];u&&e.compute(_r(Ae,f),{inputs:[Ae]})},ge=(e,t)=>{E(e.inputs),V(e,t)},Fe=e=>zt({axis:e.axis})}),Ze,rt,_t,Mt,Rt,Wt=_(()=>{Lt(),Ot(),Jt(),Ze=e=>Array.from(e.getBigInt64Array(),Number),rt=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(Ze(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")},_t=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Ze(e[1]),i=_t(r,n),a=ze.size(i),o=e[0].dataType,u=Qe("input",o,r.length),m=It("output",o,i.length),f=$=>` + const inputShape = ${u.indices(...r)}; + ${$.registerUniform("output_size","u32").declareVariables(u,m)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${m.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + for (var i = 0; i < ${r.length}; i++) { + let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${m.indicesGet("output_indices","i")} % input_dim_i; + + ${u.indicesSet("input_indices","i","input_dim_value")} + } + ${m.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...bt(e[0].dims,i)]}),getShaderSource:f}},Rt=e=>{rt(e.inputs),e.compute(Mt(e.inputs),{inputs:[0]})}}),Dt,Gt,es,ns=_(()=>{Lt(),Ot(),Jt(),Dt=(e,t,r,n,i)=>{let a=It("output_data",i,r.length,4),o=Qe("a_data",t[1].dataType,t[1].dims.length,4),u=Qe("b_data",t[2].dataType,t[2].dims.length,4),m=Qe("c_data",t[0].dataType,t[0].dims.length,4),f,$=(k,d,N)=>`select(${d}, ${k}, ${N})`;if(!n)f=a.setByOffset("global_idx",$(o.getByOffset("global_idx"),u.getByOffset("global_idx"),m.getByOffset("global_idx")));else{let k=(d,N,j="")=>{let K=`a_data[index_a${N}][component_a${N}]`,ee=`b_data[index_b${N}][component_b${N}]`,te=`bool(c_data[index_c${N}] & (0xffu << (component_c${N} * 8)))`;return` + let output_indices${N} = ${a.offsetToIndices(`global_idx * 4u + ${N}u`)}; + let offset_a${N} = ${o.broadcastedIndicesToOffset(`output_indices${N}`,a)}; + let offset_b${N} = ${u.broadcastedIndicesToOffset(`output_indices${N}`,a)}; + let offset_c${N} = ${m.broadcastedIndicesToOffset(`output_indices${N}`,a)}; + let index_a${N} = offset_a${N} / 4u; + let index_b${N} = offset_b${N} / 4u; + let index_c${N} = offset_c${N} / 4u; + let component_a${N} = offset_a${N} % 4u; + let component_b${N} = offset_b${N} % 4u; + let component_c${N} = offset_c${N} % 4u; + ${d}[${N}] = ${j}(${$(K,ee,te)}); + `};i===9?f=` + var data = vec4(0); + ${k("data",0,"u32")} + ${k("data",1,"u32")} + ${k("data",2,"u32")} + ${k("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:f=` + ${k("output_data[global_idx]",0)} + ${k("output_data[global_idx]",1)} + ${k("output_data[global_idx]",2)} + ${k("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(m,o,u,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${f} + }`},Gt=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(ze.areEqual(t,r)&&ze.areEqual(r,n)),o=t,u=ze.size(t);if(a){let f=Gs.calcShape(Gs.calcShape(t,r,!1),n,!1);if(!f)throw new Error("Can't perform where op on the given tensors");o=f,u=ze.size(o)}let m=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:f=>Dt(f,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:m},...bt(n,t,r,o)]})}},es=e=>{e.compute(Gt(e.inputs))}}),Yt,as=_(()=>{tp(),go(),sp(),rp(),np(),ip(),xu(),up(),cp(),pp(),hp(),mp(),fp(),_p(),gp(),yp(),bp(),Mp(),uh(),_a(),Pp(),Fd(),Ep(),Cp(),Wd(),Ed(),Qd(),Op(),dh(),Fp(),Lp(),fi(),zp(),Bp(),Zt(),y(),De(),ba(),Wt(),Yr(),Fo(),ns(),Yt=new Map([["Abs",[Dl]],["Acos",[vo]],["Acosh",[Ll]],["Add",[Lo]],["ArgMax",[po,ho]],["ArgMin",[Cl,ho]],["Asin",[zl]],["Asinh",[xo]],["Atan",[Bl]],["Atanh",[Rl]],["Attention",[kl]],["AveragePool",[Ap,Aa]],["BatchNormalization",[wo]],["BiasAdd",[Fl]],["BiasSplitGelu",[Do]],["Cast",[Nl,To]],["Ceil",[Ul]],["Clip",[Po]],["Concat",[Mu,vu]],["Conv",[Ei,ra]],["ConvTranspose",[Nu,oa]],["Cos",[Vl]],["Cosh",[Eo]],["CumSum",[ju,Uu]],["DepthToSpace",[Gu,Ku]],["DequantizeLinear",[ic,oc]],["Div",[pu]],["Einsum",[Xu,Yu]],["Elu",[Wl,qn]],["Equal",[hu]],["Erf",[Gl]],["Exp",[Co]],["Expand",[td]],["FastGelu",[sd]],["Floor",[Kl]],["FusedConv",[Ei,ra]],["Gather",[id,nd]],["GatherElements",[hd,pd]],["GatherBlockQuantized",[ud,dd]],["GatherND",[Ii,ad]],["Gelu",[Hl]],["Gemm",[Ai,_d]],["GlobalAveragePool",[Jd,Yd]],["GlobalMaxPool",[sc,tc]],["Greater",[_u]],["GreaterOrEqual",[Bo]],["GridSample",[vd,xd]],["GroupQueryAttention",[Ma]],["HardSigmoid",[Jl,ko]],["InstanceNormalization",[Od]],["LayerNormalization",[Ta]],["LeakyRelu",[So,qn]],["Less",[gu]],["LessOrEqual",[yu]],["Log",[iu]],["MatMul",[Bd]],["MatMulNBits",[Ud,Vd]],["MaxPool",[Zd,ec]],["Mul",[mu]],["MultiHeadAttention",[vp,Pd]],["Neg",[Ql]],["Not",[ql]],["Pad",[kp]],["Pow",[fu]],["QuickGelu",[au,qn]],["Range",[uc]],["Reciprocal",[$o]],["ReduceMin",[xl]],["ReduceMean",[bl]],["ReduceMax",[lo]],["ReduceSum",[uo]],["ReduceProd",[Tl]],["ReduceL1",[ao]],["ReduceL2",[Ml]],["ReduceLogSum",[El]],["ReduceLogSumExp",[vl]],["ReduceSumSquare",[Pl]],["Relu",[Xl]],["Resize",[Sc,$c]],["RotaryEmbedding",[Ac]],["ScatterND",[Fa,Dp]],["Sigmoid",[Yl]],["Sin",[Zl]],["Sinh",[Io]],["Slice",[Lc,zc]],["SkipLayerNormalization",[Rp]],["Split",[kd,Id]],["Sqrt",[eu]],["Softmax",[ge,Fe]],["Sub",[zo]],["Tan",[tu]],["Tanh",[su]],["ThresholdedRelu",[nu,qn]],["Tile",[Rt]],["Transpose",[Za,Zi]],["Where",[es]]])}),Es,Ts=_(()=>{Re(),Ee(),Jt(),Es=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,i){Ne(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let f of t)u.push({binding:u.length,resource:{buffer:f.buffer}});for(let f of r)u.push({binding:u.length,resource:{buffer:f.buffer}});i&&u.push({binding:u.length,resource:i});let m=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let f={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:m,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(f)}o.setPipeline(e.computePipeline),o.setBindGroup(0,m),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(),je(e.programInfo.name)}dispose(){}build(e,t){Ne(e.name);let r=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(f=>{r.features.has(f.feature)&&n.push(`enable ${f.extension};`)});let i=Qa(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${n.join(` +`)} +${i.additionalImplementations} +${a}`,u=r.createShaderModule({code:o,label:e.name});os("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let m=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return je(e.name),{programInfo:e,computePipeline:m,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&r<=i&&n<=i)return[t,r,n];let a=t*r*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]}}}),cs,Ps,Os,ir,qs,kr=_(()=>{Re(),Lt(),Ee(),Y(),us(),as(),Ts(),cs=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var i,a;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${cs(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Os=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ir=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]}},qs=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r},i=a=>t.features.has(a)&&r.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 ir(this.device),this.adapterInfo=new Os(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fs(this),this.programManager=new Es(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,kn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ne(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=N);let K=Number(N-this.queryTimeBase),ee=Number(j-this.queryTimeBase);if(!Number.isSafeInteger(K)||!Number.isSafeInteger(ee))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:k.map(te=>({dims:te.dims,dataType:wr(te.dataType)})),outputsMetadata:d.map(te=>({dims:te.dims,dataType:wr(te.dataType)})),kernelId:o,kernelType:m,kernelName:f,programName:$,startTime:K,endTime:ee});else{let te="";k.forEach((fe,he)=>{te+=`input[${he}]: [${fe.dims}] | ${wr(fe.dataType)}, `});let J="";d.forEach((fe,he)=>{J+=`output[${he}]: [${fe.dims}] | ${wr(fe.dataType)}, `}),console.log(`[profiling] kernel "${o}|${m}|${f}|${$}" ${te}${J}execution time: ${ee-K} ns`)}Ve("GPU",`${$}::${N}::${j}`)}e.unmap(),this.pendingQueries.delete(e)}),je()}run(e,t,r,n,i,a){Ne(e.name);let o=[];for(let J=0;Jfe):r;if($.length!==u.length)throw new Error(`Output size ${$.length} must be equal to ${u.length}.`);let k=[],d=[];for(let J=0;J=a)throw new Error(`Invalid output index: ${$[J]}`);if($[J]===-3)continue;let fe=$[J]===-1,he=$[J]===-2,Me=fe||he?i(u[J].dataType,u[J].dims):n($[J],u[J].dataType,u[J].dims);if(k.push(Me),Me.data===0)continue;let Ae=this.gpuDataManager.get(Me.data);if(!Ae)throw new Error(`no GPU data for output: ${Me.data}`);if(fe&&this.temporaryData.push(Ae),he){let Le=this.kernelPersistentData.get(this.currentKernelId);Le||(Le=[],this.kernelPersistentData.set(this.currentKernelId,Le)),Le.push(Ae)}d.push(Ae)}if(o.length!==t.length||d.length!==k.length){if(d.length===0)return je(e.name),k;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let N;if(f){let J=0,fe=[];f.forEach(Le=>{let et=typeof Le.data=="number"?[Le.data]:Le.data;if(et.length===0)return;let dt=Le.type===10?2:4,Pt,qt;Le.type===10?(qt=et.length>4?16:et.length>2?8:et.length*dt,Pt=et.length>4?16:dt*et.length):(qt=et.length<=2?et.length*dt:16,Pt=16),J=Math.ceil(J/qt)*qt,fe.push(J);let Bt=Le.type===10?8:4;J+=et.length>4?Math.ceil(et.length/Bt)*Pt:et.length*dt});let he=16;J=Math.ceil(J/he)*he;let Me=new ArrayBuffer(J);f.forEach((Le,et)=>{let dt=fe[et],Pt=typeof Le.data=="number"?[Le.data]:Le.data;if(Le.type===6)new Int32Array(Me,dt,Pt.length).set(Pt);else if(Le.type===12)new Uint32Array(Me,dt,Pt.length).set(Pt);else if(Le.type===10)new Uint16Array(Me,dt,Pt.length).set(Pt);else if(Le.type===1)new Float32Array(Me,dt,Pt.length).set(Pt);else throw new Error(`Unsupported uniform type: ${wr(Le.type)}`)});let Ae=this.gpuDataManager.create(J,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ae.buffer,0,Me,0,J),this.gpuDataManager.release(Ae.id),N={offset:0,size:J,buffer:Ae.buffer}}let j=this.programManager.normalizeDispatchGroupSize(m),K=j[1]===1&&j[2]===1,ee=Ps(e,t,K),te=this.programManager.getArtifact(ee);if(te||(te=this.programManager.build(e,j),this.programManager.setArtifact(ee,te),os("info",()=>`[artifact] key: ${ee}, programName: ${e.name}`)),f&&te.uniformVariablesInfo){if(f.length!==te.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${te.uniformVariablesInfo.length}, got ${f.length} in program "${te.programInfo.name}".`);for(let J=0;J`[ProgramManager] run "${e.name}" (key=${ee}) with ${j[0]}x${j[1]}x${j[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let J={kernelId:this.currentKernelId,programName:te.programInfo.name,inputTensorViews:t,outputTensorViews:k};this.pendingKernels.push(J),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(J)}return this.programManager.run(te,o,d,j,N),je(e.name),k}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let i=Yt.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,a=n.kernelName,o=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),os("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let m=this.env.debug;this.temporaryData=[];try{return m&&this.device.pushErrorScope("validation"),o(t,u[1]),0}catch(f){return r.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${f}`)),1}finally{m&&r.push(this.device.popErrorScope().then(f=>f?`GPU validation error for kernel "[${i}] ${a}": ${f.message}`:null));for(let f of this.temporaryData)this.gpuDataManager.release(f.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,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(r,n,a);return i.set(t,[o,r]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[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,r){return async()=>{let n=await Tt(this,e,t);return C(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){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),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}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()}}}),An,Li,mr,Pr,zi,ei,Bi,Ri,Cs=_(()=>{Ee(),An=1,Li=()=>An++,mr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Pr=(e,t)=>{let r=mr.get(e);if(!r)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,i)=>n*i)*r/8):0},zi=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 Pr(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)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,i)=>n===r[i])}},ei=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,r,n){if(this.wrapper){if(this.wrapper.canReuseTensor(e,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Pr(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,i,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else 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()}},Bi=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Li();return this.tensorTrackersById.set(e,new ei(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,r,n){os("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(this.backend.currentContext,t,r,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){os("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.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,r,n){let i=Li(),a=new zi({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(i,new ei(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,r,n,i){let a=this.backend.currentSessionId,o=this.backend.currentContext;for(let[m,f]of this.freeTensors.entries())if(f.canReuseTensor(o,e,t)){os("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let $=this.freeTensors.splice(m,1)[0];return $.sessionId=a,$}os("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await o.createTensor({dataType:e,shape:t,dimensions:t,usage:r,writable:n,readable:i});return new zi({sessionId:a,context:o,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Ri=(...e)=>new Bi(...e)}),Rs,Zr,_n,ti=_(()=>{Lt(),pr(),Y(),Cs(),Ee(),Rs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Zr=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((i,a)=>i===n[a]&&e[i]===t[i])},_n=class{constructor(e){this.tensorManager=Ri(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],kn(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 r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>Zr(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}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 r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.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,r,n){let i=Rs.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,r,n)}uploadTensor(e,t){if(!vs().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 r=await this.tensorManager.download(e);return C(r,t)}}registerMLTensor(e,t,r){let n=Rs.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,r);return os("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,r,n,i,a){if(!a)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let u=a.get(o);if(!u)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+r>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let m=u.slice(t,t+r).buffer,f;switch(i.dataType){case"float32":f=new Float32Array(m);break;case"float16":f=new Uint16Array(m);break;case"int32":f=new Int32Array(m);break;case"uint32":f=new Uint32Array(m);break;case"int64":f=new BigInt64Array(m);break;case"uint64":f=new BigUint64Array(m);break;case"int8":f=new Int8Array(m);break;case"int4":case"uint4":case"uint8":f=new Uint8Array(m);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,f)}flush(){}}}),Ni={};v(Ni,{init:()=>Ba});var si,za,Ba,ch=_(()=>{Lt(),kr(),Ee(),Ot(),ti(),si=class Gf{constructor(t,r,n,i){this.module=t,this.dataType=r,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=ze.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=ze.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=ze.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=ze.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(ze.size(t)!==ze.size(this.dims))throw new Error("Invalid new shape");return new Gf(this.module,this.dataType,this.data,t)}},za=class{constructor(e,t,r){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=r/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*i++,a));let o=Number(e.getValue(n*i++,a));this.outputCount=Number(e.getValue(n*i++,a)),this.customDataOffset=Number(e.getValue(n*i++,"*")),this.customDataSize=Number(e.getValue(n*i++,a));let u=[];for(let m=0;mtypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(u,m,f)=>new si(this.module,m,this.output(u,f),f),a=(u,m)=>{let f=hr(u,m);if(!f)throw new Error(`Unsupported data type: ${u}`);let $=f>0?this.backend.gpuDataManager.create(f).id:0;return new si(this.module,u,$,m)};return this.backend.run(e,r,n,i,a,this.outputCount)}output(e,t){let r=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 qs;await a.initialize(r,n),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,u,m,f=!1)=>{if(f)os("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(u)}, size=${Number(m)}`),a.memcpy(Number(o),Number(u));else{os("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(u)}, size=${Number(m)}`);let $=t.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(m));a.upload(Number(u),$)}},async(o,u,m)=>{os("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${u}, size=${m}`),await a.download(Number(o),()=>t.HEAPU8.subarray(Number(u)>>>0,Number(u+m)>>>0))},(o,u,m)=>a.createKernel(o,Number(u),m,t.UTF8ToString(t._JsepGetNodeName(Number(u)))),o=>a.releaseKernel(o),(o,u,m,f)=>{os("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${m}, kernel=${o}, contextDataOffset=${u}`);let $=new za(t,a,Number(u));return a.computeKernel(Number(o),$,f)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new _n(r);i("webnn",[a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,u,m,f)=>a.ensureTensor(o,u,m,f),(o,u)=>{a.uploadTensor(o,u)},async(o,u)=>a.downloadTensor(o,u)])}}}),Ra,ri,ji,en,Na,On,Bc,Rc,Nc,tn,yr,ph,Qh=_(()=>{di(),ci(),Lt(),pr(),Tn(),Un(),Ra=(e,t)=>{vs()._OrtInit(e,t)!==0&&ss("Can't initialize onnxruntime.")},ri=async e=>{Ra(e.wasm.numThreads,on(e.logLevel))},ji=async(e,t)=>{{let r=(ch(),b(Ni)).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 r("webgpu",vs(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",vs(),e)}}},en=new Map,Na=e=>{let t=vs(),r=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,i,i+n)!==0&&ss("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(r)}},On=e=>{let t=vs(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Bc=async(e,t)=>{var k,d,N;let r,n,i=vs();Array.isArray(e)?[r,n]=e:e.buffer===i.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=On(e);let a=0,o=0,u=0,m=[],f=[],$=[];try{if([o,m]=jn(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let Me=[];for(let Ae of t.externalData){let Le=typeof Ae=="string"?Ae:Ae.path;Me.push($n(typeof Ae=="string"?Ae:Ae.data).then(et=>{i.mountExternalData(Le,et)}))}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 Ae=Me,Le=Ae==null?void 0:Ae.context,et=Ae==null?void 0:Ae.gpuDevice,dt=Ae==null?void 0:Ae.deviceType,Pt=Ae==null?void 0:Ae.powerPreference;Le?i.currentContext=Le:et?i.currentContext=await i.jsepCreateMLContext(et):i.currentContext=await i.jsepCreateMLContext({deviceType:dt,powerPreference:Pt})}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(r,n,o),a===0&&ss("Can't create a session."),(k=i.jsepOnCreateSession)==null||k.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[j,K]=Na(a),ee=!!(t!=null&&t.enableGraphCapture),te=[],J=[],fe=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(u=i._OrtCreateBinding(a),u===0&&ss("Can't create IO binding."),he={handle:u,outputPreferredLocations:fe,outputPreferredLocationsEncoded:fe.map(Me=>Sn(Me))}),en.set(a,[a,f,$,he,ee,!1]),[a,te,J]}catch(j){throw f.forEach(K=>i._OrtFree(K)),$.forEach(K=>i._OrtFree(K)),u!==0&&i._OrtReleaseBinding(u)!==0&&ss("Can't release IO binding."),a!==0&&i._OrtReleaseSession(a)!==0&&ss("Can't release session."),j}finally{i._free(r),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ss("Can't release session options."),m.forEach(j=>i._free(j)),(N=i.unmountExternalData)==null||N.call(i)}},Rc=e=>{var m;let t=vs(),r=en.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,o,u]=r;o&&(u&&t._OrtClearBoundOutputs(o.handle)!==0&&ss("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ss("Can't release IO binding.")),(m=t.jsepOnReleaseSession)==null||m.call(t,e),i.forEach(f=>t._OrtFree(f)),a.forEach(f=>t._OrtFree(f)),t._OrtReleaseSession(n)!==0&&ss("Can't release session."),en.delete(e)},Nc=(e,t,r,n,i,a=!1)=>{if(!e){t.push(0);return}let o=vs(),u=o.PTR_SIZE,m=e[0],f=e[1],$=e[3],k,d;if(m==="string"&&($==="gpu-buffer"||$==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&$!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if($==="gpu-buffer"){let K=e[2].gpuBuffer;d=hr(Qr(m),f);let ee=o.jsepRegisterBuffer;if(!ee)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');k=ee(n,i,K,d)}else if($==="ml-tensor"){let K=e[2].mlTensor;d=hr(Qr(m),f);let ee=o.jsepRegisterMLTensor;if(!ee)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');k=ee(K,Qr(m),f)}else{let K=e[2];if(Array.isArray(K)){d=u*K.length,k=o._malloc(d),r.push(k);for(let ee=0;eeo.setValue(j+te*u,ee,u===4?"i32":"i64"));let K=o._OrtCreateTensor(Qr(m),k,d,j,f.length,Sn($));K===0&&ss(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(K)}finally{o.stackRestore(N)}},tn=async(e,t,r,n,i,a)=>{var qt,Bt;let o=vs(),u=o.PTR_SIZE,m=en.get(e);if(!m)throw new Error(`cannot run inference. invalid session id: ${e}`);let f=m[0],$=m[1],k=m[2],d=m[3],N=m[4],j=m[5],K=t.length,ee=n.length,te=0,J=[],fe=[],he=[],Me=[],Ae=o.stackSave(),Le=o.stackAlloc(K*u),et=o.stackAlloc(K*u),dt=o.stackAlloc(ee*u),Pt=o.stackAlloc(ee*u);try{(qt=o.jsepOnRunStart)==null||qt.call(o,f),[te,J]=Hr(a);for(let yt=0;ytSs*sr,1);gs=wr(hs);let jr=d==null?void 0:d.outputPreferredLocations[n[yt]];if(gs==="string"){if(jr==="gpu-buffer"||jr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ss=[];for(let sr=0;sr0){let Ss=o.jsepGetBuffer;if(!Ss)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let sr=Ss(ot),Fn=hr(hs,gn);if(Fn===void 0||!En(gs))throw new Error(`Unsupported data type: ${gs}`);Qt=!0,ts.push([gs,Nr,{gpuBuffer:sr,download:o.jsepCreateDownloader(sr,Fn,gs),dispose:()=>{o._OrtReleaseTensor(Ht)!==0&&ss("Can't release tensor.")}},"gpu-buffer"])}else if(jr==="ml-tensor"&&gn>0){let Ss=o.jsepEnsureTensor;if(!Ss)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(hr(hs,gn)===void 0||!Cn(gs))throw new Error(`Unsupported data type: ${gs}`);let sr=await Ss(ot,hs,Nr,!1);Qt=!0,ts.push([gs,Nr,{mlTensor:sr,download:o.jsepCreateMLTensorDownloader(ot,gs),dispose:()=>{o.jsepReleaseTensorId(ot),o._OrtReleaseTensor(Ht)}},"ml-tensor"])}else{let Ss=Pn(gs),sr=new Ss(gn);new Uint8Array(sr.buffer,sr.byteOffset,sr.byteLength).set(o.HEAPU8.subarray(ot,ot+sr.byteLength)),ts.push([gs,Nr,sr,"cpu"])}}finally{o.stackRestore(ps),gs==="string"&&ot&&o._free(ot),Qt||o._OrtReleaseTensor(Ht)}}return d&&!N&&(o._OrtClearBoundOutputs(d.handle)!==0&&ss("Can't clear bound outputs."),en.set(e,[f,$,k,d,N,!1])),ts}finally{o.stackRestore(Ae),fe.forEach(At=>o._OrtReleaseTensor(At)),he.forEach(At=>o._OrtReleaseTensor(At)),Me.forEach(At=>o._free(At)),te!==0&&o._OrtReleaseRunOptions(te),J.forEach(At=>o._free(At))}},yr=e=>{let t=vs(),r=en.get(e);if(!r)throw new Error("invalid session id");let n=r[0],i=t._OrtEndProfiling(n);i===0&&ss("Can't get an profile file name."),t._OrtFree(i)},ph=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),ni,Er,ja,jc,Uc,jp,hh,Up,Ui,Vi,Xh,Yh,Jh,Zh,em,tm,sm,rm,nm=_(()=>{Re(),Qh(),pr(),Gr(),ni=()=>!!L.wasm.proxy&&typeof document<"u",ja=!1,jc=!1,Uc=!1,Up=new Map,Ui=(e,t)=>{let r=Up.get(e);r?r.push(t):Up.set(e,[t])},Vi=()=>{if(ja||!jc||Uc||!Er)throw new Error("worker not ready")},Xh=e=>{switch(e.data.type){case"init-wasm":ja=!1,e.data.err?(Uc=!0,hh[1](e.data.err)):(jc=!0,hh[0]()),jp&&(URL.revokeObjectURL(jp),jp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Up.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Yh=async()=>{if(!jc){if(ja)throw new Error("multiple calls to 'initWasm()' detected.");if(Uc)throw new Error("previous call to 'initWasm()' failed.");if(ja=!0,ni())return new Promise((e,t)=>{Er==null||Er.terminate(),Vr().then(([r,n])=>{var i;try{Er=n,Er.onerror=o=>t(o),Er.onmessage=Xh,hh=[e,t];let a={type:"init-wasm",in:L};!a.in.wasm.wasmPaths&&(r||(i=import.meta.url)!=null&&i.startsWith("file:"))&&(a.in.wasm.wasmPaths={wasm:new URL(s("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),s.b).href}),Er.postMessage(a),jp=r}catch(a){t(a)}},t)});try{await Lr(L.wasm),await ri(L),jc=!0}catch(e){throw Uc=!0,e}finally{ja=!1}}},Jh=async e=>{if(ni())return Vi(),new Promise((t,r)=>{Ui("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:L}};Er.postMessage(n)});await ji(L,e)},Zh=async e=>ni()?(Vi(),new Promise((t,r)=>{Ui("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Er.postMessage(n,[e.buffer])})):On(e),em=async(e,t)=>{if(ni()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Vi(),new Promise((r,n)=>{Ui("create",[r,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Er.postMessage(i,a)})}else return Bc(e,t)},tm=async e=>{if(ni())return Vi(),new Promise((t,r)=>{Ui("release",[t,r]);let n={type:"release",in:e};Er.postMessage(n)});Rc(e)},sm=async(e,t,r,n,i,a)=>{if(ni()){if(r.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 Vi(),new Promise((o,u)=>{Ui("run",[o,u]);let m=r,f={type:"run",in:{sessionId:e,inputIndices:t,inputs:m,outputIndices:n,options:a}};Er.postMessage(f,ph(m))})}else return tn(e,t,r,n,i,a)},rm=async e=>{if(ni())return Vi(),new Promise((t,r)=>{Ui("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Er.postMessage(n)});yr(e)}}),mh,im,om,Yf=_(()=>{Re(),nm(),Lt(),qe(),Un(),mh=(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()}`)}},im=e=>{switch(e[3]){case"cpu":return new ue(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!En(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:i}=e[2];return ue.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!Cn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:i}=e[2];return ue.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},om=class{async fetchModelAndCopyToWasmMemory(e){return Zh(await $n(e))}async loadModel(e,t){Ne();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await em(r,t),je()}async dispose(){return tm(this.sessionId)}async run(e,t,r){Ne();let n=[],i=[];Object.entries(e).forEach(k=>{let d=k[0],N=k[1],j=this.inputNames.indexOf(d);if(j===-1)throw new Error(`invalid input '${d}'`);n.push(N),i.push(j)});let a=[],o=[];Object.entries(t).forEach(k=>{let d=k[0],N=k[1],j=this.outputNames.indexOf(d);if(j===-1)throw new Error(`invalid output '${d}'`);a.push(N),o.push(j)});let u=n.map((k,d)=>mh(k,()=>`input "${this.inputNames[i[d]]}"`)),m=a.map((k,d)=>k?mh(k,()=>`output "${this.outputNames[o[d]]}"`):null),f=await sm(this.sessionId,i,u,o,m,r),$={};for(let k=0;k_h,initializeFlags:()=>fh,wasmBackend:()=>lm});var fh,_h,lm,Jf=_(()=>{Re(),nm(),Yf(),fh=()=>{if((typeof L.wasm.initTimeout!="number"||L.wasm.initTimeout<0)&&(L.wasm.initTimeout=0),L.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 L.wasm.proxy!="boolean"&&(L.wasm.proxy=!1),typeof L.wasm.trace!="boolean"&&(L.wasm.trace=!1),typeof L.wasm.numThreads!="number"||!Number.isInteger(L.wasm.numThreads)||L.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)L.wasm.numThreads=1;else{let e=typeof navigator>"u"?F("node:os").cpus().length:navigator.hardwareConcurrency;L.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},_h=class{async init(e){fh(),await Yh(),await Jh(e)}async createInferenceSessionHandler(e,t){let r=new om;return await r.loadModel(e,t),Promise.resolve(r)}},lm=new _h});Re(),Re(),Re();var Zf="1.21.0-dev.20250206-d981b153d3",e_=$e;{let e=(Jf(),b(am)).wasmBackend;H("webgpu",e,5),H("webnn",e,5),H("cpu",e,10),H("wasm",e,10)}Object.defineProperty(L.versions,"web",{value:Zf,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":(R,c,s)=>{var h;s.r(c),s.d(c,{Tensor:()=>F.Tensor,createInferenceSession:()=>ne,deviceToExecutionProviders:()=>H,isONNXProxy:()=>X,isONNXTensor:()=>G});var T=s("./src/env.js"),I=s("?2ce3"),U=s("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),F=s("./node_modules/onnxruntime-common/dist/esm/index.js");const _=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 w,b;const x=Symbol.for("onnxruntime");if(x in globalThis)b=globalThis[x];else if(T.apis.IS_NODE_ENV){switch(b=I??(h||(h=s.t(I,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),w=["cpu"]}else b=U,T.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),T.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),w=["wasm"];const O=b.InferenceSession;function H(D=null){if(!D)return w;switch(D){case"auto":return v;case"gpu":return v.filter(A=>["webgpu","cuda","dml","webnn-gpu"].includes(A))}if(v.includes(D))return[_[D]??D];throw new Error(`Unsupported device: "${D}". Should be one of: ${v.join(", ")}.`)}let re=null;async function ne(D,A,M){re&&await re;const P=O.create(D,A);re??(re=P);const L=await P;return L.config=M,L}function G(D){return D instanceof b.Tensor}const W=b==null?void 0:b.env;W!=null&&W.wasm&&(W.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${T.env.version}/dist/`,W.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(W.wasm.numThreads=1)),W!=null&&W.webgpu&&(W.webgpu.powerPreference="high-performance");function X(){var D;return(D=W==null?void 0:W.wasm)==null?void 0:D.proxy}T.env.backends.onnx=W},"./src/base/feature_extraction_utils.js":(R,c,s)=>{s.r(c),s.d(c,{FeatureExtractor:()=>U,validate_audio_inputs:()=>F});var h=s("./src/utils/constants.js"),T=s("./src/utils/generic.js"),I=s("./src/utils/hub.js");class U extends T.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,w){const b=await(0,I.getModelJSON)(v,h.FEATURE_EXTRACTOR_NAME,!0,w);return new this(b)}}function F(_,v){var w;if(!(_ instanceof Float32Array||_ instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((w=_==null?void 0:_.constructor)==null?void 0:w.name)??typeof _} 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":(R,c,s)=>{s.r(c),s.d(c,{ImageProcessor:()=>D,center_to_corners_format:()=>b,post_process_instance_segmentation:()=>X,post_process_object_detection:()=>x,post_process_panoptic_segmentation:()=>W,post_process_semantic_segmentation:()=>O});var h=s("./src/utils/generic.js"),T=s("./src/utils/tensor.js"),I=s("./src/utils/maths.js");s("./src/utils/image.js");var U=s("./src/utils/core.js"),F=s("./src/utils/hub.js"),_=s("./src/utils/constants.js");function v(A,M,P=0,L=null){const le=A/M;let oe=(0,I.bankers_round)(le)*M;return L!==null&&oe>L&&(oe=Math.floor(le)*M),oeM&&Z.push(Se)}else{let Se=(0,I.max)(be.data)[1];if(Se===ie-1||(ce=(0,I.softmax)(be.data),ce[Se]Je*ke[(se+1)%2])),Oe.boxes.push(Be),Oe.classes.push(Se),Oe.scores.push(ce[Se])}}Pe.push(Oe)}return Pe}function O(A,M=null){const P=A.logits,L=P.dims[0];if(M!==null&&M.length!==L)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const le=[];for(let oe=0;oeke[Z]&&(ke[Z]=be[Z],Oe[Z]=Ge)}const Ce=new Array(we.dims[0]);for(let Ge=0;GeGe!==void 0);le.push({segmentation:pe,labels:tt})}return le}function H(A,M,P,L){const le=[],oe=[],Te=[];for(let we=0;weP&&(le.push(Pe),oe.push(Oe),Te.push(pe))}return[le,oe,Te]}function re(A,M,P,L=.5,le=.8){const oe=[];let Te=0,we=0;const ie=M[P].data;for(let pe=0;pe=L&&++we;let Pe=Te>0&&we>0;return Pe&&(Pe=Te/we>le),[Pe,oe]}function ne(A,M,P,L,le,oe=null,Te=null){const[we,ie]=Te??A[0].dims,Pe=new T.Tensor("int32",new Int32Array(we*ie),[we,ie]),pe=[];if(Te!==null)for(let Ge=0;GeOe[ce]&&(ke[ce]=Ge,Oe[ce]=Z[ce])}let Ce=0;const tt=Pe.data;for(let Ge=0;Ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(A,M)/Math.min(A,M)}`);let oe=Math.round(A/P)*P,Te=Math.round(M/P)*P;if(oe*Te>le){const we=Math.sqrt(A*M/le);oe=Math.floor(A/we/P)*P,Te=Math.floor(M/we/P)*P}else if(oe*Teoe?Pe=Math.floor(oe*ie/le):oe>le&&(ie=Math.floor(le*Pe/oe)),await M.resize(Pe,ie,{resample:L}))}async crop_margin(M,P=200){const L=M.clone().grayscale(),le=(0,I.min)(L.data)[0],Te=(0,I.max)(L.data)[0]-le;if(Te===0)return M;const we=P/255;let ie=L.width,Pe=L.height,pe=0,ke=0;const Oe=L.data;for(let Ce=0;Cethis.preprocess(oe)));return{pixel_values:(0,T.stack)(L.map(oe=>oe.pixel_values),0),original_sizes:L.map(oe=>oe.original_size),reshaped_input_sizes:L.map(oe=>oe.reshaped_input_size)}}static async from_pretrained(M,P){const L=await(0,F.getModelJSON)(M,_.IMAGE_PROCESSOR_NAME,!0,P);return new this(L)}}},"./src/base/processing_utils.js":(R,c,s)=>{s.r(c),s.d(c,{Processor:()=>U});var h=s("./src/utils/constants.js"),T=s("./src/utils/generic.js"),I=s("./src/utils/hub.js");class U extends T.Callable{constructor(_,v){super(),this.config=_,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(_,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(_,{tokenize:!1,...v})}batch_decode(..._){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(..._)}decode(..._){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(..._)}async _call(_,...v){for(const w of[this.image_processor,this.feature_extractor,this.tokenizer])if(w)return w(_,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(_,v){const[w,b]=await Promise.all([this.uses_processor_config?(0,I.getModelJSON)(_,h.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(x=>x in this).map(async x=>{const O=await this[x].from_pretrained(_,v);return[x.replace(/_class$/,""),O]})).then(Object.fromEntries)]);return new this(w,b)}}_e(U,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),_e(U,"uses_processor_config",!1)},"./src/configs.js":(R,c,s)=>{s.r(c),s.d(c,{AutoConfig:()=>v,PretrainedConfig:()=>_,getKeyValueShapes:()=>F});var h=s("./src/utils/core.js"),T=s("./src/utils/hub.js");async function I(w,b){return await(0,T.getModelJSON)(w,"config.json",!0,b)}function U(w){const b={};let x={};switch(w.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":x=U(w.text_config);break;case"moondream1":x=U(w.phi_config);break;case"musicgen":x=U(w.decoder);break;case"multi_modality":x=U(w.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":b.num_heads="n_head",b.num_layers="n_layer",b.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":b.num_heads="num_attention_heads",b.num_layers="num_hidden_layers",b.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":b.num_heads="num_key_value_heads",b.num_layers="num_hidden_layers",b.hidden_size="hidden_size",b.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"glm":case"helium":b.num_heads="num_key_value_heads",b.num_layers="num_hidden_layers",b.dim_kv="head_dim";break;case"openelm":b.num_heads="num_kv_heads",b.num_layers="num_transformer_layers",b.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":b.num_heads="num_heads",b.num_layers="num_layers",b.hidden_size="hidden_size";break;case"bloom":b.num_heads="n_head",b.num_layers="n_layer",b.hidden_size="hidden_size";break;case"mpt":b.num_heads="n_heads",b.num_layers="n_layers",b.hidden_size="d_model";break;case"exaone":b.num_heads="num_key_value_heads",b.num_layers="num_layers",b.dim_kv="head_dim",b.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":b.num_decoder_layers="num_decoder_layers",b.num_decoder_heads="num_heads",b.decoder_dim_kv="d_kv",b.num_encoder_layers="num_layers",b.num_encoder_heads="num_heads",b.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":b.num_decoder_layers="decoder_layers",b.num_decoder_heads="decoder_attention_heads",b.decoder_hidden_size="d_model",b.num_encoder_layers="encoder_layers",b.num_encoder_heads="encoder_attention_heads",b.encoder_hidden_size="d_model";break;case"speecht5":b.num_decoder_layers="decoder_layers",b.num_decoder_heads="decoder_attention_heads",b.decoder_hidden_size="hidden_size",b.num_encoder_layers="encoder_layers",b.num_encoder_heads="encoder_attention_heads",b.encoder_hidden_size="hidden_size";break;case"trocr":b.num_encoder_layers=b.num_decoder_layers="decoder_layers",b.num_encoder_heads=b.num_decoder_heads="decoder_attention_heads",b.encoder_hidden_size=b.decoder_hidden_size="d_model";break;case"musicgen_decoder":b.num_encoder_layers=b.num_decoder_layers="num_hidden_layers",b.num_encoder_heads=b.num_decoder_heads="num_attention_heads",b.encoder_hidden_size=b.decoder_hidden_size="hidden_size";break;case"moonshine":b.num_decoder_layers="decoder_num_hidden_layers",b.num_decoder_heads="decoder_num_key_value_heads",b.num_encoder_layers="encoder_num_hidden_layers",b.num_encoder_heads="encoder_num_key_value_heads",b.encoder_hidden_size=b.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const H=U(w.decoder),re="num_decoder_layers"in H,ne=(0,h.pick)(w,["model_type","is_encoder_decoder"]);return re?(ne.num_decoder_layers=H.num_decoder_layers,ne.num_decoder_heads=H.num_decoder_heads,ne.decoder_hidden_size=H.decoder_hidden_size,ne.num_encoder_layers=H.num_encoder_layers,ne.num_encoder_heads=H.num_encoder_heads,ne.encoder_hidden_size=H.encoder_hidden_size):(ne.num_layers=H.num_layers,ne.num_heads=H.num_heads,ne.hidden_size=H.hidden_size),ne}const O={...x,...(0,h.pick)(w,["model_type","multi_query","is_encoder_decoder"])};for(const H in b)O[H]=w[b[H]];return O}function F(w,{prefix:b="past_key_values",batch_size:x=1}={}){const O={},H=w.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,ne=H.decoder_dim_kv??H.decoder_hidden_size/H.num_decoder_heads,G=[x,H.num_encoder_heads,0,re],W=[x,H.num_decoder_heads,0,ne];for(let X=0;X{var L,le;s.r(c),s.d(c,{apis:()=>ne,env:()=>M});var h=s("?569f"),T=s("?3f59"),I=s("?154a");const U="3.3.3",F=typeof window<"u"&&typeof window.document<"u",_=typeof self<"u"&&((L=self.constructor)==null?void 0:L.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,w=typeof navigator<"u"&&"gpu"in navigator,b=typeof navigator<"u"&&"ml"in navigator,x=typeof process<"u",O=x&&((le=process==null?void 0:process.release)==null?void 0:le.name)==="node",H=!P(h),re=!P(T),ne=Object.freeze({IS_BROWSER_ENV:F,IS_WEBWORKER_ENV:_,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:w,IS_WEBNN_AVAILABLE:b,IS_PROCESS_AVAILABLE:x,IS_NODE_ENV:O,IS_FS_AVAILABLE:H,IS_PATH_AVAILABLE:re}),G=H&&re;let W="./";if(G){const oe=Object(import.meta).url;oe?W=T.dirname(T.dirname(I.fileURLToPath(oe))):typeof __dirname<"u"&&(W=T.dirname(__dirname))}const X=G?T.join(W,"/.cache/"):null,D="/models/",A=G?T.join(W,D):D,M={version:U,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(F||_),localModelPath:A,useFS:H,useBrowserCache:v,useFSCache:H,cacheDir:X,useCustomCache:!1,customCache:null};function P(oe){return Object.keys(oe).length===0}},"./src/generation/configuration_utils.js":(R,c,s)=>{s.r(c),s.d(c,{GenerationConfig:()=>T});var h=s("./src/utils/core.js");class T{constructor(U){_e(this,"max_length",20);_e(this,"max_new_tokens",null);_e(this,"min_length",0);_e(this,"min_new_tokens",null);_e(this,"early_stopping",!1);_e(this,"max_time",null);_e(this,"do_sample",!1);_e(this,"num_beams",1);_e(this,"num_beam_groups",1);_e(this,"penalty_alpha",null);_e(this,"use_cache",!0);_e(this,"temperature",1);_e(this,"top_k",50);_e(this,"top_p",1);_e(this,"typical_p",1);_e(this,"epsilon_cutoff",0);_e(this,"eta_cutoff",0);_e(this,"diversity_penalty",0);_e(this,"repetition_penalty",1);_e(this,"encoder_repetition_penalty",1);_e(this,"length_penalty",1);_e(this,"no_repeat_ngram_size",0);_e(this,"bad_words_ids",null);_e(this,"force_words_ids",null);_e(this,"renormalize_logits",!1);_e(this,"constraints",null);_e(this,"forced_bos_token_id",null);_e(this,"forced_eos_token_id",null);_e(this,"remove_invalid_values",!1);_e(this,"exponential_decay_length_penalty",null);_e(this,"suppress_tokens",null);_e(this,"streamer",null);_e(this,"begin_suppress_tokens",null);_e(this,"forced_decoder_ids",null);_e(this,"guidance_scale",null);_e(this,"num_return_sequences",1);_e(this,"output_attentions",!1);_e(this,"output_hidden_states",!1);_e(this,"output_scores",!1);_e(this,"return_dict_in_generate",!1);_e(this,"pad_token_id",null);_e(this,"bos_token_id",null);_e(this,"eos_token_id",null);_e(this,"encoder_no_repeat_ngram_size",0);_e(this,"decoder_start_token_id",null);_e(this,"generation_kwargs",{});Object.assign(this,(0,h.pick)(U,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(R,c,s)=>{s.r(c),s.d(c,{ClassifierFreeGuidanceLogitsProcessor:()=>G,ForcedBOSTokenLogitsProcessor:()=>_,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>I,LogitsProcessorList:()=>F,LogitsWarper:()=>U,MinLengthLogitsProcessor:()=>H,MinNewTokensLengthLogitsProcessor:()=>re,NoBadWordsLogitsProcessor:()=>ne,NoRepeatNGramLogitsProcessor:()=>x,RepetitionPenaltyLogitsProcessor:()=>O,SuppressTokensAtBeginLogitsProcessor:()=>w,TemperatureLogitsWarper:()=>W,TopKLogitsWarper:()=>D,TopPLogitsWarper:()=>X,WhisperTimeStampLogitsProcessor:()=>b});var h=s("./src/utils/generic.js");s("./src/utils/tensor.js");var T=s("./src/utils/maths.js");class I extends h.Callable{_call(M,P){throw Error("`_call` should be implemented in a subclass")}}class U extends h.Callable{_call(M,P){throw Error("`_call` should be implemented in a subclass")}}class F extends h.Callable{constructor(){super(),this.processors=[]}push(M){this.processors.push(M)}extend(M){this.processors.push(...M)}_call(M,P){let L=P;for(const le of this.processors)L=le(M,L);return L}[Symbol.iterator](){return this.processors.values()}}class _ extends I{constructor(M){super(),this.bos_token_id=M}_call(M,P){for(let L=0;L=1&&oe[oe.length-1]>=this.timestamp_begin,we=oe.length<2||oe[oe.length-2]>=this.timestamp_begin;if(Te&&(we?le.subarray(this.timestamp_begin).fill(-1/0):le.subarray(0,this.eos_token_id).fill(-1/0)),M[L].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ke=this.timestamp_begin+this.max_initial_timestamp_index;le.subarray(ke+1).fill(-1/0)}const ie=(0,T.log_softmax)(le),Pe=Math.log(ie.subarray(this.timestamp_begin).map(Math.exp).reduce((ke,Oe)=>ke+Oe)),pe=(0,T.max)(ie.subarray(0,this.timestamp_begin))[0];Pe>pe&&le.subarray(0,this.timestamp_begin).fill(-1/0)}return P}}class x extends I{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const P=M.length,L=[];for(let oe=0;oe1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,P){if(P.dims[0]!==2*M.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 ${P.dims[0]} for the logits and ${M.length} for the input ids.`);const L=M.length,le=P.slice([0,L],null),oe=P.slice([L,P.dims[0]],null);for(let Te=0;Te1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(L)||L<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${L}`);this.top_p=M,this.filter_value=P,this.min_tokens_to_keep=L}}class D extends U{constructor(M,{filter_value:P=-1/0,min_tokens_to_keep:L=1}={}){if(super(),!Number.isInteger(M)||M<0)throw new Error(`\`top_k\` must be a positive integer, but is ${M}`);this.top_k=Math.max(M,L),this.filter_value=P}}},"./src/generation/logits_sampler.js":(R,c,s)=>{s.r(c),s.d(c,{LogitsSampler:()=>U});var h=s("./src/utils/generic.js"),T=s("./src/utils/tensor.js"),I=s("./src/utils/maths.js");s("./src/generation/configuration_utils.js");class U extends h.Callable{constructor(b){super(),this.generation_config=b}async _call(b){return this.sample(b)}async sample(b){throw Error("sample should be implemented in subclasses.")}getLogits(b,x){let O=b.dims.at(-1),H=b.data;if(x===-1)H=H.slice(-O);else{let re=x*O;H=H.slice(re,re+O)}return H}randomSelect(b){let x=0;for(let H=0;H1)return new v(b);if(b.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${b.num_return_sequences}.`);return new F(b)}}class F extends U{async sample(b){const x=(0,I.max)(b.data)[1];return[[BigInt(x),0]]}}class _ extends U{async sample(b){let x=b.dims.at(-1);this.generation_config.top_k>0&&(x=Math.min(this.generation_config.top_k,x));const[O,H]=await(0,T.topk)(b,x),re=(0,I.softmax)(O.data);return Array.from({length:this.generation_config.num_beams},()=>{const ne=this.randomSelect(re);return[H.data[ne],Math.log(re[ne])]})}}class v extends U{async sample(b){let x=b.dims.at(-1);this.generation_config.top_k>0&&(x=Math.min(this.generation_config.top_k,x));const[O,H]=await(0,T.topk)(b,x),re=(0,I.softmax)(O.data);return Array.from({length:this.generation_config.num_beams},(ne,G)=>[H.data[G],Math.log(re[G])])}}},"./src/generation/stopping_criteria.js":(R,c,s)=>{s.r(c),s.d(c,{EosTokenCriteria:()=>F,InterruptableStoppingCriteria:()=>_,MaxLengthCriteria:()=>U,StoppingCriteria:()=>T,StoppingCriteriaList:()=>I});var h=s("./src/utils/generic.js");class T extends h.Callable{_call(w,b){throw Error("StoppingCriteria needs to be subclassed")}}class I extends h.Callable{constructor(){super(),this.criteria=[]}push(w){this.criteria.push(w)}extend(w){w instanceof I?w=w.criteria:w instanceof T&&(w=[w]),this.criteria.push(...w)}_call(w,b){const x=new Array(w.length).fill(!1);for(const O of this.criteria){const H=O(w,b);for(let re=0;reb.length>=this.max_length)}}class F extends T{constructor(w){super(),Array.isArray(w)||(w=[w]),this.eos_token_id=w}_call(w,b){return w.map(x=>{const O=x.at(-1);return this.eos_token_id.some(H=>O==H)})}}class _ extends T{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(w,b){return new Array(w.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(R,c,s)=>{s.r(c),s.d(c,{BaseStreamer:()=>U,TextStreamer:()=>_,WhisperTextStreamer:()=>v});var h=s("./src/utils/core.js"),T=s("./src/tokenizers.js"),I=s("./src/env.js");class U{put(b){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const F=I.apis.IS_PROCESS_AVAILABLE?w=>process.stdout.write(w):w=>console.log(w);class _ extends U{constructor(b,{skip_prompt:x=!1,callback_function:O=null,token_callback_function:H=null,skip_special_tokens:re=!0,decode_kwargs:ne={},...G}={}){super(),this.tokenizer=b,this.skip_prompt=x,this.callback_function=O??F,this.token_callback_function=H,this.decode_kwargs={skip_special_tokens:re,...ne,...G},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(b){var re;if(b.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 x=b[0];(re=this.token_callback_function)==null||re.call(this,x),this.token_cache=(0,h.mergeArrays)(this.token_cache,x);const O=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let H;O.endsWith(` +`)?(H=O.slice(this.print_len),this.token_cache=[],this.print_len=0):O.length>0&&(0,T.is_chinese_char)(O.charCodeAt(O.length-1))?(H=O.slice(this.print_len),this.print_len+=H.length):(H=O.slice(this.print_len,O.lastIndexOf(" ")+1),this.print_len+=H.length),this.on_finalized_text(H,!1)}end(){let b;this.token_cache.length>0?(b=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):b="",this.next_tokens_are_prompt=!0,this.on_finalized_text(b,!0)}on_finalized_text(b,x){var O,H;b.length>0&&((O=this.callback_function)==null||O.call(this,b)),x&&this.callback_function===F&&I.apis.IS_PROCESS_AVAILABLE&&((H=this.callback_function)==null||H.call(this,` +`))}}class v extends _{constructor(b,{skip_prompt:x=!1,callback_function:O=null,token_callback_function:H=null,on_chunk_start:re=null,on_chunk_end:ne=null,on_finalize:G=null,time_precision:W=.02,skip_special_tokens:X=!0,decode_kwargs:D={}}={}){super(b,{skip_prompt:x,skip_special_tokens:X,callback_function:O,token_callback_function:H,decode_kwargs:D}),this.timestamp_begin=b.timestamp_begin,this.on_chunk_start=re,this.on_chunk_end=ne,this.on_finalize=G,this.time_precision=W,this.waiting_for_timestamp=!1}put(b){var O,H;if(b.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const x=b[0];if(x.length===1){const re=Number(x[0])-this.timestamp_begin;if(re>=0){const ne=re*this.time_precision;this.waiting_for_timestamp?(O=this.on_chunk_end)==null||O.call(this,ne):(H=this.on_chunk_start)==null||H.call(this,ne),this.waiting_for_timestamp=!this.waiting_for_timestamp,b=[[]]}}return super.put(b)}end(){var b;super.end(),(b=this.on_finalize)==null||b.call(this)}}},"./src/models.js":(R,c,s)=>{s.r(c),s.d(c,{ASTForAudioClassification:()=>Xi,ASTModel:()=>Xa,ASTPreTrainedModel:()=>Jt,AlbertForMaskedLM:()=>os,AlbertForQuestionAnswering:()=>Kn,AlbertForSequenceClassification:()=>kn,AlbertModel:()=>Gn,AlbertPreTrainedModel:()=>Xr,AutoModel:()=>Fa,AutoModelForAudioClassification:()=>Cc,AutoModelForAudioFrameClassification:()=>$c,AutoModelForCTC:()=>Ec,AutoModelForCausalLM:()=>_c,AutoModelForDepthEstimation:()=>Ac,AutoModelForDocumentQuestionAnswering:()=>zp,AutoModelForImageClassification:()=>bc,AutoModelForImageFeatureExtraction:()=>Fc,AutoModelForImageMatting:()=>kc,AutoModelForImageSegmentation:()=>Mc,AutoModelForImageToImage:()=>Ic,AutoModelForMaskGeneration:()=>Pc,AutoModelForMaskedLM:()=>gc,AutoModelForNormalEstimation:()=>Bp,AutoModelForObjectDetection:()=>xc,AutoModelForPoseEstimation:()=>Oc,AutoModelForQuestionAnswering:()=>yc,AutoModelForSemanticSegmentation:()=>vc,AutoModelForSeq2SeqLM:()=>hc,AutoModelForSequenceClassification:()=>Lp,AutoModelForSpeechSeq2Seq:()=>mc,AutoModelForTextToSpectrogram:()=>Da,AutoModelForTextToWaveform:()=>fc,AutoModelForTokenClassification:()=>pc,AutoModelForUniversalSegmentation:()=>La,AutoModelForVision2Seq:()=>wc,AutoModelForXVector:()=>Sc,AutoModelForZeroShotObjectDetection:()=>Tc,BartForConditionalGeneration:()=>Kt,BartForSequenceClassification:()=>fs,BartModel:()=>Tt,BartPretrainedModel:()=>ft,BaseModelOutput:()=>Ue,BeitForImageClassification:()=>dn,BeitModel:()=>un,BeitPreTrainedModel:()=>xu,BertForMaskedLM:()=>Ve,BertForQuestionAnswering:()=>je,BertForSequenceClassification:()=>We,BertForTokenClassification:()=>Ne,BertModel:()=>ve,BertPreTrainedModel:()=>ue,BlenderbotForConditionalGeneration:()=>rr,BlenderbotModel:()=>ze,BlenderbotPreTrainedModel:()=>Gs,BlenderbotSmallForConditionalGeneration:()=>er,BlenderbotSmallModel:()=>ks,BlenderbotSmallPreTrainedModel:()=>zr,BloomForCausalLM:()=>Yl,BloomModel:()=>Xl,BloomPreTrainedModel:()=>$o,CLIPModel:()=>ll,CLIPPreTrainedModel:()=>ln,CLIPSegForImageSegmentation:()=>fl,CLIPSegModel:()=>ml,CLIPSegPreTrainedModel:()=>ro,CLIPTextModel:()=>Jc,CLIPTextModelWithProjection:()=>ul,CLIPVisionModel:()=>Zc,CLIPVisionModelWithProjection:()=>dl,CamembertForMaskedLM:()=>rn,CamembertForQuestionAnswering:()=>nn,CamembertForSequenceClassification:()=>Or,CamembertForTokenClassification:()=>Fr,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>Cr,CausalLMOutput:()=>fn,CausalLMOutputWithPast:()=>Np,ChineseCLIPModel:()=>Mr,ChineseCLIPPreTrainedModel:()=>ep,ClapAudioModelWithProjection:()=>Pd,ClapModel:()=>ur,ClapPreTrainedModel:()=>_a,ClapTextModelWithProjection:()=>Td,CodeGenForCausalLM:()=>Cl,CodeGenModel:()=>co,CodeGenPreTrainedModel:()=>fi,CohereForCausalLM:()=>zl,CohereModel:()=>Ll,CoherePreTrainedModel:()=>vo,ConvBertForMaskedLM:()=>St,ConvBertForQuestionAnswering:()=>Ms,ConvBertForSequenceClassification:()=>kt,ConvBertForTokenClassification:()=>is,ConvBertModel:()=>vt,ConvBertPreTrainedModel:()=>ct,ConvNextForImageClassification:()=>ia,ConvNextModel:()=>Bu,ConvNextPreTrainedModel:()=>na,ConvNextV2ForImageClassification:()=>aa,ConvNextV2Model:()=>Ru,ConvNextV2PreTrainedModel:()=>oa,DPTForDepthEstimation:()=>lp,DPTModel:()=>$u,DPTPreTrainedModel:()=>ta,DebertaForMaskedLM:()=>Dr,DebertaForQuestionAnswering:()=>cr,DebertaForSequenceClassification:()=>Wr,DebertaForTokenClassification:()=>Gr,DebertaModel:()=>Vr,DebertaPreTrainedModel:()=>fr,DebertaV2ForMaskedLM:()=>Ft,DebertaV2ForQuestionAnswering:()=>Lr,DebertaV2ForSequenceClassification:()=>Ws,DebertaV2ForTokenClassification:()=>Kr,DebertaV2Model:()=>xt,DebertaV2PreTrainedModel:()=>it,DecisionTransformerModel:()=>Cp,DecisionTransformerPreTrainedModel:()=>Bd,DeiTForImageClassification:()=>Ho,DeiTModel:()=>Eu,DeiTPreTrainedModel:()=>Mi,DepthAnythingForDepthEstimation:()=>Iu,DepthAnythingPreTrainedModel:()=>ku,DepthProForDepthEstimation:()=>ra,DepthProPreTrainedModel:()=>Ti,DetrForObjectDetection:()=>cn,DetrForSegmentation:()=>Hs,DetrModel:()=>jo,DetrObjectDetectionOutput:()=>Uo,DetrPreTrainedModel:()=>Br,DetrSegmentationOutput:()=>Vo,Dinov2ForImageClassification:()=>cp,Dinov2Model:()=>Nu,Dinov2PreTrainedModel:()=>la,Dinov2WithRegistersForImageClassification:()=>Uu,Dinov2WithRegistersModel:()=>ju,Dinov2WithRegistersPreTrainedModel:()=>ua,DistilBertForMaskedLM:()=>Tn,DistilBertForQuestionAnswering:()=>ss,DistilBertForSequenceClassification:()=>Fs,DistilBertForTokenClassification:()=>Sr,DistilBertModel:()=>pr,DistilBertPreTrainedModel:()=>vs,DonutSwinModel:()=>zu,DonutSwinPreTrainedModel:()=>dp,EfficientNetForImageClassification:()=>Id,EfficientNetModel:()=>kd,EfficientNetPreTrainedModel:()=>Oi,ElectraForMaskedLM:()=>ar,ElectraForQuestionAnswering:()=>Vs,ElectraForSequenceClassification:()=>Ar,ElectraForTokenClassification:()=>sn,ElectraModel:()=>zs,ElectraPreTrainedModel:()=>$s,EsmForMaskedLM:()=>Bn,EsmForSequenceClassification:()=>Rn,EsmForTokenClassification:()=>Nn,EsmModel:()=>di,EsmPreTrainedModel:()=>Hr,ExaoneForCausalLM:()=>go,ExaoneModel:()=>kl,ExaonePreTrainedModel:()=>_o,FalconForCausalLM:()=>xd,FalconModel:()=>vd,FalconPreTrainedModel:()=>fa,FastViTForImageClassification:()=>hu,FastViTModel:()=>pu,FastViTPreTrainedModel:()=>Lo,Florence2ForConditionalGeneration:()=>rl,Florence2PreTrainedModel:()=>sl,GLPNForDepthEstimation:()=>Lu,GLPNModel:()=>up,GLPNPreTrainedModel:()=>Ei,GPT2LMHeadModel:()=>gl,GPT2Model:()=>_l,GPT2PreTrainedModel:()=>no,GPTBigCodeForCausalLM:()=>El,GPTBigCodeModel:()=>Pl,GPTBigCodePreTrainedModel:()=>uo,GPTJForCausalLM:()=>Tl,GPTJModel:()=>xl,GPTJPreTrainedModel:()=>lo,GPTNeoForCausalLM:()=>bl,GPTNeoModel:()=>xr,GPTNeoPreTrainedModel:()=>oo,GPTNeoXForCausalLM:()=>vl,GPTNeoXModel:()=>Ml,GPTNeoXPreTrainedModel:()=>ao,Gemma2ForCausalLM:()=>jl,Gemma2Model:()=>Nl,Gemma2PreTrainedModel:()=>To,GemmaForCausalLM:()=>Rl,GemmaModel:()=>Bl,GemmaPreTrainedModel:()=>xo,GlmForCausalLM:()=>Hn,GlmModel:()=>$l,GlmPreTrainedModel:()=>fo,GraniteForCausalLM:()=>Dl,GraniteModel:()=>ds,GranitePreTrainedModel:()=>Mo,GroundingDinoForObjectDetection:()=>Vu,GroundingDinoPreTrainedModel:()=>pp,GroupViTModel:()=>Tr,GroupViTPreTrainedModel:()=>cu,HeliumForCausalLM:()=>Sl,HeliumModel:()=>_i,HeliumPreTrainedModel:()=>mo,HieraForImageClassification:()=>Qo,HieraModel:()=>vi,HieraPreTrainedModel:()=>qo,HubertForCTC:()=>dd,HubertForSequenceClassification:()=>bp,HubertModel:()=>ud,HubertPreTrainedModel:()=>wp,IJepaForImageClassification:()=>nu,IJepaModel:()=>ru,IJepaPreTrainedModel:()=>wi,Idefics3ForConditionalGeneration:()=>eo,Idefics3PreTrainedModel:()=>ol,ImageMattingOutput:()=>Lc,JAISLMHeadModel:()=>wl,JAISModel:()=>yl,JAISPreTrainedModel:()=>io,JinaCLIPModel:()=>mi,JinaCLIPPreTrainedModel:()=>hi,JinaCLIPTextModel:()=>so,JinaCLIPVisionModel:()=>vr,LlamaForCausalLM:()=>tp,LlamaModel:()=>ho,LlamaPreTrainedModel:()=>po,LlavaForConditionalGeneration:()=>pi,LlavaOnevisionForConditionalGeneration:()=>el,LlavaPreTrainedModel:()=>Yr,LongT5ForConditionalGeneration:()=>Ie,LongT5Model:()=>xe,LongT5PreTrainedModel:()=>de,M2M100ForConditionalGeneration:()=>pa,M2M100Model:()=>Qu,M2M100PreTrainedModel:()=>ca,MBartForCausalLM:()=>lr,MBartForConditionalGeneration:()=>zt,MBartForSequenceClassification:()=>rs,MBartModel:()=>Ds,MBartPreTrainedModel:()=>us,MPNetForMaskedLM:()=>on,MPNetForQuestionAnswering:()=>Sn,MPNetForSequenceClassification:()=>En,MPNetForTokenClassification:()=>Cn,MPNetModel:()=>Pn,MPNetPreTrainedModel:()=>hr,MT5ForConditionalGeneration:()=>gt,MT5Model:()=>ht,MT5PreTrainedModel:()=>Xe,MarianMTModel:()=>qu,MarianModel:()=>Hu,MarianPreTrainedModel:()=>Si,MaskFormerForInstanceSegmentation:()=>Du,MaskFormerModel:()=>Fu,MaskFormerPreTrainedModel:()=>Pi,MaskedLMOutput:()=>tr,MgpstrForSceneTextRecognition:()=>Vd,MgpstrModelOutput:()=>jd,MgpstrPreTrainedModel:()=>Ud,MistralForCausalLM:()=>wd,MistralModel:()=>yd,MistralPreTrainedModel:()=>ha,MobileBertForMaskedLM:()=>ci,MobileBertForQuestionAnswering:()=>wr,MobileBertForSequenceClassification:()=>Qr,MobileBertModel:()=>jn,MobileBertPreTrainedModel:()=>qr,MobileLLMForCausalLM:()=>Al,MobileLLMModel:()=>Il,MobileLLMPreTrainedModel:()=>yo,MobileNetV1ForImageClassification:()=>va,MobileNetV1Model:()=>Pp,MobileNetV1PreTrainedModel:()=>Ma,MobileNetV2ForImageClassification:()=>Od,MobileNetV2Model:()=>Ad,MobileNetV2PreTrainedModel:()=>xa,MobileNetV3ForImageClassification:()=>Ld,MobileNetV3Model:()=>Dd,MobileNetV3PreTrainedModel:()=>Fd,MobileNetV4ForImageClassification:()=>zd,MobileNetV4Model:()=>Ep,MobileNetV4PreTrainedModel:()=>Ta,MobileViTForImageClassification:()=>gu,MobileViTModel:()=>_u,MobileViTPreTrainedModel:()=>zo,MobileViTV2ForImageClassification:()=>ip,MobileViTV2Model:()=>yu,MobileViTV2PreTrainedModel:()=>Bo,ModelOutput:()=>Ke,ModernBertForMaskedLM:()=>pt,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>mt,ModernBertModel:()=>ut,ModernBertPreTrainedModel:()=>st,Moondream1ForConditionalGeneration:()=>tl,MoonshineForConditionalGeneration:()=>Za,MoonshineModel:()=>_r,MoonshinePreTrainedModel:()=>Ji,MptForCausalLM:()=>Zl,MptModel:()=>Jl,MptPreTrainedModel:()=>ko,MultiModalityCausalLM:()=>Nd,MultiModalityPreTrainedModel:()=>Rd,MusicgenForCausalLM:()=>Tp,MusicgenForConditionalGeneration:()=>Fi,MusicgenModel:()=>xp,MusicgenPreTrainedModel:()=>ba,NomicBertModel:()=>ae,NomicBertPreTrainedModel:()=>B,OPTForCausalLM:()=>tu,OPTModel:()=>eu,OPTPreTrainedModel:()=>Io,Olmo2ForCausalLM:()=>rp,Olmo2Model:()=>Fl,Olmo2PreTrainedModel:()=>bo,OlmoForCausalLM:()=>Ol,OlmoModel:()=>sp,OlmoPreTrainedModel:()=>wo,OpenELMForCausalLM:()=>Vl,OpenELMModel:()=>Ul,OpenELMPreTrainedModel:()=>Po,OwlViTForObjectDetection:()=>bu,OwlViTModel:()=>wu,OwlViTPreTrainedModel:()=>Ro,Owlv2ForObjectDetection:()=>vu,Owlv2Model:()=>Mu,Owlv2PreTrainedModel:()=>No,PaliGemmaForConditionalGeneration:()=>il,PaliGemmaPreTrainedModel:()=>nl,PatchTSMixerForPrediction:()=>qd,PatchTSMixerModel:()=>Hd,PatchTSMixerPreTrainedModel:()=>Pa,PatchTSTForPrediction:()=>Kd,PatchTSTModel:()=>Gd,PatchTSTPreTrainedModel:()=>Wd,Phi3ForCausalLM:()=>Ql,Phi3Model:()=>ql,Phi3PreTrainedModel:()=>So,Phi3VForCausalLM:()=>gr,Phi3VPreTrainedModel:()=>al,PhiForCausalLM:()=>Hl,PhiModel:()=>Kl,PhiPreTrainedModel:()=>Co,PreTrainedModel:()=>se,PretrainedMixin:()=>ws,PvtForImageClassification:()=>Fo,PvtModel:()=>au,PvtPreTrainedModel:()=>Oo,PyAnnoteForAudioFrameClassification:()=>ed,PyAnnoteModel:()=>Zu,PyAnnotePreTrainedModel:()=>$i,QuestionAnsweringModelOutput:()=>nr,Qwen2ForCausalLM:()=>Wl,Qwen2Model:()=>qn,Qwen2PreTrainedModel:()=>Eo,Qwen2VLForConditionalGeneration:()=>Gl,Qwen2VLPreTrainedModel:()=>gi,RTDetrForObjectDetection:()=>Qn,RTDetrModel:()=>op,RTDetrObjectDetectionOutput:()=>Go,RTDetrPreTrainedModel:()=>Wo,ResNetForImageClassification:()=>ap,ResNetModel:()=>Cu,ResNetPreTrainedModel:()=>Xo,RoFormerForMaskedLM:()=>$e,RoFormerForQuestionAnswering:()=>at,RoFormerForSequenceClassification:()=>Re,RoFormerForTokenClassification:()=>qe,RoFormerModel:()=>me,RoFormerPreTrainedModel:()=>q,RobertaForMaskedLM:()=>br,RobertaForQuestionAnswering:()=>bt,RobertaForSequenceClassification:()=>_s,RobertaForTokenClassification:()=>Is,RobertaModel:()=>dr,RobertaPreTrainedModel:()=>Ot,SamImageSegmentationOutput:()=>Yn,SamModel:()=>Ci,SamPreTrainedModel:()=>hp,SapiensForDepthEstimation:()=>xi,SapiensForNormalEstimation:()=>Ou,SapiensForSemanticSegmentation:()=>Au,SapiensPreTrainedModel:()=>sa,SegformerForImageClassification:()=>Ed,SegformerForSemanticSegmentation:()=>Cd,SegformerModel:()=>vp,SegformerPreTrainedModel:()=>mn,Seq2SeqLMOutput:()=>Rp,SequenceClassifierOutput:()=>Zt,SiglipModel:()=>cl,SiglipPreTrainedModel:()=>to,SiglipTextModel:()=>pl,SiglipVisionModel:()=>hl,SpeechT5ForSpeechToText:()=>$r,SpeechT5ForTextToSpeech:()=>Rr,SpeechT5HifiGan:()=>pn,SpeechT5Model:()=>uh,SpeechT5PreTrainedModel:()=>Ai,SqueezeBertForMaskedLM:()=>Un,SqueezeBertForQuestionAnswering:()=>Wn,SqueezeBertForSequenceClassification:()=>Vn,SqueezeBertModel:()=>$n,SqueezeBertPreTrainedModel:()=>Lt,StableLmForCausalLM:()=>$d,StableLmModel:()=>Sd,StableLmPreTrainedModel:()=>wa,Starcoder2ForCausalLM:()=>Md,Starcoder2Model:()=>bd,Starcoder2PreTrainedModel:()=>ma,StyleTextToSpeech2Model:()=>_d,StyleTextToSpeech2PreTrainedModel:()=>fd,Swin2SRForImageSuperResolution:()=>Su,Swin2SRModel:()=>ea,Swin2SRPreTrainedModel:()=>Zo,SwinForImageClassification:()=>Xn,SwinModel:()=>Jo,SwinPreTrainedModel:()=>Yo,T5ForConditionalGeneration:()=>Y,T5Model:()=>C,T5PreTrainedModel:()=>Ee,TableTransformerForObjectDetection:()=>Pu,TableTransformerModel:()=>Tu,TableTransformerObjectDetectionOutput:()=>Ko,TableTransformerPreTrainedModel:()=>bi,TokenClassifierOutput:()=>Ls,TrOCRForCausalLM:()=>gd,TrOCRPreTrainedModel:()=>hn,UniSpeechForCTC:()=>_p,UniSpeechForSequenceClassification:()=>rd,UniSpeechModel:()=>sd,UniSpeechPreTrainedModel:()=>ki,UniSpeechSatForAudioFrameClassification:()=>od,UniSpeechSatForCTC:()=>id,UniSpeechSatForSequenceClassification:()=>gp,UniSpeechSatModel:()=>nd,UniSpeechSatPreTrainedModel:()=>Jn,ViTForImageClassification:()=>Ao,ViTMAEModel:()=>uu,ViTMAEPreTrainedModel:()=>lu,ViTMSNForImageClassification:()=>du,ViTMSNModel:()=>np,ViTMSNPreTrainedModel:()=>Do,ViTModel:()=>su,ViTPreTrainedModel:()=>yi,VisionEncoderDecoderModel:()=>Zi,VitMatteForImageMatting:()=>fu,VitMattePreTrainedModel:()=>mu,VitPoseForPoseEstimation:()=>ou,VitPosePreTrainedModel:()=>iu,VitsModel:()=>ya,VitsModelOutput:()=>zc,VitsPreTrainedModel:()=>ga,Wav2Vec2BertForCTC:()=>yp,Wav2Vec2BertForSequenceClassification:()=>ld,Wav2Vec2BertModel:()=>ad,Wav2Vec2BertPreTrainedModel:()=>Ii,Wav2Vec2ForAudioFrameClassification:()=>Ju,Wav2Vec2ForCTC:()=>Yu,Wav2Vec2ForSequenceClassification:()=>mp,Wav2Vec2Model:()=>Xu,Wav2Vec2PreTrainedModel:()=>Jr,WavLMForAudioFrameClassification:()=>md,WavLMForCTC:()=>pd,WavLMForSequenceClassification:()=>hd,WavLMForXVector:()=>Mp,WavLMModel:()=>cd,WavLMPreTrainedModel:()=>In,WeSpeakerResNetModel:()=>fp,WeSpeakerResNetPreTrainedModel:()=>td,WhisperForConditionalGeneration:()=>Ja,WhisperModel:()=>Ya,WhisperPreTrainedModel:()=>Yi,XLMForQuestionAnswering:()=>an,XLMForSequenceClassification:()=>Ks,XLMForTokenClassification:()=>$t,XLMModel:()=>Bs,XLMPreTrainedModel:()=>Xt,XLMRobertaForMaskedLM:()=>Ha,XLMRobertaForQuestionAnswering:()=>Qa,XLMRobertaForSequenceClassification:()=>Qi,XLMRobertaForTokenClassification:()=>qa,XLMRobertaModel:()=>It,XLMRobertaPreTrainedModel:()=>Qe,XLMWithLMHeadModel:()=>As,XVectorOutput:()=>Dc,YolosForObjectDetection:()=>Gu,YolosModel:()=>Wu,YolosObjectDetectionOutput:()=>Ku,YolosPreTrainedModel:()=>da});var h=s("./src/configs.js"),T=s("./src/backends/onnx.js"),I=s("./src/utils/dtypes.js"),U=s("./src/utils/generic.js"),F=s("./src/utils/core.js"),_=s("./src/utils/hub.js"),v=s("./src/utils/constants.js"),w=s("./src/generation/logits_process.js"),b=s("./src/generation/configuration_utils.js"),x=s("./src/utils/tensor.js"),O=s("./src/utils/image.js"),H=s("./src/utils/maths.js"),re=s("./src/generation/stopping_criteria.js"),ne=s("./src/generation/logits_sampler.js"),G=s("./src/env.js"),W=s("./src/models/whisper/generation_whisper.js"),X=s("./src/models/whisper/common_whisper.js");const D={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},A=new Map,M=new Map,P=new Map;async function L(y,E,V){var Ts;const ge=((Ts=V.config)==null?void 0:Ts["transformers.js_config"])??{};let Fe=V.device??ge.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(E)?Fe=Fe[E]:(console.warn(`device not specified for "${E}". Using the default device.`),Fe=null));const De=Fe??(G.apis.IS_NODE_ENV?"cpu":"wasm"),Ze=(0,T.deviceToExecutionProviders)(De);let rt=V.dtype??ge.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(E)?rt=rt[E]:(rt=I.DEFAULT_DEVICE_DTYPE_MAPPING[De]??I.DATA_TYPES.fp32,console.warn(`dtype not specified for "${E}". Using the default dtype (${rt}) for this device (${De}).`))),rt===I.DATA_TYPES.auto){let cs=ge.dtype;typeof cs!="string"&&(cs=cs[E]),cs&&cs!==I.DATA_TYPES.auto&&I.DATA_TYPES.hasOwnProperty(cs)?rt=cs:rt=I.DEFAULT_DEVICE_DTYPE_MAPPING[De]??I.DATA_TYPES.fp32}const _t=rt;if(I.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(_t)){if(_t===I.DATA_TYPES.fp16&&De==="webgpu"&&!await(0,I.isWebGpuFp16Supported)())throw new Error(`The device (${De}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_t}. Should be one of: ${Object.keys(I.DATA_TYPES).join(", ")}`);const Mt=ge.kv_cache_dtype?typeof ge.kv_cache_dtype=="string"?ge.kv_cache_dtype:ge.kv_cache_dtype[_t]??"float32":void 0;if(Mt&&!["float32","float16"].includes(Mt))throw new Error(`Invalid kv_cache_dtype: ${Mt}. Should be one of: float32, float16`);const Rt={dtype:_t,kv_cache_dtype:Mt},Wt=I.DEFAULT_DTYPE_SUFFIX_MAPPING[_t],Dt=`${V.subfolder??""}/${E}${Wt}.onnx`,Gt={...V.session_options};Gt.executionProviders??(Gt.executionProviders=Ze);const es=ge.free_dimension_overrides;es?Gt.freeDimensionOverrides??(Gt.freeDimensionOverrides=es):De.startsWith("webnn")&&!Gt.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const ns=(0,_.getModelFile)(y,Dt,!0,V),Yt=V.use_external_data_format??ge.use_external_data_format;let as=[];if(Yt&&(Yt===!0||typeof Yt=="object"&&Yt.hasOwnProperty(E)&&Yt[E]===!0)){if(G.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const cs=`${E}${Wt}.onnx_data`,Ps=`${V.subfolder??""}/${cs}`;as.push(new Promise(async(Os,ir)=>{const qs=await(0,_.getModelFile)(y,Ps,!0,V);Os({path:cs,data:qs})}))}else Gt.externalData!==void 0&&(as=Gt.externalData.map(async cs=>{if(typeof cs.data=="string"){const Ps=await(0,_.getModelFile)(y,cs.data,!0,V);return{...cs,data:Ps}}return cs}));if(as.length>0&&(Gt.externalData=await Promise.all(as)),De==="webgpu"){const cs=(0,h.getKeyValueShapes)(V.config,{prefix:"present"});if(Object.keys(cs).length>0&&!(0,T.isONNXProxy)()){const Ps={};for(const Os in cs)Ps[Os]="gpu-buffer";Gt.preferredOutputLocation=Ps}}return{buffer:await ns,session_options:Gt,session_config:Rt}}async function le(y,E,V){return Object.fromEntries(await Promise.all(Object.keys(E).map(async ge=>{const{buffer:Fe,session_options:De,session_config:Ze}=await L(y,E[ge],V),rt=await(0,T.createInferenceSession)(Fe,De,Ze);return[ge,rt]})))}async function oe(y,E,V){return Object.fromEntries(await Promise.all(Object.keys(E).map(async ge=>{const Fe=await(0,_.getModelJSON)(y,E[ge],!1,V);return[ge,Fe]})))}function Te(y,E){const V=Object.create(null),ge=[];for(const Ze of y.inputNames){const rt=E[Ze];if(!(rt instanceof x.Tensor)){ge.push(Ze);continue}V[Ze]=(0,T.isONNXProxy)()?rt.clone():rt}if(ge.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ge.join(", ")}.`);const Fe=Object.keys(E).length,De=y.inputNames.length;if(Fe>De){let Ze=Object.keys(E).filter(rt=>!y.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${De}). The following inputs will be ignored: "${Ze.join(", ")}".`)}return V}async function we(y,E){const V=Te(y,E);try{const ge=Object.fromEntries(Object.entries(V).map(([De,Ze])=>[De,Ze.ort_tensor]));let Fe=await y.run(ge);return Fe=ie(Fe),Fe}catch(ge){const Fe=Object.fromEntries(Object.entries(V).map(([De,{type:Ze,dims:rt,data:_t}])=>[De,{type:Ze,dims:rt,data:_t}]));throw console.error(`An error occurred during model execution: "${ge}".`),console.error("Inputs given to model:",Fe),ge}}function ie(y){for(let E in y)(0,T.isONNXTensor)(y[E])?y[E]=new x.Tensor(y[E]):typeof y[E]=="object"&&ie(y[E]);return y}function Pe(y){if(y instanceof x.Tensor)return y;if(y.length===0)throw Error("items must be non-empty");if(Array.isArray(y[0])){if(y.some(E=>E.length!==y[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 x.Tensor("int64",BigInt64Array.from(y.flat().map(E=>BigInt(E))),[y.length,y[0].length])}else return new x.Tensor("int64",BigInt64Array.from(y.map(E=>BigInt(E))),[1,y.length])}function pe(y){return new x.Tensor("bool",[y],[1])}async function ke(y,E){let{encoder_outputs:V,input_ids:ge,decoder_input_ids:Fe,...De}=E;if(!V){const rt=(0,F.pick)(E,y.sessions.model.inputNames);V=(await Oe(y,rt)).last_hidden_state}return De.input_ids=Fe,De.encoder_hidden_states=V,y.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(De.encoder_attention_mask=E.attention_mask),await Ce(y,De,!0)}async function Oe(y,E){const V=y.sessions.model,ge=(0,F.pick)(E,V.inputNames);if(V.inputNames.includes("inputs_embeds")&&!ge.inputs_embeds){if(!E.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ge.inputs_embeds=await y.encode_text({input_ids:E.input_ids})}if(V.inputNames.includes("token_type_ids")&&!ge.token_type_ids){if(!ge.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ge.token_type_ids=(0,x.zeros_like)(ge.input_ids)}if(V.inputNames.includes("pixel_mask")&&!ge.pixel_mask){if(!ge.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Fe=ge.pixel_values.dims;ge.pixel_mask=(0,x.ones)([Fe[0],Fe[2],Fe[3]])}return await we(V,ge)}async function Ce(y,E,V=!1){const ge=y.sessions[V?"decoder_model_merged":"model"],{past_key_values:Fe,...De}=E;if(ge.inputNames.includes("use_cache_branch")&&(De.use_cache_branch=pe(!!Fe)),ge.inputNames.includes("position_ids")&&De.attention_mask&&!De.position_ids){const rt=y.config.model_type==="paligemma"?1:0;De.position_ids=Z(De,Fe,rt)}y.addPastKeyValues(De,Fe);const Ze=(0,F.pick)(De,ge.inputNames);return await we(ge,Ze)}function tt({image_token_id:y,inputs_embeds:E,image_features:V,input_ids:ge,attention_mask:Fe}){const De=ge.tolist().map(Mt=>Mt.reduce((Rt,Wt,Dt)=>(Wt==y&&Rt.push(Dt),Rt),[])),Ze=De.reduce((Mt,Rt)=>Mt+Rt.length,0),rt=V.dims[0];if(Ze!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${Ze}, features ${rt}`);let _t=0;for(let Mt=0;MtDe.dims[1])){if(Fert==y.config.image_token_index)){const rt=y.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const _t=De.dims[1]-(Fe-rt);V.input_ids=De.slice(null,[-_t,null]),V.attention_mask=(0,x.ones)([1,Fe+_t])}}}return V}function Se(y,E,V,ge){return V.past_key_values&&(E=E.map(Fe=>[Fe.at(-1)])),{...V,decoder_input_ids:Pe(E)}}function Be(y,...E){return y.config.is_encoder_decoder?Se(y,...E):ce(y,...E)}function Je(y,E,V,ge){const Fe=!!V.past_key_values;return ge.guidance_scale!==null&&ge.guidance_scale>1&&(Fe?V.input_ids=(0,x.cat)([V.input_ids,V.input_ids],0):(V.input_ids=(0,x.cat)([V.input_ids,(0,x.full_like)(V.input_ids,BigInt(ge.pad_token_id))],0),V.attention_mask=(0,x.cat)([V.attention_mask,(0,x.full_like)(V.attention_mask,0n)],0))),(Fe||!V.pixel_values)&&(V.pixel_values=(0,x.full)([0,0,3,384,384],1)),Fe&&(V.images_seq_mask=new x.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),V.images_emb_mask=new x.Tensor("bool",new Array(0).fill(!1),[1,1,0])),V}class se extends U.Callable{constructor(V,ge,Fe){super();_e(this,"main_input_name","input_ids");_e(this,"forward_params",["input_ids","attention_mask"]);this.config=V,this.sessions=ge,this.configs=Fe;const De=P.get(this.constructor),Ze=A.get(De);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ze){case D.DecoderOnly:this.can_generate=!0,this._forward=Ce,this._prepare_inputs_for_generation=ce;break;case D.Seq2Seq:case D.Vision2Seq:case D.Musicgen:this.can_generate=!0,this._forward=ke,this._prepare_inputs_for_generation=Se;break;case D.EncoderDecoder:this._forward=ke;break;case D.ImageTextToText:this.can_generate=!0,this._forward=Ge,this._prepare_inputs_for_generation=Be;break;case D.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Be;break;case D.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Je;break;default:this._forward=Oe;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ge;const V=[];for(const Fe of Object.values(this.sessions))(ge=Fe==null?void 0:Fe.handler)!=null&&ge.dispose&&V.push(Fe.handler.dispose());return await Promise.all(V)}static async from_pretrained(V,{progress_callback:ge=null,config:Fe=null,cache_dir:De=null,local_files_only:Ze=!1,revision:rt="main",model_file_name:_t=null,subfolder:Mt="onnx",device:Rt=null,dtype:Wt=null,use_external_data_format:Dt=null,session_options:Gt={}}={}){let es={progress_callback:ge,config:Fe,cache_dir:De,local_files_only:Ze,revision:rt,model_file_name:_t,subfolder:Mt,device:Rt,dtype:Wt,use_external_data_format:Dt,session_options:Gt};const ns=P.get(this),Yt=A.get(ns);Fe=es.config=await h.AutoConfig.from_pretrained(V,es);let as;if(Yt===D.DecoderOnly)as=await Promise.all([le(V,{model:es.model_file_name??"model"},es),oe(V,{generation_config:"generation_config.json"},es)]);else if(Yt===D.Seq2Seq||Yt===D.Vision2Seq)as=await Promise.all([le(V,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es),oe(V,{generation_config:"generation_config.json"},es)]);else if(Yt===D.MaskGeneration)as=await Promise.all([le(V,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},es)]);else if(Yt===D.EncoderDecoder)as=await Promise.all([le(V,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es)]);else if(Yt===D.ImageTextToText){const Es={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(Es.model="encoder_model"),as=await Promise.all([le(V,Es,es),oe(V,{generation_config:"generation_config.json"},es)])}else if(Yt===D.Musicgen)as=await Promise.all([le(V,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},es),oe(V,{generation_config:"generation_config.json"},es)]);else if(Yt===D.MultiModality)as=await Promise.all([le(V,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},es),oe(V,{generation_config:"generation_config.json"},es)]);else if(Yt===D.Phi3V)as=await Promise.all([le(V,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},es),oe(V,{generation_config:"generation_config.json"},es)]);else{if(Yt!==D.EncoderOnly){const Es=ns??(Fe==null?void 0:Fe.model_type);Es!=="custom"&&console.warn(`Model type for '${Es}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}as=await Promise.all([le(V,{model:es.model_file_name??"model"},es)])}return new this(Fe,...as)}async _call(V){return await this.forward(V)}async forward(V){return await this._forward(this,V)}get generation_config(){var V;return((V=this.configs)==null?void 0:V.generation_config)??null}_get_logits_warper(V){const ge=new w.LogitsProcessorList;return V.temperature!==null&&V.temperature!==1&&ge.push(new w.TemperatureLogitsWarper(V.temperature)),V.top_k!==null&&V.top_k!==0&&ge.push(new w.TopKLogitsWarper(V.top_k)),V.top_p!==null&&V.top_p<1&&ge.push(new w.TopPLogitsWarper(V.top_p)),ge}_get_logits_processor(V,ge,Fe=null){const De=new w.LogitsProcessorList;if(V.repetition_penalty!==null&&V.repetition_penalty!==1&&De.push(new w.RepetitionPenaltyLogitsProcessor(V.repetition_penalty)),V.no_repeat_ngram_size!==null&&V.no_repeat_ngram_size>0&&De.push(new w.NoRepeatNGramLogitsProcessor(V.no_repeat_ngram_size)),V.bad_words_ids!==null&&De.push(new w.NoBadWordsLogitsProcessor(V.bad_words_ids,V.eos_token_id)),V.min_length!==null&&V.eos_token_id!==null&&V.min_length>0&&De.push(new w.MinLengthLogitsProcessor(V.min_length,V.eos_token_id)),V.min_new_tokens!==null&&V.eos_token_id!==null&&V.min_new_tokens>0&&De.push(new w.MinNewTokensLengthLogitsProcessor(ge,V.min_new_tokens,V.eos_token_id)),V.forced_bos_token_id!==null&&De.push(new w.ForcedBOSTokenLogitsProcessor(V.forced_bos_token_id)),V.forced_eos_token_id!==null&&De.push(new w.ForcedEOSTokenLogitsProcessor(V.max_length,V.forced_eos_token_id)),V.begin_suppress_tokens!==null){const Ze=ge>1||V.forced_bos_token_id===null?ge:ge+1;De.push(new w.SuppressTokensAtBeginLogitsProcessor(V.begin_suppress_tokens,Ze))}return V.guidance_scale!==null&&V.guidance_scale>1&&De.push(new w.ClassifierFreeGuidanceLogitsProcessor(V.guidance_scale)),Fe!==null&&De.extend(Fe),De}_prepare_generation_config(V,ge,Fe=b.GenerationConfig){const De={...this.config};for(const rt of["decoder","generator","text_config"])rt in De&&Object.assign(De,De[rt]);const Ze=new Fe(De);return Object.assign(Ze,this.generation_config??{}),V&&Object.assign(Ze,V),ge&&Object.assign(Ze,(0,F.pick)(ge,Object.getOwnPropertyNames(Ze))),Ze}_get_stopping_criteria(V,ge=null){const Fe=new re.StoppingCriteriaList;return V.max_length!==null&&Fe.push(new re.MaxLengthCriteria(V.max_length,this.config.max_position_embeddings??null)),V.eos_token_id!==null&&Fe.push(new re.EosTokenCriteria(V.eos_token_id)),ge&&Fe.extend(ge),Fe}_validate_model_class(){if(!this.can_generate){const V=[$a,Aa,Di,Qd],ge=P.get(this.constructor),Fe=new Set,De=this.config.model_type;for(const rt of V){const _t=rt.get(De);_t&&Fe.add(_t[0])}let Ze=`The current model class (${ge}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(Ze+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(Ze)}}prepare_inputs_for_generation(...V){return this._prepare_inputs_for_generation(this,...V)}_update_model_kwargs_for_generation({generated_input_ids:V,outputs:ge,model_inputs:Fe,is_encoder_decoder:De}){return Fe.past_key_values=this.getPastKeyValues(ge,Fe.past_key_values),Fe.input_ids=new x.Tensor("int64",V.flat(),[V.length,1]),De||(Fe.attention_mask=(0,x.cat)([Fe.attention_mask,(0,x.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:V,bos_token_id:ge,model_kwargs:Fe}){const De=(0,F.pick)(Fe,this.forward_params),Ze=this.main_input_name;if(Ze in De){if(V)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else De[Ze]=V;return{inputs_tensor:De[Ze],model_inputs:De,model_input_name:Ze}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:V,model_inputs:ge,model_input_name:Fe,generation_config:De}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ge.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:_t,attention_mask:Mt,...Rt}=ge,Wt=await this._prepare_inputs_embeds(ge);ge={...Rt,...(0,F.pick)(Wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ze}=await Oe(this,ge);if(De.guidance_scale!==null&&De.guidance_scale>1)Ze=(0,x.cat)([Ze,(0,x.full_like)(Ze,0)],0),"attention_mask"in ge&&(ge.attention_mask=(0,x.cat)([ge.attention_mask,(0,x.zeros_like)(ge.attention_mask)],0));else if(ge.decoder_input_ids){const rt=Pe(ge.decoder_input_ids).dims[0];if(rt!==Ze.dims[0]){if(Ze.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ze.dims[0]}) than the decoder inputs (${rt}).`);Ze=(0,x.cat)(Array.from({length:rt},()=>Ze),0)}}return ge.encoder_outputs=Ze,ge}_prepare_decoder_input_ids_for_generation({batch_size:V,model_input_name:ge,model_kwargs:Fe,decoder_start_token_id:De,bos_token_id:Ze,generation_config:rt}){let{decoder_input_ids:_t,...Mt}=Fe;if(!(_t instanceof x.Tensor)){if(_t)Array.isArray(_t[0])||(_t=Array.from({length:V},()=>_t));else if(De??(De=Ze),this.config.model_type==="musicgen")_t=Array.from({length:V*this.config.decoder.num_codebooks},()=>[De]);else if(Array.isArray(De)){if(De.length!==V)throw new Error(`\`decoder_start_token_id\` expcted to have length ${V} but got ${De.length}`);_t=De}else _t=Array.from({length:V},()=>[De]);_t=Pe(_t)}return Fe.decoder_attention_mask=(0,x.ones_like)(_t),{input_ids:_t,model_inputs:Mt}}async generate({inputs:V=null,generation_config:ge=null,logits_processor:Fe=null,stopping_criteria:De=null,streamer:Ze=null,...rt}){this._validate_model_class(),ge=this._prepare_generation_config(ge,rt);let{inputs_tensor:_t,model_inputs:Mt,model_input_name:Rt}=this._prepare_model_inputs({inputs:V,model_kwargs:rt});const Wt=this.config.is_encoder_decoder;Wt&&("encoder_outputs"in Mt||(Mt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:_t,model_inputs:Mt,model_input_name:Rt,generation_config:ge})));let Dt;Wt?{input_ids:Dt,model_inputs:Mt}=this._prepare_decoder_input_ids_for_generation({batch_size:Mt[Rt].dims.at(0),model_input_name:Rt,model_kwargs:Mt,decoder_start_token_id:ge.decoder_start_token_id,bos_token_id:ge.bos_token_id,generation_config:ge}):Dt=Mt[Rt];let Gt=Dt.dims.at(-1);ge.max_new_tokens!==null&&(ge.max_length=Gt+ge.max_new_tokens);const es=this._get_logits_processor(ge,Gt,Fe),ns=this._get_stopping_criteria(ge,De),Yt=Mt[Rt].dims.at(0),as=ne.LogitsSampler.getSampler(ge),Es=new Array(Yt).fill(0),Ts=Dt.tolist();Ze&&Ze.put(Ts);let cs,Ps={};for(;;){if(Mt=this.prepare_inputs_for_generation(Ts,Mt,ge),cs=await this.forward(Mt),ge.output_attentions&&ge.return_dict_in_generate){const mr=this.getAttentions(cs);for(const Pr in mr)Pr in Ps||(Ps[Pr]=[]),Ps[Pr].push(mr[Pr])}const qs=cs.logits.slice(null,-1,null),kr=es(Ts,qs),An=[];for(let mr=0;mrmr))break;Mt=this._update_model_kwargs_for_generation({generated_input_ids:An,outputs:cs,model_inputs:Mt,is_encoder_decoder:Wt})}Ze&&Ze.end();const Os=this.getPastKeyValues(cs,Mt.past_key_values,!0),ir=new x.Tensor("int64",Ts.flat(),[Ts.length,Ts[0].length]);if(ge.return_dict_in_generate)return{sequences:ir,past_key_values:Os,...Ps};for(const qs of Object.values(cs))qs.location==="gpu-buffer"&&qs.dispose();return ir}getPastKeyValues(V,ge,Fe=!1){const De=Object.create(null);for(const Ze in V)if(Ze.startsWith("present")){const rt=Ze.replace("present","past_key_values"),_t=Ze.includes("encoder");if(_t&&ge?De[rt]=ge[rt]:De[rt]=V[Ze],ge&&(!_t||Fe)){const Mt=ge[rt];Mt.location==="gpu-buffer"&&Mt.dispose()}}return De}getAttentions(V){const ge={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const De in V)De.startsWith(Fe)&&(Fe in ge||(ge[Fe]=[]),ge[Fe].push(V[De]));return ge}addPastKeyValues(V,ge){var Fe,De,Ze;if(ge)Object.assign(V,ge);else{const rt=this.sessions.decoder_model_merged??this.sessions.model,_t=((Fe=rt==null?void 0:rt.config)==null?void 0:Fe.kv_cache_dtype)??"float32",Mt=_t==="float16"?new Uint16Array:[],Rt=((Ze=(De=V[this.main_input_name]??V.attention_mask)==null?void 0:De.dims)==null?void 0:Ze[0])??1,Wt=(0,h.getKeyValueShapes)(this.config,{batch_size:Rt});for(const Dt in Wt)V[Dt]=new x.Tensor(_t,Mt,Wt[Dt])}}async encode_image({pixel_values:V}){const ge=(await we(this.sessions.vision_encoder,{pixel_values:V})).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 (${ge.dims[1]}).`),this.config.num_image_tokens=ge.dims[1]),ge}async encode_text({input_ids:V}){return(await we(this.sessions.embed_tokens,{input_ids:V})).inputs_embeds}}class Ke{}class Ue extends Ke{constructor({last_hidden_state:E,hidden_states:V=null,attentions:ge=null}){super(),this.last_hidden_state=E,this.hidden_states=V,this.attentions=ge}}class ue extends se{}class ve extends ue{}class Ve extends ue{async _call(E){return new tr(await super._call(E))}}class We extends ue{async _call(E){return new Zt(await super._call(E))}}class Ne extends ue{async _call(E){return new Ls(await super._call(E))}}class je extends ue{async _call(E){return new nr(await super._call(E))}}class st extends se{}class ut extends st{}class pt extends st{async _call(E){return new tr(await super._call(E))}}class lt extends st{async _call(E){return new Zt(await super._call(E))}}class mt extends st{async _call(E){return new Ls(await super._call(E))}}class B extends se{}class ae extends B{}class q extends se{}class me extends q{}class $e extends q{async _call(E){return new tr(await super._call(E))}}class Re extends q{async _call(E){return new Zt(await super._call(E))}}class qe extends q{async _call(E){return new Ls(await super._call(E))}}class at extends q{async _call(E){return new nr(await super._call(E))}}class ct extends se{}class vt extends ct{}class St extends ct{async _call(E){return new tr(await super._call(E))}}class kt extends ct{async _call(E){return new Zt(await super._call(E))}}class is extends ct{async _call(E){return new Ls(await super._call(E))}}class Ms extends ct{async _call(E){return new nr(await super._call(E))}}class $s extends se{}class zs extends $s{}class ar extends $s{async _call(E){return new tr(await super._call(E))}}class Ar extends $s{async _call(E){return new Zt(await super._call(E))}}class sn extends $s{async _call(E){return new Ls(await super._call(E))}}class Vs extends $s{async _call(E){return new nr(await super._call(E))}}class Cr extends se{}class Nt extends Cr{}class rn extends Cr{async _call(E){return new tr(await super._call(E))}}class Or extends Cr{async _call(E){return new Zt(await super._call(E))}}class Fr extends Cr{async _call(E){return new Ls(await super._call(E))}}class nn extends Cr{async _call(E){return new nr(await super._call(E))}}class fr extends se{}class Vr extends fr{}class Dr extends fr{async _call(E){return new tr(await super._call(E))}}class Wr extends fr{async _call(E){return new Zt(await super._call(E))}}class Gr extends fr{async _call(E){return new Ls(await super._call(E))}}class cr extends fr{async _call(E){return new nr(await super._call(E))}}class it extends se{}class xt extends it{}class Ft extends it{async _call(E){return new tr(await super._call(E))}}class Ws extends it{async _call(E){return new Zt(await super._call(E))}}class Kr extends it{async _call(E){return new Ls(await super._call(E))}}class Lr extends it{async _call(E){return new nr(await super._call(E))}}class vs extends se{}class pr extends vs{}class Fs extends vs{async _call(E){return new Zt(await super._call(E))}}class Sr extends vs{async _call(E){return new Ls(await super._call(E))}}class ss extends vs{async _call(E){return new nr(await super._call(E))}}class Tn extends vs{async _call(E){return new tr(await super._call(E))}}class Hr extends se{}class di extends Hr{}class Bn extends Hr{async _call(E){return new tr(await super._call(E))}}class Rn extends Hr{async _call(E){return new Zt(await super._call(E))}}class Nn extends Hr{async _call(E){return new Ls(await super._call(E))}}class qr extends se{}class jn extends qr{}class ci extends qr{async _call(E){return new tr(await super._call(E))}}class Qr extends qr{async _call(E){return new Zt(await super._call(E))}}class wr extends qr{async _call(E){return new nr(await super._call(E))}}class hr extends se{}class Pn extends hr{}class on extends hr{async _call(E){return new tr(await super._call(E))}}class En extends hr{async _call(E){return new Zt(await super._call(E))}}class Cn extends hr{async _call(E){return new Ls(await super._call(E))}}class Sn extends hr{async _call(E){return new nr(await super._call(E))}}class Lt extends se{}class $n extends Lt{}class Un extends Lt{async _call(E){return new tr(await super._call(E))}}class Vn extends Lt{async _call(E){return new Zt(await super._call(E))}}class Wn extends Lt{async _call(E){return new nr(await super._call(E))}}class Xr extends se{}class Gn extends Xr{}class kn extends Xr{async _call(E){return new Zt(await super._call(E))}}class Kn extends Xr{async _call(E){return new nr(await super._call(E))}}class os extends Xr{async _call(E){return new tr(await super._call(E))}}class Ee extends se{constructor(){super(...arguments);_e(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class C extends Ee{}class Y extends Ee{}class de extends se{}class xe extends de{}class Ie extends de{}class Xe extends se{}class ht extends Xe{}class gt extends Xe{}class ft extends se{}class Tt extends ft{}class Kt extends ft{}class fs extends ft{async _call(E){return new Zt(await super._call(E))}}class us extends se{}class Ds extends us{}class zt extends us{}class rs extends us{async _call(E){return new Zt(await super._call(E))}}class lr extends us{}class Gs extends se{}class ze extends Gs{}class rr extends Gs{}class zr extends se{}class ks extends zr{}class er extends zr{}class Ot extends se{}class dr extends Ot{}class br extends Ot{async _call(E){return new tr(await super._call(E))}}class _s extends Ot{async _call(E){return new Zt(await super._call(E))}}class Is extends Ot{async _call(E){return new Ls(await super._call(E))}}class bt extends Ot{async _call(E){return new nr(await super._call(E))}}class Xt extends se{}class Bs extends Xt{}class As extends Xt{async _call(E){return new tr(await super._call(E))}}class Ks extends Xt{async _call(E){return new Zt(await super._call(E))}}class $t extends Xt{async _call(E){return new Ls(await super._call(E))}}class an extends Xt{async _call(E){return new nr(await super._call(E))}}class Qe extends se{}class It extends Qe{}class Ha extends Qe{async _call(E){return new tr(await super._call(E))}}class Qi extends Qe{async _call(E){return new Zt(await super._call(E))}}class qa extends Qe{async _call(E){return new Ls(await super._call(E))}}class Qa extends Qe{async _call(E){return new nr(await super._call(E))}}class Jt extends se{}class Xa extends Jt{}class Xi extends Jt{}class Yi extends se{constructor(){super(...arguments);_e(this,"requires_attention_mask",!1);_e(this,"main_input_name","input_features");_e(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ya extends Yi{}class Ja extends Yi{_prepare_generation_config(E,V){return super._prepare_generation_config(E,V,W.WhisperGenerationConfig)}_retrieve_init_tokens(E){const V=[E.decoder_start_token_id];let ge=E.language;const Fe=E.task;if(E.is_multilingual){ge||(console.warn("No language specified - defaulting to English (en)."),ge="en");const Ze=`<|${(0,X.whisper_language_to_code)(ge)}|>`;V.push(E.lang_to_id[Ze]),V.push(E.task_to_id[Fe??"transcribe"])}else if(ge||Fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!E.return_timestamps&&E.no_timestamps_token_id&&V.at(-1)!==E.no_timestamps_token_id?V.push(E.no_timestamps_token_id):E.return_timestamps&&V.at(-1)===E.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),V.pop()),V.filter(De=>De!=null)}async generate({inputs:E=null,generation_config:V=null,logits_processor:ge=null,stopping_criteria:Fe=null,...De}){V=this._prepare_generation_config(V,De);const Ze=De.decoder_input_ids??this._retrieve_init_tokens(V);if(V.return_timestamps&&(ge??(ge=new w.LogitsProcessorList),ge.push(new w.WhisperTimeStampLogitsProcessor(V,Ze))),V.begin_suppress_tokens&&(ge??(ge=new w.LogitsProcessorList),ge.push(new w.SuppressTokensAtBeginLogitsProcessor(V.begin_suppress_tokens,Ze.length))),V.return_token_timestamps){if(!V.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.");V.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),V.output_attentions=!0,V.return_dict_in_generate=!0}const rt=await super.generate({inputs:E,generation_config:V,logits_processor:ge,decoder_input_ids:Ze,...De});return V.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,V.alignment_heads,V.num_frames)),rt}_extract_token_timestamps(E,V,ge=null,Fe=.02){if(!E.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`.");ge==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let De=this.config.median_filter_width;De===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),De=7);const Ze=E.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(ns,Yt)=>(0,x.cat)(Ze.map(as=>as[Yt]),2)),_t=(0,x.stack)(V.map(([ns,Yt])=>{if(ns>=rt.length)throw new Error(`Layer index ${ns} is out of bounds for cross attentions (length ${rt.length}).`);return ge?rt[ns].slice(null,Yt,null,[0,ge]):rt[ns].slice(null,Yt)})).transpose(1,0,2,3),[Mt,Rt]=(0,x.std_mean)(_t,-2,0,!0),Wt=_t.clone();for(let ns=0;nsas[ir+1]-as[ir]),cs=(0,F.mergeArrays)([1],Ts).map(Os=>!!Os),Ps=[];for(let Os=0;OsDt.findIndex(Gt=>Gt==De)),_t=rt.every(Dt=>Dt===-1),Mt=rt.every(Dt=>Dt!==-1);if(!_t&&!Mt)throw new Error("Every input should contain either 0 or 1 image token.");if(_t)return{inputs_embeds:E,attention_mask:Fe};const Rt=[],Wt=[];for(let Dt=0;DtArray.from({length:E.dims[0]},Ts=>Array.from({length:E.dims[1]},cs=>1))),es=V?V.tolist():[],ns=ge?ge.tolist():[];let Yt=0,as=0;for(let Es=0;EsDt[Es][Rs]==1),Ps=Ts.reduce((Cs,Rs,Zr)=>(Rs==_t&&Cs.push(Zr),Cs),[]).map(Cs=>Ts[Cs+1]),Os=Ps.filter(Cs=>Cs==Ze).length,ir=Ps.filter(Cs=>Cs==rt).length;let qs=[],kr=0,An=Os,Li=ir;for(let Cs=0;Csyr>kr&&tn==Ze),Zr=Ts.findIndex((tn,yr)=>yr>kr&&tn==rt),_n=An>0&&Rs!==-1?Rs:Ts.length+1,ti=Li>0&&Zr!==-1?Zr:Ts.length+1;let Ni,si,za,Ba;_n0?(0,H.max)(qs.at(-1))[0]+1:0;qs.push(Array.from({length:3*ji},(tn,yr)=>en+yr%ji));const Na=ji+en,On=ch*Ra*ri,Bc=Array.from({length:On},(tn,yr)=>Na+Math.floor(yr/(Ra*ri))),Rc=Array.from({length:On},(tn,yr)=>Na+Math.floor(yr/ri)%Ra),Nc=Array.from({length:On},(tn,yr)=>Na+yr%ri);qs.push([Bc,Rc,Nc].flat()),kr=Ni+On}if(kr0?(0,H.max)(qs.at(-1))[0]+1:0,Rs=Ts.length-kr;qs.push(Array.from({length:3*Rs},(Zr,_n)=>Cs+_n%Rs))}const mr=qs.reduce((Cs,Rs)=>Cs+Rs.length,0),Pr=new Array(mr);let zi=0;for(let Cs=0;Cs<3;++Cs)for(let Rs=0;RsWt[Yt%Wt.length]),es=Array.from({length:Dt[0]},(ns,Yt)=>(0,H.max)(Wt.subarray(Dt[1]*Yt,Dt[1]*(Yt+1)))[0]+1n+BigInt(Dt[1]));return[new x.Tensor("int64",Gt,[3,...Dt]),new x.Tensor("int64",es,[es.length,1])]}else{const[Wt,Dt]=E.dims,Gt=BigInt64Array.from({length:3*Wt*Dt},(es,ns)=>BigInt(Math.floor(ns%Dt/Wt)));return[new x.Tensor("int64",Gt,[3,...E.dims]),(0,x.zeros)([Wt,1])]}}async encode_image({pixel_values:E,image_grid_thw:V}){return(await we(this.sessions.vision_encoder,{pixel_values:E,grid_thw:V})).image_features}_merge_input_ids_with_image_features(E){return tt({image_token_id:this.config.image_token_id,...E})}prepare_inputs_for_generation(E,V,ge){if(V.attention_mask&&!V.position_ids)if(!V.past_key_values)[V.position_ids,V.rope_deltas]=this.get_rope_index(V.input_ids,V.image_grid_thw,V.video_grid_thw,V.attention_mask);else{V.pixel_values=null;const Fe=BigInt(Object.values(V.past_key_values)[0].dims.at(-2)),De=V.rope_deltas.map(Ze=>Fe+Ze);V.position_ids=(0,x.stack)([De,De,De],0)}return V}}class Co extends se{}class Kl extends Co{}class Hl extends Co{}class So extends se{}class ql extends So{}class Ql extends So{}class $o extends se{}class Xl extends $o{}class Yl extends $o{}class ko extends se{}class Jl extends ko{}class Zl extends ko{}class Io extends se{}class eu extends Io{}class tu extends Io{}class yi extends se{}class su extends yi{}class Ao extends yi{async _call(E){return new Zt(await super._call(E))}}class wi extends se{}class ru extends wi{}class nu extends wi{async _call(E){return new Zt(await super._call(E))}}class iu extends se{}class ou extends iu{}class Oo extends se{}class au extends Oo{}class Fo extends Oo{async _call(E){return new Zt(await super._call(E))}}class lu extends se{}class uu extends lu{}class Do extends se{}class np extends Do{}class du extends Do{async _call(E){return new Zt(await super._call(E))}}class cu extends se{}class Tr extends cu{}class Lo extends se{}class pu extends Lo{}class hu extends Lo{async _call(E){return new Zt(await super._call(E))}}class mu extends se{}class fu extends mu{async _call(E){return new Lc(await super._call(E))}}class zo extends se{}class _u extends zo{}class gu extends zo{async _call(E){return new Zt(await super._call(E))}}class Bo extends se{}class yu extends Bo{}class ip extends Bo{async _call(E){return new Zt(await super._call(E))}}class Ro extends se{}class wu extends Ro{}class bu extends Ro{}class No extends se{}class Mu extends No{}class vu extends No{}class xu extends se{}class un extends xu{}class dn extends xu{async _call(E){return new Zt(await super._call(E))}}class Br extends se{}class jo extends Br{}class cn extends Br{async _call(E){return new Uo(await super._call(E))}}class Hs extends Br{async _call(E){return new Vo(await super._call(E))}}class Uo extends Ke{constructor({logits:E,pred_boxes:V}){super(),this.logits=E,this.pred_boxes=V}}class Vo extends Ke{constructor({logits:E,pred_boxes:V,pred_masks:ge}){super(),this.logits=E,this.pred_boxes=V,this.pred_masks=ge}}class Wo extends se{}class op extends Wo{}class Qn extends Wo{async _call(E){return new Go(await super._call(E))}}class Go extends Ke{constructor({logits:E,pred_boxes:V}){super(),this.logits=E,this.pred_boxes=V}}class bi extends se{}class Tu extends bi{}class Pu extends bi{async _call(E){return new Ko(await super._call(E))}}class Ko extends Uo{}class Mi extends se{}class Eu extends Mi{}class Ho extends Mi{async _call(E){return new Zt(await super._call(E))}}class qo extends se{}class vi extends qo{}class Qo extends qo{async _call(E){return new Zt(await super._call(E))}}class Xo extends se{}class Cu extends Xo{}class ap extends Xo{async _call(E){return new Zt(await super._call(E))}}class Yo extends se{}class Jo extends Yo{}class Xn extends Yo{async _call(E){return new Zt(await super._call(E))}}class Zo extends se{}class ea extends Zo{}class Su extends Zo{}class ta extends se{}class $u extends ta{}class lp extends ta{}class ku extends se{}class Iu extends ku{}class sa extends se{}class Au extends sa{}class xi extends sa{}class Ou extends sa{}class Ti extends se{}class ra extends Ti{}class Pi extends se{}class Fu extends Pi{}class Du extends Pi{}class Ei extends se{}class up extends Ei{}class Lu extends Ei{}class dp extends se{}class zu extends dp{}class na extends se{}class Bu extends na{}class ia extends na{async _call(E){return new Zt(await super._call(E))}}class oa extends se{}class Ru extends oa{}class aa extends oa{async _call(E){return new Zt(await super._call(E))}}class la extends se{}class Nu extends la{}class cp extends la{async _call(E){return new Zt(await super._call(E))}}class ua extends se{}class ju extends ua{}class Uu extends ua{async _call(E){return new Zt(await super._call(E))}}class pp extends se{}class Vu extends pp{}class da extends se{}class Wu extends da{}class Gu extends da{async _call(E){return new Ku(await super._call(E))}}class Ku extends Ke{constructor({logits:E,pred_boxes:V}){super(),this.logits=E,this.pred_boxes=V}}class hp extends se{}class Ci extends hp{async get_image_embeddings({pixel_values:E}){return await Oe(this,{pixel_values:E})}async forward(E){if((!E.image_embeddings||!E.image_positional_embeddings)&&(E={...E,...await this.get_image_embeddings(E)}),!E.input_labels&&E.input_points){const ge=E.input_points.dims.slice(0,-1),Fe=ge.reduce((De,Ze)=>De*Ze,1);E.input_labels=new x.Tensor("int64",new BigInt64Array(Fe).fill(1n),ge)}const V={image_embeddings:E.image_embeddings,image_positional_embeddings:E.image_positional_embeddings};return E.input_points&&(V.input_points=E.input_points),E.input_labels&&(V.input_labels=E.input_labels),E.input_boxes&&(V.input_boxes=E.input_boxes),await we(this.sessions.prompt_encoder_mask_decoder,V)}async _call(E){return new Yn(await super._call(E))}}class Yn extends Ke{constructor({iou_scores:E,pred_masks:V}){super(),this.iou_scores=E,this.pred_masks=V}}class Si extends se{}class Hu extends Si{}class qu extends Si{}class ca extends se{}class Qu extends ca{}class pa extends ca{}class Jr extends se{}class Xu extends Jr{}class Yu extends Jr{async _call(E){return new fn(await super._call(E))}}class mp extends Jr{async _call(E){return new Zt(await super._call(E))}}class Ju extends Jr{async _call(E){return new Ls(await super._call(E))}}class $i extends se{}class Zu extends $i{}class ed extends $i{async _call(E){return new Ls(await super._call(E))}}class td extends se{}class fp extends td{}class ki extends se{}class sd extends ki{}class _p extends ki{async _call(E){return new fn(await super._call(E))}}class rd extends ki{async _call(E){return new Zt(await super._call(E))}}class Jn extends se{}class nd extends Jn{}class id extends Jn{async _call(E){return new fn(await super._call(E))}}class gp extends Jn{async _call(E){return new Zt(await super._call(E))}}class od extends Jn{async _call(E){return new Ls(await super._call(E))}}class Ii extends se{}class ad extends Ii{}class yp extends Ii{async _call(E){return new fn(await super._call(E))}}class ld extends Ii{async _call(E){return new Zt(await super._call(E))}}class wp extends se{}class ud extends Jr{}class dd extends Jr{async _call(E){return new fn(await super._call(E))}}class bp extends Jr{async _call(E){return new Zt(await super._call(E))}}class In extends se{}class cd extends In{}class pd extends In{async _call(E){return new fn(await super._call(E))}}class hd extends In{async _call(E){return new Zt(await super._call(E))}}class Mp extends In{async _call(E){return new Dc(await super._call(E))}}class md extends In{async _call(E){return new Ls(await super._call(E))}}class fd extends se{}class _d extends fd{}class Ai extends se{}class uh extends Ai{}class $r extends Ai{}class Rr extends Ai{async generate_speech(E,V,{threshold:ge=.5,minlenratio:Fe=0,maxlenratio:De=20,vocoder:Ze=null}={}){const rt={input_ids:E},{encoder_outputs:_t,encoder_attention_mask:Mt}=await Oe(this,rt),Rt=_t.dims[1]/this.config.reduction_factor,Wt=Math.floor(Rt*De),Dt=Math.floor(Rt*Fe),Gt=this.config.num_mel_bins;let es=[],ns=null,Yt=null,as=0;for(;;){++as;const cs=pe(!!Yt);let Ps;Yt?Ps=Yt.output_sequence_out:Ps=new x.Tensor("float32",new Float32Array(Gt),[1,1,Gt]);let Os={use_cache_branch:cs,output_sequence:Ps,encoder_attention_mask:Mt,speaker_embeddings:V,encoder_hidden_states:_t};this.addPastKeyValues(Os,ns),Yt=await we(this.sessions.decoder_model_merged,Os),ns=this.getPastKeyValues(Yt,ns);const{prob:ir,spectrum:qs}=Yt;if(es.push(qs),as>=Dt&&(Array.from(ir.data).filter(kr=>kr>=ge).length>0||as>=Wt))break}const Es=(0,x.cat)(es),{waveform:Ts}=await we(Ze.sessions.model,{spectrogram:Es});return{spectrogram:Es,waveform:Ts}}}class pn extends se{constructor(){super(...arguments);_e(this,"main_input_name","spectrogram")}}class hn extends se{}class gd extends hn{}class ha extends se{}class yd extends ha{}class wd extends ha{}class ma extends se{}class bd extends ma{}class Md extends ma{}class fa extends se{}class vd extends fa{}class xd extends fa{}class _a extends se{}class ur extends _a{}class Td extends _a{static async from_pretrained(E,V={}){return super.from_pretrained(E,{...V,model_file_name:V.model_file_name??"text_model"})}}class Pd extends _a{static async from_pretrained(E,V={}){return super.from_pretrained(E,{...V,model_file_name:V.model_file_name??"audio_model"})}}class ga extends se{}class ya extends ga{async _call(E){return new zc(await super._call(E))}}class mn extends se{}class vp extends mn{}class Ed extends mn{}class Cd extends mn{}class wa extends se{}class Sd extends wa{}class $d extends wa{}class Oi extends se{}class kd extends Oi{}class Id extends Oi{async _call(E){return new Zt(await super._call(E))}}class ba extends se{}class xp extends ba{}class Tp extends ba{}class Fi extends se{constructor(){super(...arguments);_e(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(V){const[ge,Fe]=V.dims,De=this.config.decoder.num_codebooks,Ze=Fe-De;let rt=0;for(let Rt=0;Rt0&&Gt<=Ze&&(V.data[rt++]=V.data[Rt])}const _t=Math.floor(ge/De),Mt=rt/(_t*De);return new x.Tensor(V.type,V.data.slice(0,rt),[_t,De,Mt])}prepare_inputs_for_generation(V,ge,Fe){let De=structuredClone(V);for(let rt=0;rt=_t&&(De[rt][_t]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(De=De.concat(De)),super.prepare_inputs_for_generation(De,ge,Fe)}async generate(V){const ge=await super.generate(V),Fe=this._apply_and_filter_by_delay_pattern_mask(ge).unsqueeze_(0),{audio_values:De}=await we(this.sessions.encodec_decode,{audio_codes:Fe});return De}}class Ma extends se{}class Pp extends Ma{}class va extends Ma{async _call(E){return new Zt(await super._call(E))}}class xa extends se{}class Ad extends xa{}class Od extends xa{async _call(E){return new Zt(await super._call(E))}}class Fd extends se{}class Dd extends Fd{}class Ld extends Fd{async _call(E){return new Zt(await super._call(E))}}class Ta extends se{}class Ep extends Ta{}class zd extends Ta{async _call(E){return new Zt(await super._call(E))}}class Bd extends se{}class Cp extends Bd{}class Rd extends se{}class Nd extends Rd{constructor(...V){super(...V);_e(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(V){const ge=this._generation_mode??"text";let Fe;if(ge==="text"||!V.past_key_values){const Mt=this.sessions.prepare_inputs_embeds,Rt=(0,F.pick)(V,Mt.inputNames);Fe=await we(Mt,Rt)}else{const Mt=this.sessions.gen_img_embeds,Rt=(0,F.pick)({image_ids:V.input_ids},Mt.inputNames);Fe=await we(Mt,Rt)}const De={...V,...Fe},Ze=await Ce(this,De),rt=this.sessions[ge==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const _t=await we(rt,(0,F.pick)(Ze,rt.inputNames));return{...Fe,...Ze,..._t}}async generate(V){return this._generation_mode="text",super.generate(V)}async generate_images(V){this._generation_mode="image";const ge=(V.inputs??V[this.main_input_name]).dims[1],De=(await super.generate(V)).slice(null,[ge,null]),Ze=this.sessions.image_decode,{decoded_image:rt}=await we(Ze,{generated_tokens:De}),_t=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Mt=[];for(const Rt of _t){const Wt=O.RawImage.fromTensor(Rt);Mt.push(Wt)}return Mt}}class jd extends Ke{constructor({char_logits:E,bpe_logits:V,wp_logits:ge}){super(),this.char_logits=E,this.bpe_logits=V,this.wp_logits=ge}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Ud extends se{}class Vd extends Ud{async _call(E){return new jd(await super._call(E))}}class Wd extends se{}class Gd extends Wd{}class Kd extends Wd{}class Pa extends se{}class Hd extends Pa{}class qd extends Pa{}class ws{static async from_pretrained(E,{progress_callback:V=null,config:ge=null,cache_dir:Fe=null,local_files_only:De=!1,revision:Ze="main",model_file_name:rt=null,subfolder:_t="onnx",device:Mt=null,dtype:Rt=null,use_external_data_format:Wt=null,session_options:Dt={}}={}){const Gt={progress_callback:V,config:ge,cache_dir:Fe,local_files_only:De,revision:Ze,model_file_name:rt,subfolder:_t,device:Mt,dtype:Rt,use_external_data_format:Wt,session_options:Dt};if(Gt.config=await h.AutoConfig.from_pretrained(E,Gt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const es of this.MODEL_CLASS_MAPPINGS){const ns=es.get(Gt.config.model_type);if(ns)return await ns[1].from_pretrained(E,Gt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Gt.config.model_type}", attempting to construct from base class.`),await se.from_pretrained(E,Gt);throw Error(`Unsupported model type: ${Gt.config.model_type}`)}}_e(ws,"MODEL_CLASS_MAPPINGS",null),_e(ws,"BASE_IF_FAIL",!1);const Sp=new Map([["bert",["BertModel",ve]],["modernbert",["ModernBertModel",ut]],["nomic_bert",["NomicBertModel",ae]],["roformer",["RoFormerModel",me]],["electra",["ElectraModel",zs]],["esm",["EsmModel",di]],["convbert",["ConvBertModel",vt]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",Vr]],["deberta-v2",["DebertaV2Model",xt]],["mpnet",["MPNetModel",Pn]],["albert",["AlbertModel",Gn]],["distilbert",["DistilBertModel",pr]],["roberta",["RobertaModel",dr]],["xlm",["XLMModel",Bs]],["xlm-roberta",["XLMRobertaModel",It]],["clap",["ClapModel",ur]],["clip",["CLIPModel",ll]],["clipseg",["CLIPSegModel",ml]],["chinese_clip",["ChineseCLIPModel",Mr]],["siglip",["SiglipModel",cl]],["jina_clip",["JinaCLIPModel",mi]],["mobilebert",["MobileBertModel",jn]],["squeezebert",["SqueezeBertModel",$n]],["wav2vec2",["Wav2Vec2Model",Xu]],["wav2vec2-bert",["Wav2Vec2BertModel",ad]],["unispeech",["UniSpeechModel",sd]],["unispeech-sat",["UniSpeechSatModel",nd]],["hubert",["HubertModel",ud]],["wavlm",["WavLMModel",cd]],["audio-spectrogram-transformer",["ASTModel",Xa]],["vits",["VitsModel",ya]],["pyannote",["PyAnnoteModel",Zu]],["wespeaker-resnet",["WeSpeakerResNetModel",fp]],["detr",["DetrModel",jo]],["rt_detr",["RTDetrModel",op]],["table-transformer",["TableTransformerModel",Tu]],["vit",["ViTModel",su]],["ijepa",["IJepaModel",ru]],["pvt",["PvtModel",au]],["vit_msn",["ViTMSNModel",np]],["vit_mae",["ViTMAEModel",uu]],["groupvit",["GroupViTModel",Tr]],["fastvit",["FastViTModel",pu]],["mobilevit",["MobileViTModel",_u]],["mobilevitv2",["MobileViTV2Model",yu]],["owlvit",["OwlViTModel",wu]],["owlv2",["Owlv2Model",Mu]],["beit",["BeitModel",un]],["deit",["DeiTModel",Eu]],["hiera",["HieraModel",vi]],["convnext",["ConvNextModel",Bu]],["convnextv2",["ConvNextV2Model",Ru]],["dinov2",["Dinov2Model",Nu]],["dinov2_with_registers",["Dinov2WithRegistersModel",ju]],["resnet",["ResNetModel",Cu]],["swin",["SwinModel",Jo]],["swin2sr",["Swin2SRModel",ea]],["donut-swin",["DonutSwinModel",zu]],["yolos",["YolosModel",Wu]],["dpt",["DPTModel",$u]],["glpn",["GLPNModel",up]],["hifigan",["SpeechT5HifiGan",pn]],["efficientnet",["EfficientNetModel",kd]],["decision_transformer",["DecisionTransformerModel",Cp]],["patchtst",["PatchTSTForPrediction",Gd]],["patchtsmixer",["PatchTSMixerForPrediction",Hd]],["mobilenet_v1",["MobileNetV1Model",Pp]],["mobilenet_v2",["MobileNetV2Model",Ad]],["mobilenet_v3",["MobileNetV3Model",Dd]],["mobilenet_v4",["MobileNetV4Model",Ep]],["maskformer",["MaskFormerModel",Fu]],["mgp-str",["MgpstrForSceneTextRecognition",Vd]],["style_text_to_speech_2",["StyleTextToSpeech2Model",_d]]]),$p=new Map([["t5",["T5Model",C]],["longt5",["LongT5Model",xe]],["mt5",["MT5Model",ht]],["bart",["BartModel",Tt]],["mbart",["MBartModel",Ds]],["marian",["MarianModel",Hu]],["whisper",["WhisperModel",Ya]],["m2m_100",["M2M100Model",Qu]],["blenderbot",["BlenderbotModel",ze]],["blenderbot-small",["BlenderbotSmallModel",ks]]]),kp=new Map([["bloom",["BloomModel",Xl]],["jais",["JAISModel",yl]],["gpt2",["GPT2Model",_l]],["gptj",["GPTJModel",xl]],["gpt_bigcode",["GPTBigCodeModel",Pl]],["gpt_neo",["GPTNeoModel",xr]],["gpt_neox",["GPTNeoXModel",Ml]],["codegen",["CodeGenModel",co]],["llama",["LlamaModel",ho]],["exaone",["ExaoneModel",kl]],["olmo",["OlmoModel",sp]],["olmo2",["Olmo2Model",Fl]],["mobilellm",["MobileLLMModel",Il]],["granite",["GraniteModel",ds]],["cohere",["CohereModel",Ll]],["gemma",["GemmaModel",Bl]],["gemma2",["Gemma2Model",Nl]],["helium",["HeliumModel",_i]],["glm",["GlmModel",$l]],["openelm",["OpenELMModel",Ul]],["qwen2",["Qwen2Model",qn]],["phi",["PhiModel",Kl]],["phi3",["Phi3Model",ql]],["mpt",["MptModel",Jl]],["opt",["OPTModel",eu]],["mistral",["MistralModel",yd]],["starcoder2",["Starcoder2Model",bd]],["falcon",["FalconModel",vd]],["stablelm",["StableLmModel",Sd]]]),Qd=new Map([["speecht5",["SpeechT5ForSpeechToText",$r]],["whisper",["WhisperForConditionalGeneration",Ja]],["moonshine",["MoonshineForConditionalGeneration",Za]]]),Zn=new Map([["speecht5",["SpeechT5ForTextToSpeech",Rr]]]),Ea=new Map([["vits",["VitsModel",ya]],["musicgen",["MusicgenForConditionalGeneration",Fi]]]),Ca=new Map([["bert",["BertForSequenceClassification",We]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",Re]],["electra",["ElectraForSequenceClassification",Ar]],["esm",["EsmForSequenceClassification",Rn]],["convbert",["ConvBertForSequenceClassification",kt]],["camembert",["CamembertForSequenceClassification",Or]],["deberta",["DebertaForSequenceClassification",Wr]],["deberta-v2",["DebertaV2ForSequenceClassification",Ws]],["mpnet",["MPNetForSequenceClassification",En]],["albert",["AlbertForSequenceClassification",kn]],["distilbert",["DistilBertForSequenceClassification",Fs]],["roberta",["RobertaForSequenceClassification",_s]],["xlm",["XLMForSequenceClassification",Ks]],["xlm-roberta",["XLMRobertaForSequenceClassification",Qi]],["bart",["BartForSequenceClassification",fs]],["mbart",["MBartForSequenceClassification",rs]],["mobilebert",["MobileBertForSequenceClassification",Qr]],["squeezebert",["SqueezeBertForSequenceClassification",Vn]]]),Sa=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",mt]],["roformer",["RoFormerForTokenClassification",qe]],["electra",["ElectraForTokenClassification",sn]],["esm",["EsmForTokenClassification",Nn]],["convbert",["ConvBertForTokenClassification",is]],["camembert",["CamembertForTokenClassification",Fr]],["deberta",["DebertaForTokenClassification",Gr]],["deberta-v2",["DebertaV2ForTokenClassification",Kr]],["mpnet",["MPNetForTokenClassification",Cn]],["distilbert",["DistilBertForTokenClassification",Sr]],["roberta",["RobertaForTokenClassification",Is]],["xlm",["XLMForTokenClassification",$t]],["xlm-roberta",["XLMRobertaForTokenClassification",qa]]]),Di=new Map([["t5",["T5ForConditionalGeneration",Y]],["longt5",["LongT5ForConditionalGeneration",Ie]],["mt5",["MT5ForConditionalGeneration",gt]],["bart",["BartForConditionalGeneration",Kt]],["mbart",["MBartForConditionalGeneration",zt]],["marian",["MarianMTModel",qu]],["m2m_100",["M2M100ForConditionalGeneration",pa]],["blenderbot",["BlenderbotForConditionalGeneration",rr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",er]]]),$a=new Map([["bloom",["BloomForCausalLM",Yl]],["gpt2",["GPT2LMHeadModel",gl]],["jais",["JAISLMHeadModel",wl]],["gptj",["GPTJForCausalLM",Tl]],["gpt_bigcode",["GPTBigCodeForCausalLM",El]],["gpt_neo",["GPTNeoForCausalLM",bl]],["gpt_neox",["GPTNeoXForCausalLM",vl]],["codegen",["CodeGenForCausalLM",Cl]],["llama",["LlamaForCausalLM",tp]],["exaone",["ExaoneForCausalLM",go]],["olmo",["OlmoForCausalLM",Ol]],["olmo2",["Olmo2ForCausalLM",rp]],["mobilellm",["MobileLLMForCausalLM",Al]],["granite",["GraniteForCausalLM",Dl]],["cohere",["CohereForCausalLM",zl]],["gemma",["GemmaForCausalLM",Rl]],["gemma2",["Gemma2ForCausalLM",jl]],["helium",["HeliumForCausalLM",Sl]],["glm",["GlmForCausalLM",Hn]],["openelm",["OpenELMForCausalLM",Vl]],["qwen2",["Qwen2ForCausalLM",Wl]],["phi",["PhiForCausalLM",Hl]],["phi3",["Phi3ForCausalLM",Ql]],["mpt",["MptForCausalLM",Zl]],["opt",["OPTForCausalLM",tu]],["mbart",["MBartForCausalLM",lr]],["mistral",["MistralForCausalLM",wd]],["starcoder2",["Starcoder2ForCausalLM",Md]],["falcon",["FalconForCausalLM",xd]],["trocr",["TrOCRForCausalLM",gd]],["stablelm",["StableLmForCausalLM",$d]],["phi3_v",["Phi3VForCausalLM",gr]]]),Ip=new Map([["multi_modality",["MultiModalityCausalLM",Nd]]]),ka=new Map([["bert",["BertForMaskedLM",Ve]],["modernbert",["ModernBertForMaskedLM",pt]],["roformer",["RoFormerForMaskedLM",$e]],["electra",["ElectraForMaskedLM",ar]],["esm",["EsmForMaskedLM",Bn]],["convbert",["ConvBertForMaskedLM",St]],["camembert",["CamembertForMaskedLM",rn]],["deberta",["DebertaForMaskedLM",Dr]],["deberta-v2",["DebertaV2ForMaskedLM",Ft]],["mpnet",["MPNetForMaskedLM",on]],["albert",["AlbertForMaskedLM",os]],["distilbert",["DistilBertForMaskedLM",Tn]],["roberta",["RobertaForMaskedLM",br]],["xlm",["XLMWithLMHeadModel",As]],["xlm-roberta",["XLMRobertaForMaskedLM",Ha]],["mobilebert",["MobileBertForMaskedLM",ci]],["squeezebert",["SqueezeBertForMaskedLM",Un]]]),Ia=new Map([["bert",["BertForQuestionAnswering",je]],["roformer",["RoFormerForQuestionAnswering",at]],["electra",["ElectraForQuestionAnswering",Vs]],["convbert",["ConvBertForQuestionAnswering",Ms]],["camembert",["CamembertForQuestionAnswering",nn]],["deberta",["DebertaForQuestionAnswering",cr]],["deberta-v2",["DebertaV2ForQuestionAnswering",Lr]],["mpnet",["MPNetForQuestionAnswering",Sn]],["albert",["AlbertForQuestionAnswering",Kn]],["distilbert",["DistilBertForQuestionAnswering",ss]],["roberta",["RobertaForQuestionAnswering",bt]],["xlm",["XLMForQuestionAnswering",an]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Qa]],["mobilebert",["MobileBertForQuestionAnswering",wr]],["squeezebert",["SqueezeBertForQuestionAnswering",Wn]]]),Aa=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Zi]],["idefics3",["Idefics3ForConditionalGeneration",eo]]]),Ap=new Map([["llava",["LlavaForConditionalGeneration",pi]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",el]],["moondream1",["Moondream1ForConditionalGeneration",tl]],["florence2",["Florence2ForConditionalGeneration",rl]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Gl]],["idefics3",["Idefics3ForConditionalGeneration",eo]],["paligemma",["PaliGemmaForConditionalGeneration",il]]]),Xd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Zi]]]),Yd=new Map([["vit",["ViTForImageClassification",Ao]],["ijepa",["IJepaForImageClassification",nu]],["pvt",["PvtForImageClassification",Fo]],["vit_msn",["ViTMSNForImageClassification",du]],["fastvit",["FastViTForImageClassification",hu]],["mobilevit",["MobileViTForImageClassification",gu]],["mobilevitv2",["MobileViTV2ForImageClassification",ip]],["beit",["BeitForImageClassification",dn]],["deit",["DeiTForImageClassification",Ho]],["hiera",["HieraForImageClassification",Qo]],["convnext",["ConvNextForImageClassification",ia]],["convnextv2",["ConvNextV2ForImageClassification",aa]],["dinov2",["Dinov2ForImageClassification",cp]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Uu]],["resnet",["ResNetForImageClassification",ap]],["swin",["SwinForImageClassification",Xn]],["segformer",["SegformerForImageClassification",Ed]],["efficientnet",["EfficientNetForImageClassification",Id]],["mobilenet_v1",["MobileNetV1ForImageClassification",va]],["mobilenet_v2",["MobileNetV2ForImageClassification",Od]],["mobilenet_v3",["MobileNetV3ForImageClassification",Ld]],["mobilenet_v4",["MobileNetV4ForImageClassification",zd]]]),Jd=new Map([["detr",["DetrForObjectDetection",cn]],["rt_detr",["RTDetrForObjectDetection",Qn]],["table-transformer",["TableTransformerForObjectDetection",Pu]],["yolos",["YolosForObjectDetection",Gu]]]),Oa=new Map([["owlvit",["OwlViTForObjectDetection",bu]],["owlv2",["Owlv2ForObjectDetection",vu]],["grounding-dino",["GroundingDinoForObjectDetection",Vu]]]),Zd=new Map([["detr",["DetrForSegmentation",Hs]],["clipseg",["CLIPSegForImageSegmentation",fl]]]),ec=new Map([["segformer",["SegformerForSemanticSegmentation",Cd]],["sapiens",["SapiensForSemanticSegmentation",Au]]]),tc=new Map([["detr",["DetrForSegmentation",Hs]],["maskformer",["MaskFormerForInstanceSegmentation",Du]]]),sc=new Map([["sam",["SamModel",Ci]]]),Op=new Map([["wav2vec2",["Wav2Vec2ForCTC",Yu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",yp]],["unispeech",["UniSpeechForCTC",_p]],["unispeech-sat",["UniSpeechSatForCTC",id]],["wavlm",["WavLMForCTC",pd]],["hubert",["HubertForCTC",dd]]]),rc=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",mp]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",ld]],["unispeech",["UniSpeechForSequenceClassification",rd]],["unispeech-sat",["UniSpeechSatForSequenceClassification",gp]],["wavlm",["WavLMForSequenceClassification",hd]],["hubert",["HubertForSequenceClassification",bp]],["audio-spectrogram-transformer",["ASTForAudioClassification",Xi]]]),nc=new Map([["wavlm",["WavLMForXVector",Mp]]]),ic=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",od]],["wavlm",["WavLMForAudioFrameClassification",md]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ju]],["pyannote",["PyAnnoteForAudioFrameClassification",ed]]]),oc=new Map([["vitmatte",["VitMatteForImageMatting",fu]]]),dh=new Map([["patchtst",["PatchTSTForPrediction",Kd]],["patchtsmixer",["PatchTSMixerForPrediction",qd]]]),ac=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Su]]]),lc=new Map([["dpt",["DPTForDepthEstimation",lp]],["depth_anything",["DepthAnythingForDepthEstimation",Iu]],["glpn",["GLPNForDepthEstimation",Lu]],["sapiens",["SapiensForDepthEstimation",xi]],["depth_pro",["DepthProForDepthEstimation",ra]]]),uc=new Map([["sapiens",["SapiensForNormalEstimation",Ou]]]),Fp=new Map([["vitpose",["VitPoseForPoseEstimation",ou]]]),dc=new Map([["clip",["CLIPVisionModelWithProjection",dl]],["siglip",["SiglipVisionModel",hl]],["jina_clip",["JinaCLIPVisionModel",vr]]]),cc=[[Sp,D.EncoderOnly],[$p,D.EncoderDecoder],[kp,D.DecoderOnly],[Ca,D.EncoderOnly],[Sa,D.EncoderOnly],[Di,D.Seq2Seq],[Qd,D.Seq2Seq],[$a,D.DecoderOnly],[Ip,D.MultiModality],[ka,D.EncoderOnly],[Ia,D.EncoderOnly],[Aa,D.Vision2Seq],[Ap,D.ImageTextToText],[Yd,D.EncoderOnly],[Zd,D.EncoderOnly],[tc,D.EncoderOnly],[ec,D.EncoderOnly],[oc,D.EncoderOnly],[dh,D.EncoderOnly],[ac,D.EncoderOnly],[lc,D.EncoderOnly],[uc,D.EncoderOnly],[Fp,D.EncoderOnly],[Jd,D.EncoderOnly],[Oa,D.EncoderOnly],[sc,D.MaskGeneration],[Op,D.EncoderOnly],[rc,D.EncoderOnly],[Zn,D.Seq2Seq],[Ea,D.EncoderOnly],[nc,D.EncoderOnly],[ic,D.EncoderOnly],[dc,D.EncoderOnly]];for(const[y,E]of cc)for(const[V,ge]of y.values())A.set(V,E),P.set(ge,V),M.set(V,ge);const Dp=[["MusicgenForConditionalGeneration",Fi,D.Musicgen],["Phi3VForCausalLM",gr,D.Phi3V],["CLIPTextModelWithProjection",ul,D.EncoderOnly],["SiglipTextModel",pl,D.EncoderOnly],["JinaCLIPTextModel",so,D.EncoderOnly],["ClapTextModelWithProjection",Td,D.EncoderOnly],["ClapAudioModelWithProjection",Pd,D.EncoderOnly]];for(const[y,E,V]of Dp)A.set(y,V),P.set(E,y),M.set(y,E);class Fa extends ws{}_e(Fa,"MODEL_CLASS_MAPPINGS",cc.map(E=>E[0])),_e(Fa,"BASE_IF_FAIL",!0);class Lp extends ws{}_e(Lp,"MODEL_CLASS_MAPPINGS",[Ca]);class pc extends ws{}_e(pc,"MODEL_CLASS_MAPPINGS",[Sa]);class hc extends ws{}_e(hc,"MODEL_CLASS_MAPPINGS",[Di]);class mc extends ws{}_e(mc,"MODEL_CLASS_MAPPINGS",[Qd]);class Da extends ws{}_e(Da,"MODEL_CLASS_MAPPINGS",[Zn]);class fc extends ws{}_e(fc,"MODEL_CLASS_MAPPINGS",[Ea]);class _c extends ws{}_e(_c,"MODEL_CLASS_MAPPINGS",[$a]);class gc extends ws{}_e(gc,"MODEL_CLASS_MAPPINGS",[ka]);class yc extends ws{}_e(yc,"MODEL_CLASS_MAPPINGS",[Ia]);class wc extends ws{}_e(wc,"MODEL_CLASS_MAPPINGS",[Aa]);class bc extends ws{}_e(bc,"MODEL_CLASS_MAPPINGS",[Yd]);class Mc extends ws{}_e(Mc,"MODEL_CLASS_MAPPINGS",[Zd]);class vc extends ws{}_e(vc,"MODEL_CLASS_MAPPINGS",[ec]);class La extends ws{}_e(La,"MODEL_CLASS_MAPPINGS",[tc]);class xc extends ws{}_e(xc,"MODEL_CLASS_MAPPINGS",[Jd]);class Tc extends ws{}_e(Tc,"MODEL_CLASS_MAPPINGS",[Oa]);class Pc extends ws{}_e(Pc,"MODEL_CLASS_MAPPINGS",[sc]);class Ec extends ws{}_e(Ec,"MODEL_CLASS_MAPPINGS",[Op]);class Cc extends ws{}_e(Cc,"MODEL_CLASS_MAPPINGS",[rc]);class Sc extends ws{}_e(Sc,"MODEL_CLASS_MAPPINGS",[nc]);class $c extends ws{}_e($c,"MODEL_CLASS_MAPPINGS",[ic]);class zp extends ws{}_e(zp,"MODEL_CLASS_MAPPINGS",[Xd]);class kc extends ws{}_e(kc,"MODEL_CLASS_MAPPINGS",[oc]);class Ic extends ws{}_e(Ic,"MODEL_CLASS_MAPPINGS",[ac]);class Ac extends ws{}_e(Ac,"MODEL_CLASS_MAPPINGS",[lc]);class Bp extends ws{}_e(Bp,"MODEL_CLASS_MAPPINGS",[uc]);class Oc extends ws{}_e(Oc,"MODEL_CLASS_MAPPINGS",[Fp]);class Fc extends ws{}_e(Fc,"MODEL_CLASS_MAPPINGS",[dc]);class Rp extends Ke{constructor({logits:E,past_key_values:V,encoder_outputs:ge,decoder_attentions:Fe=null,cross_attentions:De=null}){super(),this.logits=E,this.past_key_values=V,this.encoder_outputs=ge,this.decoder_attentions=Fe,this.cross_attentions=De}}class Zt extends Ke{constructor({logits:E,...V}){super(),this.logits=E;const ge=Object.values(V);ge.length>0&&(this.attentions=ge)}}class Dc extends Ke{constructor({logits:E,embeddings:V}){super(),this.logits=E,this.embeddings=V}}class Ls extends Ke{constructor({logits:E}){super(),this.logits=E}}class tr extends Ke{constructor({logits:E}){super(),this.logits=E}}class nr extends Ke{constructor({start_logits:E,end_logits:V}){super(),this.start_logits=E,this.end_logits=V}}class fn extends Ke{constructor({logits:E}){super(),this.logits=E}}class Np extends Ke{constructor({logits:E,past_key_values:V}){super(),this.logits=E,this.past_key_values=V}}class Lc extends Ke{constructor({alphas:E}){super(),this.alphas=E}}class zc extends Ke{constructor({waveform:E,spectrogram:V}){super(),this.waveform=E,this.spectrogram=V}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(R,c,s)=>{s.r(c),s.d(c,{ASTFeatureExtractor:()=>I});var h=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var T=s("./src/utils/audio.js");class I extends h.FeatureExtractor{constructor(F){super(F);const _=this.config.sampling_rate,v=(0,T.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(_/2),_,null,"kaldi",!0);for(let w=0;w{s.r(c),s.d(c,{AutoFeatureExtractor:()=>U});var h=s("./src/utils/constants.js"),T=s("./src/utils/hub.js");s("./src/base/feature_extraction_utils.js");var I=s("./src/models/feature_extractors.js");class U{static async from_pretrained(_,v={}){const w=await(0,T.getModelJSON)(_,h.FEATURE_EXTRACTOR_NAME,!0,v),b=w.feature_extractor_type,x=I[b];if(!x)throw new Error(`Unknown feature_extractor_type: '${b}'. Please report this at ${h.GITHUB_ISSUE_URL}.`);return new x(w)}}},"./src/models/auto/image_processing_auto.js":(R,c,s)=>{s.r(c),s.d(c,{AutoImageProcessor:()=>F});var h=s("./src/utils/constants.js"),T=s("./src/utils/hub.js"),I=s("./src/base/image_processors_utils.js"),U=s("./src/models/image_processors.js");class F{static async from_pretrained(v,w={}){const b=await(0,T.getModelJSON)(v,h.IMAGE_PROCESSOR_NAME,!0,w),x=b.image_processor_type??b.feature_extractor_type;let O=U[x];return O||(x!==void 0&&console.warn(`Image processor type '${x}' not found, assuming base ImageProcessor. Please report this at ${h.GITHUB_ISSUE_URL}.`),O=I.ImageProcessor),new O(b)}}},"./src/models/auto/processing_auto.js":(R,c,s)=>{s.r(c),s.d(c,{AutoProcessor:()=>v});var h=s("./src/utils/constants.js"),T=s("./src/utils/hub.js"),I=s("./src/base/processing_utils.js"),U=s("./src/models/processors.js"),F=s("./src/models/image_processors.js"),_=s("./src/models/feature_extractors.js");class v{static async from_pretrained(b,x={}){const O=await(0,T.getModelJSON)(b,h.IMAGE_PROCESSOR_NAME,!0,x),{image_processor_type:H,feature_extractor_type:re,processor_class:ne}=O;if(ne&&U[ne])return U[ne].from_pretrained(b,x);if(!H&&!re)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const G={};if(H){const X=F[H];if(!X)throw new Error(`Unknown image_processor_type: '${H}'.`);G.image_processor=new X(O)}if(re){const X=F[re];if(X)G.image_processor=new X(O);else{const D=_[re];if(!D)throw new Error(`Unknown feature_extractor_type: '${re}'.`);G.feature_extractor=new D(O)}}const W={};return new I.Processor(W,G)}}},"./src/models/beit/image_processing_beit.js":(R,c,s)=>{s.r(c),s.d(c,{BeitFeatureExtractor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(R,c,s)=>{s.r(c),s.d(c,{BitImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(R,c,s)=>{s.r(c),s.d(c,{ChineseCLIPFeatureExtractor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(R,c,s)=>{s.r(c),s.d(c,{ClapFeatureExtractor:()=>I});var h=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var T=s("./src/utils/audio.js");class I extends h.FeatureExtractor{constructor(F){super(F),this.mel_filters=(0,T.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,T.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,T.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(F,_,v,w){let b;const x=F.length-_;if(x>0)if(v==="rand_trunc"){const O=Math.floor(Math.random()*(x+1));F=F.subarray(O,O+_),b=await this._extract_fbank_features(F,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(x<0){let O=new Float64Array(_);if(O.set(F),w==="repeat")for(let H=F.length;H<_;H+=F.length)O.set(F.subarray(0,Math.min(F.length,_-H)),H);else if(w==="repeatpad")for(let H=F.length;H<-x;H+=F.length)O.set(F,H);F=O}if(v==="fusion")throw new Error(`Truncation strategy "${v}" not implemented`);b=await this._extract_fbank_features(F,this.mel_filters_slaney,this.config.nb_max_samples)}return b.unsqueeze_(0)}async _extract_fbank_features(F,_,v=null){return(0,T.spectrogram)(F,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:_,log_mel:"dB",max_num_frames:v,do_pad:!1,transpose:!0})}async _call(F,{max_length:_=null}={}){return(0,h.validate_audio_inputs)(F,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(F,_??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}},"./src/models/clip/image_processing_clip.js":(R,c,s)=>{s.r(c),s.d(c,{CLIPFeatureExtractor:()=>I,CLIPImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/convnext/image_processing_convnext.js":(R,c,s)=>{s.r(c),s.d(c,{ConvNextFeatureExtractor:()=>I,ConvNextImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{constructor(F){super(F),this.crop_pct=this.config.crop_pct??224/256}async resize(F){var v;const _=(v=this.size)==null?void 0:v.shortest_edge;if(_===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(_<384){const w=Math.floor(_/this.crop_pct),[b,x]=this.get_resize_output_image_size(F,{shortest_edge:w});F=await F.resize(b,x,{resample:this.resample}),F=await F.center_crop(_,_)}else F=await F.resize(_,_,{resample:this.resample});return F}}class I extends T{}},"./src/models/deit/image_processing_deit.js":(R,c,s)=>{s.r(c),s.d(c,{DeiTFeatureExtractor:()=>I,DeiTImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/detr/image_processing_detr.js":(R,c,s)=>{s.r(c),s.d(c,{DetrFeatureExtractor:()=>U,DetrImageProcessor:()=>I});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/tensor.js");class I extends h.ImageProcessor{async _call(_){const v=await super._call(_),w=[v.pixel_values.dims[0],64,64],b=(0,T.full)(w,1n);return{...v,pixel_mask:b}}post_process_object_detection(..._){return(0,h.post_process_object_detection)(..._)}post_process_panoptic_segmentation(..._){return(0,h.post_process_panoptic_segmentation)(..._)}post_process_instance_segmentation(..._){return(0,h.post_process_instance_segmentation)(..._)}}class U extends I{}},"./src/models/donut/image_processing_donut.js":(R,c,s)=>{s.r(c),s.d(c,{DonutFeatureExtractor:()=>I,DonutImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{pad_image(F,_,v,w={}){const[b,x,O]=_;let H=this.image_mean;Array.isArray(this.image_mean)||(H=new Array(O).fill(H));let re=this.image_std;Array.isArray(re)||(re=new Array(O).fill(H));const ne=H.map((G,W)=>-G/re[W]);return super.pad_image(F,_,v,{center:!0,constant_values:ne,...w})}}class I extends T{}},"./src/models/dpt/image_processing_dpt.js":(R,c,s)=>{s.r(c),s.d(c,{DPTFeatureExtractor:()=>I,DPTImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/efficientnet/image_processing_efficientnet.js":(R,c,s)=>{s.r(c),s.d(c,{EfficientNetImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{constructor(U){super(U),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(F=>F*F))}}},"./src/models/feature_extractors.js":(R,c,s)=>{s.r(c),s.d(c,{ASTFeatureExtractor:()=>h.ASTFeatureExtractor,ClapFeatureExtractor:()=>T.ClapFeatureExtractor,ImageFeatureExtractor:()=>x.ImageProcessor,MoonshineFeatureExtractor:()=>I.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>U.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>F.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>_.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>w.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>b.WhisperFeatureExtractor});var h=s("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),T=s("./src/models/clap/feature_extraction_clap.js"),I=s("./src/models/moonshine/feature_extraction_moonshine.js"),U=s("./src/models/pyannote/feature_extraction_pyannote.js"),F=s("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),_=s("./src/models/speecht5/feature_extraction_speecht5.js"),v=s("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),w=s("./src/models/wespeaker/feature_extraction_wespeaker.js"),b=s("./src/models/whisper/feature_extraction_whisper.js"),x=s("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(R,c,s)=>{s.r(c),s.d(c,{Florence2Processor:()=>U});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");class U extends h.Processor{constructor(_,v){super(_,v);const{tasks_answer_post_processing_type:w,task_prompts_without_inputs:b,task_prompts_with_input:x}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(w??{})),this.task_prompts_without_inputs=new Map(Object.entries(b??{})),this.task_prompts_with_input=new Map(Object.entries(x??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(_){typeof _=="string"&&(_=[_]);const v=[];for(const w of _)if(this.task_prompts_without_inputs.has(w))v.push(this.task_prompts_without_inputs.get(w));else{for(const[b,x]of this.task_prompts_with_input)if(w.includes(b)){v.push(x.replaceAll("{input}",w).replaceAll(b,""));break}v.length!==_.length&&v.push(w)}return v}post_process_generation(_,v,w){const b=this.tasks_answer_post_processing_type.get(v)??"pure_text";_=_.replaceAll("","").replaceAll("","");let x;switch(b){case"pure_text":x=_;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const O=b==="ocr"?"quad_boxes":"bboxes",H=_.matchAll(this.regexes[O]),re=[],ne=[];for(const[G,W,...X]of H)re.push(W?W.trim():re.at(-1)??""),ne.push(X.map((D,A)=>(Number(D)+.5)/this.size_per_bin*w[A%2]));x={labels:re,[O]:ne};break;default:throw new Error(`Task "${v}" (of type "${b}") not yet implemented.`)}return{[v]:x}}async _call(_,v=null,w={}){if(!_&&!v)throw new Error("Either text or images must be provided");const b=await this.image_processor(_,w),x=v?this.tokenizer(v,w):{};return{...b,...x}}}_e(U,"tokenizer_class",I.AutoTokenizer),_e(U,"image_processor_class",T.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(R,c,s)=>{s.r(c),s.d(c,{GLPNFeatureExtractor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(R,c,s)=>{s.r(c),s.d(c,{GroundingDinoImageProcessor:()=>I});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/tensor.js");class I extends h.ImageProcessor{async _call(F){const _=await super._call(F),v=_.pixel_values.dims,w=(0,T.ones)([v[0],v[2],v[3]]);return{..._,pixel_mask:w}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(R,c,s)=>{s.r(c),s.d(c,{GroundingDinoProcessor:()=>_});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js"),U=s("./src/base/image_processors_utils.js");function F(v,w){const x=v.dims.at(-1)-1,O=v.tolist();O.fill(!1,0,1),O.fill(!1,x);const H=w.tolist();return O.map((re,ne)=>re?ne:null).filter(re=>re!==null).map(re=>H[re])}class _ extends h.Processor{async _call(w,b,x={}){const O=w?await this.image_processor(w,x):{};return{...b?this.tokenizer(b,x):{},...O}}post_process_grounded_object_detection(w,b,{box_threshold:x=.25,text_threshold:O=.25,target_sizes:H=null}={}){const{logits:re,pred_boxes:ne}=w,G=re.dims[0];if(H!==null&&H.length!==G)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const W=re.dims.at(1),X=re.sigmoid(),D=X.max(-1).tolist(),A=ne.tolist().map(P=>P.map(L=>(0,U.center_to_corners_format)(L))),M=[];for(let P=0;Pie.map((Pe,pe)=>Pe*L[(pe+1)%2])));const le=D[P],oe=[],Te=[],we=[];for(let ie=0;ie{s.r(c),s.d(c,{Idefics3ImageProcessor:()=>I});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/tensor.js");class I extends h.ImageProcessor{constructor(F){super(F),this.do_image_splitting=F.do_image_splitting??!0,this.max_image_size=F.max_image_size}get_resize_for_vision_encoder(F,_){let[v,w]=F.dims.slice(-2);const b=w/v;return w>=v?(w=Math.ceil(w/_)*_,v=Math.floor(w/b),v=Math.ceil(v/_)*_):(v=Math.ceil(v/_)*_,w=Math.floor(v*b),w=Math.ceil(w/_)*_),{height:v,width:w}}async _call(F,{do_image_splitting:_=null,return_row_col_info:v=!1}={}){let w;if(!Array.isArray(F))w=[[F]];else{if(F.length===0||!F[0])throw new Error("No images provided.");Array.isArray(F[0])?w=F:w=[F]}let b=[],x=[],O=[];const H=[],re=[];for(const P of w){let L=await Promise.all(P.map(Te=>this.preprocess(Te)));H.push(...L.map(Te=>Te.original_size)),re.push(...L.map(Te=>Te.reshaped_input_size)),L.forEach(Te=>Te.pixel_values.unsqueeze_(0));const{longest_edge:le}=this.max_image_size;let oe;if(_??this.do_image_splitting){let Te=new Array(L.length),we=new Array(L.length);oe=await Promise.all(L.map(async(ie,Pe)=>{const pe=this.get_resize_for_vision_encoder(ie.pixel_values,le),ke=await(0,T.interpolate_4d)(ie.pixel_values,{size:[pe.height,pe.width]}),{frames:Oe,num_splits_h:Ce,num_splits_w:tt}=await this.split_image(ke,this.max_image_size);return Te[Pe]=Ce,we[Pe]=tt,(0,T.cat)(Oe,0)})),x.push(Te),O.push(we)}else{const Te=[le,le];oe=await Promise.all(L.map(we=>(0,T.interpolate_4d)(we.pixel_values,{size:Te}))),x.push(new Array(L.length).fill(0)),O.push(new Array(L.length).fill(0))}b.push((0,T.cat)(oe,0))}const ne=b.length,[G,W,X,D]=b[0].dims;let A,M;if(ne===1)A=b[0].unsqueeze_(0),M=(0,T.full)([ne,G,X,D],!0);else{const P=Math.max(...b.map(oe=>oe.dims.at(0)));M=(0,T.full)([ne,P,X,D],!0);const L=M.data,le=P*X*D;for(let oe=0;oev||O>w){H=Math.ceil(x/v),re=Math.ceil(O/w);const ne=Math.ceil(x/H),G=Math.ceil(O/re);for(let D=0;D{s.r(c),s.d(c,{Idefics3Processor:()=>w});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");s("./src/utils/image.js");var U=s("./src/utils/core.js");function F(b,x,O,H,re,ne){let G="";for(let W=0;W`+re.repeat(b);G+=` +`}return G+=` +${H}${ne}`+re.repeat(b)+`${H}`,G}function _(b,x,O,H){return`${x}${H}`+O.repeat(b)+`${x}`}function v(b,x,O,H,re,ne){return b===0&&x===0?_(O,H,re,ne):F(O,b,x,H,re,ne)}class w extends h.Processor{constructor(){super(...arguments);_e(this,"fake_image_token","");_e(this,"image_token","");_e(this,"global_img_token","")}async _call(O,H=null,re={}){re.return_row_col_info??(re.return_row_col_info=!0);let ne;H&&(ne=await this.image_processor(H,re)),Array.isArray(O)||(O=[O]);const G=ne.rows??[new Array(O.length).fill(0)],W=ne.cols??[new Array(O.length).fill(0)],X=this.config.image_seq_len,D=[],A=[];for(let P=0;Pv(Pe,oe[pe],X,this.fake_image_token,this.image_token,this.global_img_token)),we=L.split(this.image_token);if(we.length===0)throw new Error("The image token should be present in the text.");let ie=we[0];for(let Pe=0;Pe{s.r(c),s.d(c,{BeitFeatureExtractor:()=>h.BeitFeatureExtractor,BitImageProcessor:()=>T.BitImageProcessor,CLIPFeatureExtractor:()=>U.CLIPFeatureExtractor,CLIPImageProcessor:()=>U.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>I.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>F.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>F.ConvNextImageProcessor,DPTFeatureExtractor:()=>b.DPTFeatureExtractor,DPTImageProcessor:()=>b.DPTImageProcessor,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTImageProcessor:()=>_.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>w.DonutFeatureExtractor,DonutImageProcessor:()=>w.DonutImageProcessor,EfficientNetImageProcessor:()=>x.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>O.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>H.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>re.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>G.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>W.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>X.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>D.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>D.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>A.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>A.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>P.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>P.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>L.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>L.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>le.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>le.MobileViTImageProcessor,NougatImageProcessor:()=>oe.NougatImageProcessor,OwlViTFeatureExtractor:()=>we.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>we.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Te.Owlv2ImageProcessor,Phi3VImageProcessor:()=>ie.Phi3VImageProcessor,PvtImageProcessor:()=>Pe.PvtImageProcessor,Qwen2VLImageProcessor:()=>pe.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ke.RTDetrImageProcessor,SamImageProcessor:()=>Oe.SamImageProcessor,SegformerFeatureExtractor:()=>Ce.SegformerFeatureExtractor,SegformerImageProcessor:()=>Ce.SegformerImageProcessor,SiglipImageProcessor:()=>tt.SiglipImageProcessor,Swin2SRImageProcessor:()=>Ge.Swin2SRImageProcessor,VLMImageProcessor:()=>ne.VLMImageProcessor,ViTFeatureExtractor:()=>be.ViTFeatureExtractor,ViTImageProcessor:()=>be.ViTImageProcessor,VitMatteImageProcessor:()=>Z.VitMatteImageProcessor,VitPoseImageProcessor:()=>ce.VitPoseImageProcessor,YolosFeatureExtractor:()=>Se.YolosFeatureExtractor,YolosImageProcessor:()=>Se.YolosImageProcessor});var h=s("./src/models/beit/image_processing_beit.js"),T=s("./src/models/bit/image_processing_bit.js"),I=s("./src/models/chinese_clip/image_processing_chinese_clip.js"),U=s("./src/models/clip/image_processing_clip.js"),F=s("./src/models/convnext/image_processing_convnext.js"),_=s("./src/models/deit/image_processing_deit.js"),v=s("./src/models/detr/image_processing_detr.js"),w=s("./src/models/donut/image_processing_donut.js"),b=s("./src/models/dpt/image_processing_dpt.js"),x=s("./src/models/efficientnet/image_processing_efficientnet.js"),O=s("./src/models/glpn/image_processing_glpn.js"),H=s("./src/models/grounding_dino/image_processing_grounding_dino.js"),re=s("./src/models/idefics3/image_processing_idefics3.js"),ne=s("./src/models/janus/image_processing_janus.js"),G=s("./src/models/jina_clip/image_processing_jina_clip.js"),W=s("./src/models/llava_onevision/image_processing_llava_onevision.js"),X=s("./src/models/mask2former/image_processing_mask2former.js"),D=s("./src/models/maskformer/image_processing_maskformer.js"),A=s("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=s("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),P=s("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),L=s("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),le=s("./src/models/mobilevit/image_processing_mobilevit.js"),oe=s("./src/models/nougat/image_processing_nougat.js"),Te=s("./src/models/owlv2/image_processing_owlv2.js"),we=s("./src/models/owlvit/image_processing_owlvit.js"),ie=s("./src/models/phi3_v/image_processing_phi3_v.js"),Pe=s("./src/models/pvt/image_processing_pvt.js"),pe=s("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ke=s("./src/models/rt_detr/image_processing_rt_detr.js"),Oe=s("./src/models/sam/image_processing_sam.js"),Ce=s("./src/models/segformer/image_processing_segformer.js"),tt=s("./src/models/siglip/image_processing_siglip.js"),Ge=s("./src/models/swin2sr/image_processing_swin2sr.js"),be=s("./src/models/vit/image_processing_vit.js"),Z=s("./src/models/vitmatte/image_processing_vitmatte.js"),ce=s("./src/models/vitpose/image_processing_vitpose.js"),Se=s("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(R,c,s)=>{s.r(c),s.d(c,{VLMImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{constructor(U){super({do_pad:!0,pad_size:{width:U.image_size,height:U.image_size},...U}),this.constant_values=this.config.background_color.map(F=>F*this.rescale_factor)}pad_image(U,F,_,v){return super.pad_image(U,F,_,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(R,c,s)=>{s.r(c),s.d(c,{VLChatProcessor:()=>v});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js"),U=s("./src/utils/core.js"),F=s("./src/utils/tensor.js"),_=s("./src/utils/image.js");class v extends h.Processor{constructor(b,x){super(b,x),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(b,{images:x=null,chat_template:O="default"}={}){x?Array.isArray(x)||(x=[x]):x=await Promise.all(b.filter(oe=>oe.images).flatMap(oe=>oe.images).map(oe=>_.RawImage.read(oe)));const H=this.tokenizer,re=H.apply_chat_template(b,{tokenize:!1,add_generation_prompt:!0,chat_template:O}),ne=oe=>H.encode(oe,{add_special_tokens:!1}),G=re.split(this.image_tag),W=G.length-1;if(x.length!==W)throw new Error(`Number of images provided (${x.length}) does not match number of "${this.image_tag}" image tags (${W})`);const[X,D,A]=H.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=ne(G[0]),P=new Array(M.length).fill(!1);for(let oe=1;oe0){const oe=await this.image_processor(x);return oe.pixel_values.unsqueeze_(0),{...le,...oe}}return le}}_e(v,"image_processor_class",T.AutoImageProcessor),_e(v,"tokenizer_class",I.AutoTokenizer),_e(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(R,c,s)=>{s.r(c),s.d(c,{JinaCLIPImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{constructor(U){const{resize_mode:F,fill_color:_,interpolation:v,size:w,...b}=U,x=F==="squash"?{width:w,height:w}:F==="shortest"?{shortest_edge:w}:{longest_edge:w},O=v==="bicubic"?3:2;super({...b,size:x,resample:O,do_center_crop:!0,crop_size:w,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(R,c,s)=>{s.r(c),s.d(c,{JinaCLIPProcessor:()=>U});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");class U extends h.Processor{async _call(_=null,v=null,w={}){if(!_&&!v)throw new Error("Either text or images must be provided");const b=_?this.tokenizer(_,w):{},x=v?await this.image_processor(v,w):{};return{...b,...x}}}_e(U,"tokenizer_class",I.AutoTokenizer),_e(U,"image_processor_class",T.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(R,c,s)=>{s.r(c),s.d(c,{LlavaOnevisionImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(R,c,s)=>{s.r(c),s.d(c,{Mask2FormerImageProcessor:()=>T});var h=s("./src/models/maskformer/image_processing_maskformer.js");class T extends h.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(R,c,s)=>{s.r(c),s.d(c,{MaskFormerFeatureExtractor:()=>I,MaskFormerImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{post_process_panoptic_segmentation(...F){return(0,h.post_process_panoptic_segmentation)(...F)}post_process_instance_segmentation(...F){return(0,h.post_process_instance_segmentation)(...F)}}class I extends T{}},"./src/models/mgp_str/processing_mgp_str.js":(R,c,s)=>{s.r(c),s.d(c,{MgpstrProcessor:()=>_});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js"),U=s("./src/utils/maths.js");const F={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class _ extends h.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(w,b){if(!F.hasOwnProperty(b))throw new Error(`Format ${b} is not supported.`);const[x,O]=F[b],H=this[x].bind(this),[re,ne]=w.dims,G=[],W=[],X=w.tolist();for(let A=0;A0?L.reduce((oe,Te)=>oe*Te,1):0;W.push(P),G.push(le)}return[H(W),G]}char_decode(w){return this.char_tokenizer.batch_decode(w).map(b=>b.replaceAll(" ",""))}bpe_decode(w){return this.bpe_tokenizer.batch_decode(w)}wp_decode(w){return this.wp_tokenizer.batch_decode(w).map(b=>b.replaceAll(" ",""))}batch_decode([w,b,x]){const[O,H]=this._decode_helper(w,"char"),[re,ne]=this._decode_helper(b,"bpe"),[G,W]=this._decode_helper(x,"wp"),X=[],D=[];for(let A=0;A{s.r(c),s.d(c,{MobileNetV1FeatureExtractor:()=>I,MobileNetV1ImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(R,c,s)=>{s.r(c),s.d(c,{MobileNetV2FeatureExtractor:()=>I,MobileNetV2ImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(R,c,s)=>{s.r(c),s.d(c,{MobileNetV3FeatureExtractor:()=>I,MobileNetV3ImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(R,c,s)=>{s.r(c),s.d(c,{MobileNetV4FeatureExtractor:()=>I,MobileNetV4ImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/mobilevit/image_processing_mobilevit.js":(R,c,s)=>{s.r(c),s.d(c,{MobileViTFeatureExtractor:()=>I,MobileViTImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/moonshine/feature_extraction_moonshine.js":(R,c,s)=>{s.r(c),s.d(c,{MoonshineFeatureExtractor:()=>I});var h=s("./src/base/feature_extraction_utils.js"),T=s("./src/utils/tensor.js");class I extends h.FeatureExtractor{async _call(F){(0,h.validate_audio_inputs)(F,"MoonshineFeatureExtractor"),F instanceof Float64Array&&(F=new Float32Array(F));const _=[1,F.length];return{input_values:new T.Tensor("float32",F,_)}}}},"./src/models/moonshine/processing_moonshine.js":(R,c,s)=>{s.r(c),s.d(c,{MoonshineProcessor:()=>U});var h=s("./src/models/auto/feature_extraction_auto.js"),T=s("./src/tokenizers.js"),I=s("./src/base/processing_utils.js");class U extends I.Processor{async _call(_){return await this.feature_extractor(_)}}_e(U,"tokenizer_class",T.AutoTokenizer),_e(U,"feature_extractor_class",h.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(R,c,s)=>{s.r(c),s.d(c,{NougatImageProcessor:()=>T});var h=s("./src/models/donut/image_processing_donut.js");class T extends h.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(R,c,s)=>{s.r(c),s.d(c,{Owlv2ImageProcessor:()=>T});var h=s("./src/models/owlvit/image_processing_owlvit.js");class T extends h.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(R,c,s)=>{s.r(c),s.d(c,{OwlViTFeatureExtractor:()=>I,OwlViTImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{post_process_object_detection(...F){return(0,h.post_process_object_detection)(...F)}}class I extends T{}},"./src/models/owlvit/processing_owlvit.js":(R,c,s)=>{s.r(c),s.d(c,{OwlViTProcessor:()=>U});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");class U extends h.Processor{}_e(U,"tokenizer_class",I.AutoTokenizer),_e(U,"image_processor_class",T.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(R,c,s)=>{s.r(c),s.d(c,{PaliGemmaProcessor:()=>_});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");const U="";function F(v,w,b,x,O){return`${x.repeat(b*O)}${w}${v} +`}class _ extends h.Processor{async _call(w,b=null,x={}){b||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),b=""),Array.isArray(w)||(w=[w]),Array.isArray(b)||(b=[b]);const O=this.tokenizer.bos_token,H=this.image_processor.config.image_seq_length;let re;b.some(W=>W.includes(U))?re=b.map(W=>{const X=W.replaceAll(U,U.repeat(H)),D=X.lastIndexOf(U),A=D===-1?0:D+U.length;return X.slice(0,A)+O+X.slice(A)+` +`}):(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=b.map(W=>F(W,O,H,U,w.length)));const ne=this.tokenizer(re,x);return{...await this.image_processor(w,x),...ne}}}_e(_,"tokenizer_class",I.AutoTokenizer),_e(_,"image_processor_class",T.AutoImageProcessor),_e(_,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(R,c,s)=>{s.r(c),s.d(c,{Phi3VImageProcessor:()=>w});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/tensor.js");const I=336,U=[2,3],{ceil:F,floor:_,sqrt:v}=Math;class w extends h.ImageProcessor{constructor(x){super({...x,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=x.num_crops}calc_num_image_tokens_from_image_size(x,O){const{num_img_tokens:H}=this.config;return _((_(O/I)*_(x/I)+1)*H+1+(_(O/I)+1)*v(H))}get_resize_output_image_size(x,O){const H=this._num_crops,[re,ne]=x.size;let G=re/ne,W=1;for(;W*Math.ceil(W/G)<=H;)W+=1;W-=1;const X=Math.floor(W*336),D=Math.floor(X/G);return[X,D]}pad_image(x,O,H,re={}){const[ne,G]=O,W=I*F(ne/I),X=I*F(G/I),D=[1,1,1].map((A,M)=>(A-this.image_mean[M])/this.image_std[M]);return super.pad_image(x,O,{width:X,height:W},{center:!0,constant_values:D,...re})}async _call(x,{num_crops:O=null}={}){if(this._num_crops=O??(O=this.config.num_crops),O<4||v(O)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(x)||(x=[x]);const H=x.length,re=await Promise.all(x.map(P=>this.preprocess(P))),ne=re.map(P=>P.original_size),G=re.map(P=>P.reshaped_input_size),W=[];for(const{pixel_values:P}of re){P.unsqueeze_(0);const[L,le]=P.dims.slice(-2),oe=await(0,T.interpolate_4d)(P,{size:[I,I],mode:"bicubic"});if(O>0){const Te=[],we=v(O),ie=_(le/we),Pe=_(L/we);for(let ke=0;keP.map(L=>I*F(L/I))),A=new T.Tensor("int64",D.flat(),[H,2]),M=D.map(([P,L])=>this.calc_num_image_tokens_from_image_size(L,P));return{pixel_values:X,original_sizes:ne,reshaped_input_sizes:G,image_sizes:A,num_img_tokens:M}}}},"./src/models/phi3_v/processing_phi3_v.js":(R,c,s)=>{s.r(c),s.d(c,{Phi3VProcessor:()=>_});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");s("./src/utils/image.js");const U="<|image|>",F=/<\|image_\d+\|>/g;class _ extends h.Processor{async _call(w,b=null,{padding:x=!0,truncation:O=!0,num_crops:H=null}={}){Array.isArray(w)||(w=[w]);let re,ne;if(b){ne=await this.image_processor(b,{num_crops:H});const{num_img_tokens:G}=ne,W=w.map((D,A)=>D.split(F).join(U.repeat(G[A])));re=this.tokenizer(W,{padding:x,truncation:O});const X=this.tokenizer.model.convert_tokens_to_ids([U])[0];re.input_ids.map_(D=>D==X?-D:D)}else re=this.tokenizer(w);return{...re,...ne}}}_e(_,"image_processor_class",T.AutoImageProcessor),_e(_,"tokenizer_class",I.AutoTokenizer)},"./src/models/processors.js":(R,c,s)=>{s.r(c),s.d(c,{Florence2Processor:()=>h.Florence2Processor,GroundingDinoProcessor:()=>T.GroundingDinoProcessor,Idefics3Processor:()=>I.Idefics3Processor,JinaCLIPProcessor:()=>F.JinaCLIPProcessor,MgpstrProcessor:()=>_.MgpstrProcessor,MoonshineProcessor:()=>v.MoonshineProcessor,OwlViTProcessor:()=>w.OwlViTProcessor,PaliGemmaProcessor:()=>x.PaliGemmaProcessor,Phi3VProcessor:()=>b.Phi3VProcessor,PyAnnoteProcessor:()=>O.PyAnnoteProcessor,Qwen2VLProcessor:()=>H.Qwen2VLProcessor,SamProcessor:()=>re.SamProcessor,SpeechT5Processor:()=>ne.SpeechT5Processor,VLChatProcessor:()=>U.VLChatProcessor,Wav2Vec2Processor:()=>G.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>W.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>X.WhisperProcessor});var h=s("./src/models/florence2/processing_florence2.js"),T=s("./src/models/grounding_dino/processing_grounding_dino.js"),I=s("./src/models/idefics3/processing_idefics3.js"),U=s("./src/models/janus/processing_janus.js"),F=s("./src/models/jina_clip/processing_jina_clip.js"),_=s("./src/models/mgp_str/processing_mgp_str.js"),v=s("./src/models/moonshine/processing_moonshine.js"),w=s("./src/models/owlvit/processing_owlvit.js"),b=s("./src/models/phi3_v/processing_phi3_v.js"),x=s("./src/models/paligemma/processing_paligemma.js"),O=s("./src/models/pyannote/processing_pyannote.js"),H=s("./src/models/qwen2_vl/processing_qwen2_vl.js"),re=s("./src/models/sam/processing_sam.js"),ne=s("./src/models/speecht5/processing_speecht5.js"),G=s("./src/models/wav2vec2/processing_wav2vec2.js"),W=s("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),X=s("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(R,c,s)=>{s.r(c),s.d(c,{PvtImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(R,c,s)=>{s.r(c),s.d(c,{PyAnnoteFeatureExtractor:()=>U});var h=s("./src/base/feature_extraction_utils.js"),T=s("./src/utils/tensor.js"),I=s("./src/utils/maths.js");class U extends h.FeatureExtractor{async _call(_){(0,h.validate_audio_inputs)(_,"PyAnnoteFeatureExtractor"),_ instanceof Float64Array&&(_=new Float32Array(_));const v=[1,1,_.length];return{input_values:new T.Tensor("float32",_,v)}}samples_to_frames(_){return(_-this.config.offset)/this.config.step}post_process_speaker_diarization(_,v){const w=v/this.samples_to_frames(v)/this.config.sampling_rate,b=[];for(const x of _.tolist()){const O=[];let H=-1;for(let re=0;re({id:re,start:ne*w,end:G*w,confidence:W/(G-ne)})))}return b}}},"./src/models/pyannote/processing_pyannote.js":(R,c,s)=>{s.r(c),s.d(c,{PyAnnoteProcessor:()=>I});var h=s("./src/base/processing_utils.js"),T=s("./src/models/pyannote/feature_extraction_pyannote.js");class I extends h.Processor{async _call(F){return await this.feature_extractor(F)}post_process_speaker_diarization(...F){return this.feature_extractor.post_process_speaker_diarization(...F)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}_e(I,"feature_extractor_class",T.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(R,c,s)=>{s.r(c),s.d(c,{Qwen2VLImageProcessor:()=>I});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/tensor.js");class I extends h.ImageProcessor{async _call(F,..._){const{pixel_values:v,original_sizes:w,reshaped_input_sizes:b}=await super._call(F,..._);let x=v;const{temporal_patch_size:O,merge_size:H,patch_size:re}=this.config;x.dims[0]===1&&(x=(0,T.cat)(Array.from({length:O},()=>x),0));const ne=x.dims[0]/O,G=x.dims[1],W=Math.floor(x.dims[2]/re),X=Math.floor(x.dims[3]/re),D=x.view(ne,O,G,Math.floor(W/H),H,re,Math.floor(X/H),H,re).permute(0,3,6,4,7,2,1,5,8).view(ne*W*X,G*O*re*re),A=new T.Tensor("int64",[ne,W,X],[1,3]);return{pixel_values:D,image_grid_thw:A,original_sizes:w,reshaped_input_sizes:b}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(R,c,s)=>{s.r(c),s.d(c,{Qwen2VLProcessor:()=>U});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js"),I=s("./src/tokenizers.js");s("./src/utils/image.js");class U extends h.Processor{async _call(_,v=null,...w){Array.isArray(_)||(_=[_]);let b,x;if(v&&(b=await this.image_processor(v),x=b.image_grid_thw),x){let H=this.image_processor.config.merge_size**2,re=0;const ne=x.tolist();_=_.map(G=>{for(;G.includes("<|image_pad|>");){const W=Number(ne[re++].reduce((X,D)=>X*D,1n));G=G.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(W/H)))}return G.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(_),...b}}}_e(U,"image_processor_class",T.AutoImageProcessor),_e(U,"tokenizer_class",I.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(R,c,s)=>{s.r(c),s.d(c,{RTDetrImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{post_process_object_detection(...U){return(0,h.post_process_object_detection)(...U)}}},"./src/models/sam/image_processing_sam.js":(R,c,s)=>{s.r(c),s.d(c,{SamImageProcessor:()=>U});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/core.js"),I=s("./src/utils/tensor.js");class U extends h.ImageProcessor{reshape_input_points(_,v,w,b=!1){_=structuredClone(_);let x=(0,T.calculateDimensions)(_);if(x.length===3)b||(x=[1,...x]),_=[_];else if(x.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let O=0;O<_.length;++O){let H=v[O],re=w[O],ne=[re[0]/H[0],re[1]/H[1]];for(let G=0;G<_[O].length;++G)for(let W=0;W<_[O][G].length;++W)for(let X=0;X<_[O][G][W].length;++X)_[O][G][W][X]*=ne[X%2]}return new I.Tensor("float32",Float32Array.from(_.flat(1/0)),x)}add_input_labels(_,v){let w=(0,T.calculateDimensions)(_);if(w.length===2)w=[1,...w],_=[_];else if(w.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(w.some((b,x)=>b!==v.dims[x]))throw Error(`The first ${w.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new I.Tensor("int64",_.flat(1/0).map(BigInt),w)}async _call(_,{input_points:v=null,input_labels:w=null,input_boxes:b=null}={}){const x=await super._call(_);if(v&&(x.input_points=this.reshape_input_points(v,x.original_sizes,x.reshaped_input_sizes)),w){if(!x.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");x.input_labels=this.add_input_labels(w,x.input_points)}return b&&(x.input_boxes=this.reshape_input_points(b,x.original_sizes,x.reshaped_input_sizes,!0)),x}async post_process_masks(_,v,w,{mask_threshold:b=0,binarize:x=!0,pad_size:O=null}={}){const H=[];O=O??this.pad_size;const re=[O.height,O.width];for(let ne=0;neb&&(A[M]=1);X=new I.Tensor("bool",A,X.dims)}H.push(X)}return H}generate_crop_boxes(_,v,{crop_n_layers:w=0,overlap_ratio:b=512/1500,points_per_crop:x=32,crop_n_points_downscale_factor:O=1}={}){}}},"./src/models/sam/processing_sam.js":(R,c,s)=>{s.r(c),s.d(c,{SamProcessor:()=>I});var h=s("./src/base/processing_utils.js"),T=s("./src/models/auto/image_processing_auto.js");class I extends h.Processor{async _call(...F){return await this.image_processor(...F)}post_process_masks(...F){return this.image_processor.post_process_masks(...F)}reshape_input_points(...F){return this.image_processor.reshape_input_points(...F)}}_e(I,"image_processor_class",T.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(R,c,s)=>{s.r(c),s.d(c,{SeamlessM4TFeatureExtractor:()=>U});var h=s("./src/base/feature_extraction_utils.js"),T=s("./src/utils/tensor.js"),I=s("./src/utils/audio.js");class U extends h.FeatureExtractor{constructor(_){super(_);const v=this.config.sampling_rate,w=(0,I.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let b=0;bw*32768),(0,I.spectrogram)(_,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:v,transpose:!0})}async _call(_,{padding:v=!0,pad_to_multiple_of:w=2,do_normalize_per_mel_bins:b=!0,return_attention_mask:x=!0}={}){(0,h.validate_audio_inputs)(_,"SeamlessM4TFeatureExtractor");let O=await this._extract_fbank_features(_,this.config.max_length);if(b){const[A,M]=O.dims,P=O.data;for(let L=0;L0){const le=new Float32Array(M*(A+L));le.set(P),le.fill(this.config.padding_value,P.length);const oe=A+L;O=new T.Tensor(O.type,le,[oe,M]),x&&(H=new T.Tensor("int64",new BigInt64Array(oe),[1,oe]),H.data.fill(1n,0,A))}}const[re,ne]=O.dims,G=this.config.stride;if(re%G!==0)throw new Error(`The number of frames (${re}) must be a multiple of the stride (${G}).`);const X=O.view(1,Math.floor(re/G),ne*G),D={input_features:X};if(x){const A=X.dims[1],M=new BigInt64Array(A);if(H){const P=H.data;for(let L=1,le=0;L{s.r(c),s.d(c,{SegformerFeatureExtractor:()=>I,SegformerImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{post_process_semantic_segmentation(...F){return(0,h.post_process_semantic_segmentation)(...F)}}class I extends T{}},"./src/models/siglip/image_processing_siglip.js":(R,c,s)=>{s.r(c),s.d(c,{SiglipImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(R,c,s)=>{s.r(c),s.d(c,{SpeechT5FeatureExtractor:()=>T});var h=s("./src/base/feature_extraction_utils.js");class T extends h.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(R,c,s)=>{s.r(c),s.d(c,{SpeechT5Processor:()=>U});var h=s("./src/base/processing_utils.js"),T=s("./src/tokenizers.js"),I=s("./src/models/auto/feature_extraction_auto.js");class U extends h.Processor{async _call(_){return await this.feature_extractor(_)}}_e(U,"tokenizer_class",T.AutoTokenizer),_e(U,"feature_extractor_class",I.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(R,c,s)=>{s.r(c),s.d(c,{Swin2SRImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{pad_image(U,F,_,v={}){const[w,b,x]=F;return super.pad_image(U,F,{width:b+(_-b%_)%_,height:w+(_-w%_)%_},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(R,c,s)=>{s.r(c),s.d(c,{ViTFeatureExtractor:()=>I,ViTImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{}class I extends T{}},"./src/models/vitmatte/image_processing_vitmatte.js":(R,c,s)=>{s.r(c),s.d(c,{VitMatteImageProcessor:()=>I});var h=s("./src/base/image_processors_utils.js"),T=s("./src/utils/tensor.js");class I extends h.ImageProcessor{async _call(F,_){Array.isArray(F)||(F=[F]),Array.isArray(_)||(_=[_]);const v=await Promise.all(F.map(x=>this.preprocess(x))),w=await Promise.all(_.map(x=>this.preprocess(x,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,T.stack)(v.map((x,O)=>(0,T.cat)([x.pixel_values,w[O].pixel_values],0)),0),original_sizes:v.map(x=>x.original_size),reshaped_input_sizes:v.map(x=>x.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(R,c,s)=>{s.r(c),s.d(c,{VitPoseImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{post_process_pose_estimation(U,F,{threshold:_=null}={}){const v=U.tolist(),[w,b,x,O]=U.dims,H=[];for(let re=0;re{s.r(c),s.d(c,{Wav2Vec2FeatureExtractor:()=>I});var h=s("./src/base/feature_extraction_utils.js"),T=s("./src/utils/tensor.js");class I extends h.FeatureExtractor{_zero_mean_unit_var_norm(F){const v=F.reduce((b,x)=>b+x,0)/F.length,w=F.reduce((b,x)=>b+(x-v)**2,0)/F.length;return F.map(b=>(b-v)/Math.sqrt(w+1e-7))}async _call(F){(0,h.validate_audio_inputs)(F,"Wav2Vec2FeatureExtractor"),F instanceof Float64Array&&(F=new Float32Array(F));let _=F;this.config.do_normalize&&(_=this._zero_mean_unit_var_norm(_));const v=[1,_.length];return{input_values:new T.Tensor("float32",_,v),attention_mask:new T.Tensor("int64",new BigInt64Array(_.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(R,c,s)=>{s.r(c),s.d(c,{Wav2Vec2Processor:()=>U});var h=s("./src/tokenizers.js"),T=s("./src/models/auto/feature_extraction_auto.js"),I=s("./src/base/processing_utils.js");class U extends I.Processor{async _call(_){return await this.feature_extractor(_)}}_e(U,"tokenizer_class",h.AutoTokenizer),_e(U,"feature_extractor_class",T.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(R,c,s)=>{s.r(c),s.d(c,{Wav2Vec2ProcessorWithLM:()=>U});var h=s("./src/tokenizers.js"),T=s("./src/models/auto/feature_extraction_auto.js"),I=s("./src/base/processing_utils.js");class U extends I.Processor{async _call(_){return await this.feature_extractor(_)}}_e(U,"tokenizer_class",h.AutoTokenizer),_e(U,"feature_extractor_class",T.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(R,c,s)=>{s.r(c),s.d(c,{WeSpeakerFeatureExtractor:()=>I});var h=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var T=s("./src/utils/audio.js");class I extends h.FeatureExtractor{constructor(F){super(F);const _=this.config.sampling_rate,v=(0,T.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(_/2),_,null,"kaldi",!0);for(let w=0;w_*32768),(0,T.spectrogram)(F,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(F){(0,h.validate_audio_inputs)(F,"WeSpeakerFeatureExtractor");const _=(await this._extract_fbank_features(F)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=_.mean(1).data,w=_.data,[b,x,O]=_.dims;for(let H=0;H{s.r(c),s.d(c,{WHISPER_LANGUAGE_MAPPING:()=>T,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>I,whisper_language_to_code:()=>U});const h=[["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"]],T=new Map(h),I=new Map([...h.map(([F,_])=>[_,F]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function U(F){F=F.toLowerCase();let _=I.get(F);if(_===void 0)if(T.has(F))_=F;else{const w=F.length===2?T.keys():T.values();throw new Error(`Language "${F}" is not supported. Must be one of: ${JSON.stringify(w)}`)}return _}},"./src/models/whisper/feature_extraction_whisper.js":(R,c,s)=>{s.r(c),s.d(c,{WhisperFeatureExtractor:()=>U});var h=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var T=s("./src/utils/audio.js"),I=s("./src/utils/maths.js");class U extends h.FeatureExtractor{constructor(_){var v;super(_),(v=this.config).mel_filters??(v.mel_filters=(0,T.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,T.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(_){const v=await(0,T.spectrogram)(_,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),w=v.data,b=(0,I.max)(w)[0];for(let x=0;xthis.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=_.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(_)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(R,c,s)=>{s.r(c),s.d(c,{WhisperGenerationConfig:()=>T});var h=s("./src/generation/configuration_utils.js");class T extends h.GenerationConfig{constructor(){super(...arguments);_e(this,"return_timestamps",null);_e(this,"return_token_timestamps",null);_e(this,"num_frames",null);_e(this,"alignment_heads",null);_e(this,"task",null);_e(this,"language",null);_e(this,"no_timestamps_token_id",null);_e(this,"prompt_ids",null);_e(this,"is_multilingual",null);_e(this,"lang_to_id",null);_e(this,"task_to_id",null);_e(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(R,c,s)=>{s.r(c),s.d(c,{WhisperProcessor:()=>U});var h=s("./src/models/auto/feature_extraction_auto.js"),T=s("./src/tokenizers.js"),I=s("./src/base/processing_utils.js");class U extends I.Processor{async _call(_){return await this.feature_extractor(_)}}_e(U,"tokenizer_class",T.AutoTokenizer),_e(U,"feature_extractor_class",h.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(R,c,s)=>{s.r(c),s.d(c,{YolosFeatureExtractor:()=>I,YolosImageProcessor:()=>T});var h=s("./src/base/image_processors_utils.js");class T extends h.ImageProcessor{post_process_object_detection(...F){return(0,h.post_process_object_detection)(...F)}}class I extends T{}},"./src/ops/registry.js":(R,c,s)=>{s.r(c),s.d(c,{TensorOpRegistry:()=>_});var h=s("./src/backends/onnx.js"),T=s("./src/utils/tensor.js"),I=s("./src/env.js");const U=I.apis.IS_BROWSER_ENV||I.apis.IS_WEBWORKER_ENV,F=async(v,w,b)=>{const x=await(0,h.createInferenceSession)(new Uint8Array(v),w);let O=Promise.resolve();return async H=>{const re=(0,h.isONNXProxy)(),ne=Object.fromEntries(Object.entries(H).map(([W,X])=>[W,(re?X.clone():X).ort_tensor])),G=await(O=U?O.then(()=>x.run(ne)):x.run(ne));return Array.isArray(b)?b.map(W=>new T.Tensor(G[W])):new T.Tensor(G[b])}};class _{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=F([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=F([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=F([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=F([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=F([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=F([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=F([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=F([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}_e(_,"session_options",{})},"./src/pipelines.js":(R,c,s)=>{s.r(c),s.d(c,{AudioClassificationPipeline:()=>we,AutomaticSpeechRecognitionPipeline:()=>Pe,DepthEstimationPipeline:()=>Se,DocumentQuestionAnsweringPipeline:()=>be,FeatureExtractionPipeline:()=>oe,FillMaskPipeline:()=>X,ImageClassificationPipeline:()=>ke,ImageFeatureExtractionPipeline:()=>Te,ImageSegmentationPipeline:()=>Oe,ImageToImagePipeline:()=>ce,ImageToTextPipeline:()=>pe,ObjectDetectionPipeline:()=>tt,Pipeline:()=>re,QuestionAnsweringPipeline:()=>W,SummarizationPipeline:()=>A,Text2TextGenerationPipeline:()=>D,TextClassificationPipeline:()=>ne,TextGenerationPipeline:()=>L,TextToAudioPipeline:()=>Z,TokenClassificationPipeline:()=>G,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>ie,ZeroShotClassificationPipeline:()=>le,ZeroShotImageClassificationPipeline:()=>Ce,ZeroShotObjectDetectionPipeline:()=>Ge,pipeline:()=>se});var h=s("./src/tokenizers.js"),T=s("./src/models.js"),I=s("./src/models/auto/processing_auto.js");s("./src/base/processing_utils.js");var U=s("./src/utils/generic.js"),F=s("./src/utils/core.js"),_=s("./src/utils/maths.js"),v=s("./src/utils/audio.js"),w=s("./src/utils/tensor.js"),b=s("./src/utils/image.js");async function x(Ue){return Array.isArray(Ue)||(Ue=[Ue]),await Promise.all(Ue.map(ue=>b.RawImage.read(ue)))}async function O(Ue,ue){return Array.isArray(Ue)||(Ue=[Ue]),await Promise.all(Ue.map(ve=>typeof ve=="string"||ve instanceof URL?(0,v.read_audio)(ve,ue):ve instanceof Float64Array?new Float32Array(ve):ve))}function H(Ue,ue){ue&&(Ue=Ue.map(je=>je|0));const[ve,Ve,We,Ne]=Ue;return{xmin:ve,ymin:Ve,xmax:We,ymax:Ne}}class re extends U.Callable{constructor({task:ue,model:ve,tokenizer:Ve=null,processor:We=null}){super(),this.task=ue,this.model=ve,this.tokenizer=Ve,this.processor=We}async dispose(){await this.model.dispose()}}class ne extends re{constructor(ue){super(ue)}async _call(ue,{top_k:ve=1}={}){const Ve=this.tokenizer(ue,{padding:!0,truncation:!0}),We=await this.model(Ve),Ne=this.model.config.problem_type==="multi_label_classification"?ut=>ut.sigmoid():ut=>new w.Tensor("float32",(0,_.softmax)(ut.data),ut.dims),je=this.model.config.id2label,st=[];for(const ut of We.logits){const pt=Ne(ut),lt=await(0,w.topk)(pt,ve),mt=lt[0].tolist(),ae=lt[1].tolist().map((q,me)=>({label:je?je[q]:`LABEL_${q}`,score:mt[me]}));ve===1?st.push(...ae):st.push(ae)}return Array.isArray(ue)||ve===1?st:st[0]}}class G extends re{constructor(ue){super(ue)}async _call(ue,{ignore_labels:ve=["O"]}={}){const Ve=Array.isArray(ue),We=this.tokenizer(Ve?ue:[ue],{padding:!0,truncation:!0}),je=(await this.model(We)).logits,st=this.model.config.id2label,ut=[];for(let pt=0;ptat==this.tokenizer.sep_token_id);ut[mt].map((at,ct)=>at==1&&(ct===0||ct>ae&&pt.findIndex(vt=>vt==B[ct])===-1));const q=Ne[mt].tolist(),me=je[mt].tolist();for(let at=1;atct==B[at])!==-1)&&(q[at]=-1/0,me[at]=-1/0);const $e=(0,_.softmax)(q).map((at,ct)=>[at,ct]),Re=(0,_.softmax)(me).map((at,ct)=>[at,ct]);$e[0][0]=0,Re[0][0]=0;const qe=(0,F.product)($e,Re).filter(at=>at[0][1]<=at[1][1]).map(at=>[at[0][1],at[1][1],at[0][0]*at[1][0]]).sort((at,ct)=>ct[2]-at[2]);for(let at=0;atq==this.tokenizer.mask_token_id);if(pt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=We[st][pt],mt=await(0,w.topk)(new w.Tensor("float32",(0,_.softmax)(lt.data),lt.dims),ve),B=mt[0].tolist(),ae=mt[1].tolist();Ne.push(ae.map((q,me)=>{const $e=ut.slice();return $e[pt]=q,{score:B[me],token:Number(q),token_str:this.tokenizer.decode([q]),sequence:this.tokenizer.decode($e,{skip_special_tokens:!0})}}))}return Array.isArray(ue)?Ne:Ne[0]}}class D extends re{constructor(ve){super(ve);_e(this,"_key","generated_text")}async _call(ve,Ve={}){Array.isArray(ve)||(ve=[ve]),this.model.config.prefix&&(ve=ve.map(pt=>this.model.config.prefix+pt));const We=this.model.config.task_specific_params;We&&We[this.task]&&We[this.task].prefix&&(ve=ve.map(pt=>We[this.task].prefix+pt));const Ne=this.tokenizer,je={padding:!0,truncation:!0};let st;this instanceof M&&"_build_translation_inputs"in Ne?st=Ne._build_translation_inputs(ve,je,Ve):st=Ne(ve,je);const ut=await this.model.generate({...st,...Ve});return Ne.batch_decode(ut,{skip_special_tokens:!0}).map(pt=>({[this._key]:pt}))}}class A extends D{constructor(ve){super(ve);_e(this,"_key","summary_text")}}class M extends D{constructor(ve){super(ve);_e(this,"_key","translation_text")}}function P(Ue){return Array.isArray(Ue)&&Ue.every(ue=>"role"in ue&&"content"in ue)}class L extends re{constructor(ue){super(ue)}async _call(ue,ve={}){let Ve=!1,We=!1,Ne;if(typeof ue=="string")Ne=ue=[ue];else if(Array.isArray(ue)&&ue.every(ae=>typeof ae=="string"))Ve=!0,Ne=ue;else{if(P(ue))ue=[ue];else if(Array.isArray(ue)&&ue.every(P))Ve=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");We=!0,Ne=ue.map(ae=>this.tokenizer.apply_chat_template(ae,{tokenize:!1,add_generation_prompt:!0}))}const je=ve.add_special_tokens??!1,st=We?!1:ve.return_full_text??!0;this.tokenizer.padding_side="left";const ut=this.tokenizer(Ne,{add_special_tokens:je,padding:!0,truncation:!0}),pt=await this.model.generate({...ut,...ve}),lt=this.tokenizer.batch_decode(pt,{skip_special_tokens:!0});let mt;!st&&ut.input_ids.dims.at(-1)>0&&(mt=this.tokenizer.batch_decode(ut.input_ids,{skip_special_tokens:!0}).map(ae=>ae.length));const B=Array.from({length:ue.length},ae=>[]);for(let ae=0;ae[ve.toLowerCase(),Ve])),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(ue,ve,{hypothesis_template:Ve="This example is {}.",multi_label:We=!1}={}){const Ne=Array.isArray(ue);Ne||(ue=[ue]),Array.isArray(ve)||(ve=[ve]);const je=ve.map(pt=>Ve.replace("{}",pt)),st=We||ve.length===1,ut=[];for(const pt of ue){const lt=[];for(const ae of je){const q=this.tokenizer(pt,{text_pair:ae,padding:!0,truncation:!0}),me=await this.model(q);st?lt.push([me.logits.data[this.contradiction_id],me.logits.data[this.entailment_id]]):lt.push(me.logits.data[this.entailment_id])}const B=(st?lt.map(ae=>(0,_.softmax)(ae)[1]):(0,_.softmax)(lt)).map((ae,q)=>[ae,q]).sort((ae,q)=>q[0]-ae[0]);ut.push({sequence:pt,labels:B.map(ae=>ve[ae[1]]),scores:B.map(ae=>ae[0])})}return Ne?ut:ut[0]}}class oe extends re{constructor(ue){super(ue)}async _call(ue,{pooling:ve="none",normalize:Ve=!1,quantize:We=!1,precision:Ne="binary"}={}){const je=this.tokenizer(ue,{padding:!0,truncation:!0}),st=await this.model(je);let ut=st.last_hidden_state??st.logits??st.token_embeddings;if(ve!=="none")if(ve==="mean")ut=(0,w.mean_pooling)(ut,je.attention_mask);else if(ve==="cls")ut=ut.slice(null,0);else throw Error(`Pooling method '${ve}' not supported.`);return Ve&&(ut=ut.normalize(2,-1)),We&&(ut=(0,w.quantize_embeddings)(ut,Ne)),ut}}class Te extends re{constructor(ue){super(ue)}async _call(ue,{pool:ve=null}={}){const Ve=await x(ue),{pixel_values:We}=await this.processor(Ve),Ne=await this.model({pixel_values:We});let je;if(ve){if(!("pooler_output"in Ne))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");je=Ne.pooler_output}else je=Ne.last_hidden_state??Ne.logits??Ne.image_embeds;return je}}class we extends re{constructor(ue){super(ue)}async _call(ue,{top_k:ve=5}={}){const Ve=this.processor.feature_extractor.config.sampling_rate,We=await O(ue,Ve),Ne=this.model.config.id2label,je=[];for(const st of We){const ut=await this.processor(st),lt=(await this.model(ut)).logits[0],mt=await(0,w.topk)(new w.Tensor("float32",(0,_.softmax)(lt.data),lt.dims),ve),B=mt[0].tolist(),q=mt[1].tolist().map((me,$e)=>({label:Ne?Ne[me]:`LABEL_${me}`,score:B[$e]}));je.push(q)}return Array.isArray(ue)?je:je[0]}}class ie extends re{constructor(ue){super(ue)}async _call(ue,ve,{hypothesis_template:Ve="This is a sound of {}."}={}){const We=!Array.isArray(ue);We&&(ue=[ue]);const Ne=ve.map(lt=>Ve.replace("{}",lt)),je=this.tokenizer(Ne,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,ut=await O(ue,st),pt=[];for(const lt of ut){const mt=await this.processor(lt),B=await this.model({...je,...mt}),ae=(0,_.softmax)(B.logits_per_audio.data);pt.push([...ae].map((q,me)=>({score:q,label:ve[me]})))}return We?pt[0]:pt}}class Pe extends re{constructor(ue){super(ue)}async _call(ue,ve={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ue,ve);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ue,ve);case"moonshine":return this._call_moonshine(ue,ve);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ue,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 Ve=!Array.isArray(ue);Ve&&(ue=[ue]);const We=this.processor.feature_extractor.config.sampling_rate,Ne=await O(ue,We),je=[];for(const st of Ne){const ut=await this.processor(st),lt=(await this.model(ut)).logits[0],mt=[];for(const ae of lt)mt.push((0,_.max)(ae.data)[1]);const B=this.tokenizer.decode(mt);je.push({text:B})}return Ve?je[0]:je}async _call_whisper(ue,ve){const Ve=ve.return_timestamps??!1,We=ve.chunk_length_s??0,Ne=ve.force_full_sequences??!1;let je=ve.stride_length_s??null;const st={...ve};Ve==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const ut=!Array.isArray(ue);ut&&(ue=[ue]);const pt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,lt=this.processor.feature_extractor.config.hop_length,mt=this.processor.feature_extractor.config.sampling_rate,B=await O(ue,mt),ae=[];for(const q of B){let me=[];if(We>0){if(je===null)je=We/6;else if(We<=je)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const qe=mt*We,at=mt*je,ct=qe-2*at;let vt=0;for(;;){const St=vt+qe,kt=q.subarray(vt,St),is=await this.processor(kt),Ms=vt===0,$s=St>=q.length;if(me.push({stride:[kt.length,Ms?0:at,$s?0:at],input_features:is.input_features,is_last:$s}),$s)break;vt+=ct}}else me=[{stride:[q.length,0,0],input_features:(await this.processor(q)).input_features,is_last:!0}];for(const qe of me){st.num_frames=Math.floor(qe.stride[0]/lt);const at=await this.model.generate({inputs:qe.input_features,...st});Ve==="word"?(qe.tokens=at.sequences.tolist()[0],qe.token_timestamps=at.token_timestamps.tolist()[0].map(ct=>(0,_.round)(ct,2))):qe.tokens=at[0].tolist(),qe.stride=qe.stride.map(ct=>ct/mt)}const[$e,Re]=this.tokenizer._decode_asr(me,{time_precision:pt,return_timestamps:Ve,force_full_sequences:Ne});ae.push({text:$e,...Re})}return ut?ae[0]:ae}async _call_moonshine(ue,ve){const Ve=!Array.isArray(ue);Ve&&(ue=[ue]);const We=this.processor.feature_extractor.config.sampling_rate,Ne=await O(ue,We),je=[];for(const st of Ne){const ut=await this.processor(st),pt=Math.floor(st.length/We)*6,lt=await this.model.generate({max_new_tokens:pt,...ve,...ut}),mt=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];je.push({text:mt})}return Ve?je[0]:je}}class pe extends re{constructor(ue){super(ue)}async _call(ue,ve={}){const Ve=Array.isArray(ue),We=await x(ue),{pixel_values:Ne}=await this.processor(We),je=[];for(const st of Ne){st.dims=[1,...st.dims];const ut=await this.model.generate({inputs:st,...ve}),pt=this.tokenizer.batch_decode(ut,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));je.push(pt)}return Ve?je:je[0]}}class ke extends re{constructor(ue){super(ue)}async _call(ue,{top_k:ve=5}={}){const Ve=await x(ue),{pixel_values:We}=await this.processor(Ve),Ne=await this.model({pixel_values:We}),je=this.model.config.id2label,st=[];for(const ut of Ne.logits){const pt=await(0,w.topk)(new w.Tensor("float32",(0,_.softmax)(ut.data),ut.dims),ve),lt=pt[0].tolist(),B=pt[1].tolist().map((ae,q)=>({label:je?je[ae]:`LABEL_${ae}`,score:lt[q]}));st.push(B)}return Array.isArray(ue)?st:st[0]}}class Oe extends re{constructor(ue){super(ue),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ue,{threshold:ve=.5,mask_threshold:Ve=.5,overlap_mask_area_threshold:We=.8,label_ids_to_fuse:Ne=null,target_sizes:je=null,subtask:st=null}={}){if(Array.isArray(ue)&&ue.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const pt=await x(ue),lt=pt.map(Re=>[Re.height,Re.width]),{pixel_values:mt,pixel_mask:B}=await this.processor(pt),ae=await this.model({pixel_values:mt,pixel_mask:B});let q=null;if(st!==null)q=this.subtasks_mapping[st];else for(let[Re,qe]of Object.entries(this.subtasks_mapping))if(qe in this.processor.image_processor){q=this.processor.image_processor[qe].bind(this.processor.image_processor),st=Re;break}const me=this.model.config.id2label,$e=[];if(st==="panoptic"||st==="instance"){const Re=q(ae,ve,Ve,We,Ne,je??lt)[0],qe=Re.segmentation;for(const at of Re.segments_info){const ct=new Uint8ClampedArray(qe.data.length);for(let St=0;StVe.replace("{}",B)),st=this.tokenizer(je,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ut}=await this.processor(Ne),pt=await this.model({...st,pixel_values:ut}),lt=this.model.config.model_type==="siglip"?B=>B.sigmoid().data:B=>(0,_.softmax)(B.data),mt=[];for(const B of pt.logits_per_image){const q=[...lt(B)].map((me,$e)=>({score:me,label:ve[$e]}));q.sort((me,$e)=>$e.score-me.score),mt.push(q)}return We?mt:mt[0]}}class tt extends re{constructor(ue){super(ue)}async _call(ue,{threshold:ve=.9,percentage:Ve=!1}={}){const We=Array.isArray(ue);if(We&&ue.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ne=await x(ue),je=Ve?null:Ne.map(ae=>[ae.height,ae.width]),{pixel_values:st,pixel_mask:ut}=await this.processor(Ne),pt=await this.model({pixel_values:st,pixel_mask:ut}),lt=this.processor.image_processor.post_process_object_detection(pt,ve,je),mt=this.model.config.id2label,B=lt.map(ae=>ae.boxes.map((q,me)=>({score:ae.scores[me],label:mt[ae.classes[me]],box:H(q,!Ve)})));return We?B:B[0]}}class Ge extends re{constructor(ue){super(ue)}async _call(ue,ve,{threshold:Ve=.1,top_k:We=null,percentage:Ne=!1}={}){const je=Array.isArray(ue),st=await x(ue),ut=this.tokenizer(ve,{padding:!0,truncation:!0}),pt=await this.processor(st),lt=[];for(let mt=0;mt({score:Re.scores[at],label:Re.labels[at],box:H(qe,!Ne)}))}else{const Re=this.processor.image_processor.post_process_object_detection(me,Ve,ae,!0)[0];$e=Re.boxes.map((qe,at)=>({score:Re.scores[at],label:ve[Re.classes[at]],box:H(qe,!Ne)}))}$e.sort((Re,qe)=>qe.score-Re.score),We!==null&&($e=$e.slice(0,We)),lt.push($e)}return je?lt:lt[0]}}class be extends re{constructor(ue){super(ue)}async _call(ue,ve,Ve={}){const We=(await x(ue))[0],{pixel_values:Ne}=await this.processor(We),je=`${ve}`,st=this.tokenizer(je,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ut=await this.model.generate({inputs:Ne,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...Ve}),lt=this.tokenizer.batch_decode(ut)[0].match(/(.*?)<\/s_answer>/);let mt=null;return lt&<.length>=2&&(mt=lt[1].trim()),[{answer:mt}]}}class Z extends re{constructor(ve){super(ve);_e(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ve.vocoder??null}async _call(ve,{speaker_embeddings:Ve=null}={}){return this.processor?this._call_text_to_spectrogram(ve,{speaker_embeddings:Ve}):this._call_text_to_waveform(ve)}async _call_text_to_waveform(ve){const Ve=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:We}=await this.model(Ve),Ne=this.model.config.sampling_rate;return new v.RawAudio(We.data,Ne)}async _call_text_to_spectrogram(ve,{speaker_embeddings:Ve}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await T.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ve=="string"||Ve instanceof URL)&&(Ve=new Float32Array(await(await fetch(Ve)).arrayBuffer())),Ve instanceof Float32Array)Ve=new w.Tensor("float32",Ve,[1,Ve.length]);else if(!(Ve instanceof w.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:Ne}=await this.model.generate_speech(We,Ve,{vocoder:this.vocoder}),je=this.processor.feature_extractor.config.sampling_rate;return new v.RawAudio(Ne.data,je)}}class ce extends re{constructor(ue){super(ue)}async _call(ue){const ve=await x(ue),Ve=await this.processor(ve),We=await this.model(Ve),Ne=[];for(const je of We.reconstruction){const st=je.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ne.push(b.RawImage.fromTensor(st))}return Ne.length>1?Ne:Ne[0]}}class Se extends re{constructor(ue){super(ue)}async _call(ue){const ve=await x(ue),Ve=await this.processor(ve),{predicted_depth:We}=await this.model(Ve),Ne=[];for(let je=0;je1?Ne:Ne[0]}}const Be=Object.freeze({"text-classification":{tokenizer:h.AutoTokenizer,pipeline:ne,model:T.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:h.AutoTokenizer,pipeline:G,model:T.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:h.AutoTokenizer,pipeline:W,model:T.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:h.AutoTokenizer,pipeline:X,model:T.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:h.AutoTokenizer,pipeline:A,model:T.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:h.AutoTokenizer,pipeline:M,model:T.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:h.AutoTokenizer,pipeline:D,model:T.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:h.AutoTokenizer,pipeline:L,model:T.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:h.AutoTokenizer,pipeline:le,model:T.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:we,model:T.AutoModelForAudioClassification,processor:I.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:h.AutoTokenizer,pipeline:ie,model:T.AutoModel,processor:I.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:h.AutoTokenizer,pipeline:Pe,model:[T.AutoModelForSpeechSeq2Seq,T.AutoModelForCTC],processor:I.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:h.AutoTokenizer,pipeline:Z,model:[T.AutoModelForTextToWaveform,T.AutoModelForTextToSpectrogram],processor:[I.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:h.AutoTokenizer,pipeline:pe,model:T.AutoModelForVision2Seq,processor:I.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ke,model:T.AutoModelForImageClassification,processor:I.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Oe,model:[T.AutoModelForImageSegmentation,T.AutoModelForSemanticSegmentation,T.AutoModelForUniversalSegmentation],processor:I.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:h.AutoTokenizer,pipeline:Ce,model:T.AutoModel,processor:I.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:tt,model:T.AutoModelForObjectDetection,processor:I.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:h.AutoTokenizer,pipeline:Ge,model:T.AutoModelForZeroShotObjectDetection,processor:I.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:h.AutoTokenizer,pipeline:be,model:T.AutoModelForDocumentQuestionAnswering,processor:I.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ce,model:T.AutoModelForImageToImage,processor:I.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Se,model:T.AutoModelForDepthEstimation,processor:I.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:h.AutoTokenizer,pipeline:oe,model:T.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:I.AutoProcessor,pipeline:Te,model:[T.AutoModelForImageFeatureExtraction,T.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Je=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function se(Ue,ue=null,{progress_callback:ve=null,config:Ve=null,cache_dir:We=null,local_files_only:Ne=!1,revision:je="main",device:st=null,dtype:ut=null,model_file_name:pt=null,session_options:lt={}}={}){Ue=Je[Ue]??Ue;const mt=Be[Ue.split("_",1)[0]];if(!mt)throw Error(`Unsupported pipeline: ${Ue}. Must be one of [${Object.keys(Be)}]`);ue||(ue=mt.default.model,console.log(`No model specified. Using default model: "${ue}".`));const B={progress_callback:ve,config:Ve,cache_dir:We,local_files_only:Ne,revision:je,device:st,dtype:ut,model_file_name:pt,session_options:lt},ae=new Map([["tokenizer",mt.tokenizer],["model",mt.model],["processor",mt.processor]]),q=await Ke(ae,ue,B);q.task=Ue,(0,F.dispatchCallback)(ve,{status:"ready",task:Ue,model:ue});const me=mt.pipeline;return new me(q)}async function Ke(Ue,ue,ve){const Ve=Object.create(null),We=[];for(const[Ne,je]of Ue.entries()){if(!je)continue;let st;Array.isArray(je)?st=new Promise(async(ut,pt)=>{var mt,B;let lt;for(const ae of je){if(ae===null){ut(null);return}try{ut(await ae.from_pretrained(ue,ve));return}catch(q){if((mt=q.message)!=null&&mt.includes("Unsupported model type"))lt=q;else if((B=q.message)!=null&&B.includes("Could not locate file"))lt=q;else{pt(q);return}}}pt(lt)}):st=je.from_pretrained(ue,ve),Ve[Ne]=st,We.push(st)}await Promise.all(We);for(const[Ne,je]of Object.entries(Ve))Ve[Ne]=await je;return Ve}},"./src/tokenizers.js":(R,c,s)=>{s.r(c),s.d(c,{AlbertTokenizer:()=>Or,AutoTokenizer:()=>os,BartTokenizer:()=>Lr,BertTokenizer:()=>rn,BlenderbotSmallTokenizer:()=>Vn,BlenderbotTokenizer:()=>Un,BloomTokenizer:()=>Sr,CLIPTokenizer:()=>Cn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>En,CodeLlamaTokenizer:()=>Hr,CohereTokenizer:()=>kn,ConvBertTokenizer:()=>Wr,DebertaTokenizer:()=>fr,DebertaV2Tokenizer:()=>Vr,DistilBertTokenizer:()=>cr,ElectraTokenizer:()=>Ft,EsmTokenizer:()=>qr,FalconTokenizer:()=>Rn,GPT2Tokenizer:()=>Kr,GPTNeoXTokenizer:()=>Nn,GemmaTokenizer:()=>ci,Grok1Tokenizer:()=>Qr,HerbertTokenizer:()=>Dr,LlamaTokenizer:()=>Tn,M2M100Tokenizer:()=>Pn,MBart50Tokenizer:()=>pr,MBartTokenizer:()=>vs,MPNetTokenizer:()=>Bn,MarianTokenizer:()=>Lt,MgpstrTokenizer:()=>Kn,MobileBertTokenizer:()=>Fr,NllbTokenizer:()=>hr,NougatTokenizer:()=>Xr,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>jn,RoFormerTokenizer:()=>Gr,RobertaTokenizer:()=>Fs,SiglipTokenizer:()=>Sn,SpeechT5Tokenizer:()=>Wn,SqueezeBertTokenizer:()=>nn,T5Tokenizer:()=>Ws,TokenizerModel:()=>Te,VitsTokenizer:()=>Gn,Wav2Vec2CTCTokenizer:()=>$n,WhisperTokenizer:()=>on,XLMRobertaTokenizer:()=>di,XLMTokenizer:()=>xt,is_chinese_char:()=>X});var h=s("./src/utils/generic.js"),T=s("./src/utils/core.js"),I=s("./src/utils/hub.js"),U=s("./src/utils/maths.js"),F=s("./src/utils/tensor.js"),_=s("./src/utils/data-structures.js"),v=s("./node_modules/@huggingface/jinja/dist/index.js"),w=s("./src/models/whisper/common_whisper.js");async function b(Ee,C){const Y=await Promise.all([(0,I.getModelJSON)(Ee,"tokenizer.json",!0,C),(0,I.getModelJSON)(Ee,"tokenizer_config.json",!0,C)]);return C.legacy!==null&&(Y[1].legacy=C.legacy),Y}function x(Ee,C){const Y=[];let de=0;for(const xe of Ee.matchAll(C)){const Ie=xe[0];de0&&Y.push(Ie),de=xe.index+Ie.length}return de=19968&&Ee<=40959||Ee>=13312&&Ee<=19903||Ee>=131072&&Ee<=173791||Ee>=173824&&Ee<=177983||Ee>=177984&&Ee<=178207||Ee>=178208&&Ee<=183983||Ee>=63744&&Ee<=64255||Ee>=194560&&Ee<=195103}function D(Ee,C,Y){const de=[];let xe=0;for(;xethis.tokens_to_ids.get(Y)??this.unk_token_id)}convert_ids_to_tokens(C){return C.map(Y=>this.vocab[Y]??this.unk_token)}}class we extends Te{constructor(C){super(C),this.tokens_to_ids=H(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.max_input_chars_per_word=C.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,de]of this.tokens_to_ids)this.vocab[de]=Y}encode(C){const Y=[];for(const de of C){const xe=[...de];if(xe.length>this.max_input_chars_per_word){Y.push(this.unk_token);continue}let Ie=!1,Xe=0;const ht=[];for(;Xe0&&(Tt=this.config.continuing_subword_prefix+Tt),this.tokens_to_ids.has(Tt)){ft=Tt;break}--gt}if(ft===null){Ie=!0;break}ht.push(ft),Xe=gt}Ie?Y.push(this.unk_token):Y.push(...ht)}return Y}}class ie extends Te{constructor(C,Y){super(C);const de=C.vocab.length;this.vocab=new Array(de),this.scores=new Array(de);for(let xe=0;xe[xe,Ie])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Y.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,U.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new _.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(C){const Y=C.chars,de=1;let xe=0;for(;xe{const Ee=[...Array.from({length:94},(xe,Ie)=>Ie+33),...Array.from({length:12},(xe,Ie)=>Ie+161),...Array.from({length:82},(xe,Ie)=>Ie+174)],C=Ee.slice();let Y=0;for(let xe=0;xe<256;++xe)Ee.includes(xe)||(Ee.push(xe),C.push(256+Y),Y+=1);const de=C.map(xe=>String.fromCharCode(xe));return Object.fromEntries(Ee.map((xe,Ie)=>[xe,de[Ie]]))})(),pe=(0,T.reverseDictionary)(Pe);class ke extends Te{constructor(C){super(C),this.tokens_to_ids=H(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[de,xe]of this.tokens_to_ids)this.vocab[xe]=de;const Y=Array.isArray(C.merges[0]);this.merges=Y?C.merges:C.merges.map(de=>de.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((de,xe)=>[JSON.stringify(de),xe])),this.end_of_word_suffix=C.end_of_word_suffix,this.continuing_subword_suffix=C.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(C){if(C.length===0)return[];const Y=this.cache.get(C);if(Y!==void 0)return Y;const de=Array.from(C);this.end_of_word_suffix&&(de[de.length-1]+=this.end_of_word_suffix);let xe=[];if(de.length>1){const Ie=new _.PriorityQueue((gt,ft)=>gt.score`<0x${ht.toString(16).toUpperCase().padStart(2,"0")}>`);Xe.every(ht=>this.tokens_to_ids.has(ht))?Y.push(...Xe):Y.push(this.unk_token)}else Y.push(this.unk_token)}return Y}}class Oe extends Te{constructor(C,Y){super(C),this.tokens_to_ids=H(Y.target_lang?C.vocab[Y.target_lang]:C.vocab),this.bos_token=Y.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Y.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=Y.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=Y.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[de,xe]of this.tokens_to_ids)this.vocab[xe]=de}encode(C){return C}}class Ce extends h.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"BertNormalizer":return new Ke(C);case"Precompiled":return new Ms(C);case"Sequence":return new se(C);case"Replace":return new tt(C);case"NFC":return new Ge(C);case"NFKC":return new be(C);case"NFKD":return new Z(C);case"Strip":return new ce(C);case"StripAccents":return new Se(C);case"Lowercase":return new Be(C);case"Prepend":return new Je(C);default:throw new Error(`Unknown Normalizer type: ${C.type}`)}}normalize(C){throw Error("normalize should be implemented in subclass.")}_call(C){return this.normalize(C)}}class tt extends Ce{normalize(C){const Y=O(this.config.pattern);return Y===null?C:C.replaceAll(Y,this.config.content)}}class Ge extends Ce{normalize(C){return C=C.normalize("NFC"),C}}class be extends Ce{normalize(C){return C=C.normalize("NFKC"),C}}class Z extends Ce{normalize(C){return C=C.normalize("NFKD"),C}}class ce extends Ce{normalize(C){return this.config.strip_left&&this.config.strip_right?C=C.trim():(this.config.strip_left&&(C=C.trimStart()),this.config.strip_right&&(C=C.trimEnd())),C}}class Se extends Ce{normalize(C){return C=G(C),C}}class Be extends Ce{normalize(C){return C=C.toLowerCase(),C}}class Je extends Ce{normalize(C){return C=this.config.prepend+C,C}}class se extends Ce{constructor(C){super(C),this.normalizers=C.normalizers.map(Y=>Ce.fromConfig(Y))}normalize(C){return this.normalizers.reduce((Y,de)=>de.normalize(Y),C)}}class Ke extends Ce{_tokenize_chinese_chars(C){const Y=[];for(let de=0;dethis.pre_tokenize_text(de,Y)):this.pre_tokenize_text(C,Y)).flat()}_call(C,Y){return this.pre_tokenize(C,Y)}}class ue extends Ue{constructor(C){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text(C,Y){return C.trim().match(this.pattern)||[]}}class ve extends Ue{constructor(C){super(),this.config=C,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Pe,this.text_encoder=new TextEncoder}pre_tokenize_text(C,Y){return this.add_prefix_space&&!C.startsWith(" ")&&(C=" "+C),(this.use_regex?C.match(this.pattern)||[]:[C]).map(xe=>Array.from(this.text_encoder.encode(xe),Ie=>this.byte_encoder[Ie]).join(""))}}class Ve extends Ue{constructor(C){super(),this.config=C,this.pattern=O(this.config.pattern,this.config.invert)}pre_tokenize_text(C,Y){var de;return this.pattern===null?[]:this.config.invert?C.match(this.pattern)||[]:((de=this.config.behavior)==null?void 0:de.toLowerCase())==="removed"?C.split(this.pattern).filter(xe=>xe):x(C,this.pattern)}}class We extends Ue{constructor(C){super(),this.config=C,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text(C,Y){return C.match(this.pattern)||[]}}class Ne extends Ue{constructor(C){super(),this.config=C;const Y=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Y,"gu")}pre_tokenize_text(C,Y){return C.match(this.pattern)||[]}}class je extends h.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"TemplateProcessing":return new pt(C);case"ByteLevel":return new lt(C);case"RobertaProcessing":return new ut(C);case"BertProcessing":return new st(C);case"Sequence":return new mt(C);default:throw new Error(`Unknown PostProcessor type: ${C.type}`)}}post_process(C,...Y){throw Error("post_process should be implemented in subclass.")}_call(C,...Y){return this.post_process(C,...Y)}}class st extends je{constructor(C){super(C),this.cls=C.cls[0],this.sep=C.sep[0]}post_process(C,Y=null,{add_special_tokens:de=!0}={}){de&&(C=(0,T.mergeArrays)([this.cls],C,[this.sep]));let xe=new Array(C.length).fill(0);if(Y!==null){const Ie=de&&this instanceof ut?[this.sep]:[],Xe=de?[this.sep]:[];C=(0,T.mergeArrays)(C,Ie,Y,Xe),xe=(0,T.mergeArrays)(xe,new Array(Y.length+Ie.length+Xe.length).fill(1))}return{tokens:C,token_type_ids:xe}}}class ut extends st{}class pt extends je{constructor(C){super(C),this.single=C.single,this.pair=C.pair}post_process(C,Y=null,{add_special_tokens:de=!0}={}){const xe=Y===null?this.single:this.pair;let Ie=[],Xe=[];for(const ht of xe)"SpecialToken"in ht?de&&(Ie.push(ht.SpecialToken.id),Xe.push(ht.SpecialToken.type_id)):"Sequence"in ht&&(ht.Sequence.id==="A"?(Ie=(0,T.mergeArrays)(Ie,C),Xe=(0,T.mergeArrays)(Xe,new Array(C.length).fill(ht.Sequence.type_id))):ht.Sequence.id==="B"&&(Ie=(0,T.mergeArrays)(Ie,Y),Xe=(0,T.mergeArrays)(Xe,new Array(Y.length).fill(ht.Sequence.type_id))));return{tokens:Ie,token_type_ids:Xe}}}class lt extends je{post_process(C,Y=null){return Y&&(C=(0,T.mergeArrays)(C,Y)),{tokens:C}}}class mt extends je{constructor(C){super(C),this.processors=C.processors.map(Y=>je.fromConfig(Y))}post_process(C,Y=null,de={}){let xe;for(const Ie of this.processors)if(Ie instanceof lt)C=Ie.post_process(C).tokens,Y&&(Y=Ie.post_process(Y).tokens);else{const Xe=Ie.post_process(C,Y,de);C=Xe.tokens,xe=Xe.token_type_ids}return{tokens:C,token_type_ids:xe}}}class B extends h.Callable{constructor(C){super(),this.config=C,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=C.trim_offsets}static fromConfig(C){if(C===null)return null;switch(C.type){case"WordPiece":return new Re(C);case"Metaspace":return new is(C);case"ByteLevel":return new qe(C);case"Replace":return new ae(C);case"ByteFallback":return new q(C);case"Fuse":return new me(C);case"Strip":return new $e(C);case"Sequence":return new ct(C);case"CTC":return new at(C);case"BPEDecoder":return new vt(C);default:throw new Error(`Unknown Decoder type: ${C.type}`)}}_call(C){return this.decode(C)}decode(C){return this.decode_chain(C).join("")}decode_chain(C){throw Error("`decode_chain` should be implemented in subclass.")}}class ae extends B{decode_chain(C){const Y=O(this.config.pattern);return Y===null?C:C.map(de=>de.replaceAll(Y,this.config.content))}}class q extends B{constructor(C){super(C),this.text_decoder=new TextDecoder}decode_chain(C){const Y=[];let de=[];for(const xe of C){let Ie=null;if(xe.length===6&&xe.startsWith("<0x")&&xe.endsWith(">")){const Xe=parseInt(xe.slice(3,5),16);isNaN(Xe)||(Ie=Xe)}if(Ie!==null)de.push(Ie);else{if(de.length>0){const Xe=this.text_decoder.decode(Uint8Array.from(de));Y.push(Xe),de=[]}Y.push(xe)}}if(de.length>0){const xe=this.text_decoder.decode(Uint8Array.from(de));Y.push(xe),de=[]}return Y}}class me extends B{decode_chain(C){return[C.join("")]}}class $e extends B{constructor(C){super(C),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(C){return C.map(Y=>{let de=0;for(let Ie=0;Ie(de!==0&&(Y.startsWith(this.config.prefix)?Y=Y.replace(this.config.prefix,""):Y=" "+Y),this.cleanup&&(Y=ne(Y)),Y))}}class qe extends B{constructor(C){super(C),this.byte_decoder=pe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(C){const Y=C.join(""),de=new Uint8Array([...Y].map(Ie=>this.byte_decoder[Ie]));return this.text_decoder.decode(de)}decode_chain(C){const Y=[];let de=[];for(const xe of C)this.added_tokens.find(Ie=>Ie.content===xe)!==void 0?(de.length>0&&(Y.push(this.convert_tokens_to_string(de)),de=[]),Y.push(xe)):de.push(xe);return de.length>0&&Y.push(this.convert_tokens_to_string(de)),Y}}class at extends B{constructor(C){super(C),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(C){if(C.length===0)return"";const Y=[C[0]];for(let Ie=1;IeIe!==this.pad_token).join("");return this.cleanup&&(xe=ne(xe).replaceAll(this.word_delimiter_token," ").trim()),xe}decode_chain(C){return[this.convert_tokens_to_string(C)]}}class ct extends B{constructor(C){super(C),this.decoders=C.decoders.map(Y=>B.fromConfig(Y))}decode_chain(C){return this.decoders.reduce((Y,de)=>de.decode_chain(Y),C)}}class vt extends B{constructor(C){super(C),this.suffix=this.config.suffix}decode_chain(C){return C.map((Y,de)=>Y.replaceAll(this.suffix,de===C.length-1?"":" "))}}class St extends B{decode_chain(C){let Y="";for(let de=1;dede.normalize("NFKC")).join("~"):C=C.normalize("NFKC"),C}}class $s extends Ue{constructor(C){super(),this.tokenizers=C.pretokenizers.map(Y=>Ue.fromConfig(Y))}pre_tokenize_text(C,Y){return this.tokenizers.reduce((de,xe)=>xe.pre_tokenize(de,Y),[C])}}class zs extends Ue{constructor(C){super()}pre_tokenize_text(C,Y){return C.match(/\w+|[^\w\s]+/g)||[]}}class ar extends Ue{constructor(C){super()}pre_tokenize_text(C,Y){return A(C)}}class Ar extends Ue{constructor(C){super(),this.config=C,this.pattern=O(this.config.pattern),this.content=this.config.content}pre_tokenize_text(C,Y){return this.pattern===null?[C]:[C.replaceAll(this.pattern,this.config.content)]}}const sn=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Vs(Ee,C,Y,de){for(const xe of Object.keys(Ee)){const Ie=C-Ee[xe].length,Xe=Y(xe),ht=new Array(Ie).fill(Xe);Ee[xe]=de==="right"?(0,T.mergeArrays)(Ee[xe],ht):(0,T.mergeArrays)(ht,Ee[xe])}}function Cr(Ee,C){for(const Y of Object.keys(Ee))Ee[Y].length=C}class Nt extends h.Callable{constructor(Y,de){super();_e(this,"return_token_type_ids",!1);_e(this,"padding_side","right");this._tokenizer_config=de,this.normalizer=Ce.fromConfig(Y.normalizer),this.pre_tokenizer=Ue.fromConfig(Y.pre_tokenizer),this.model=Te.fromConfig(Y.model,de),this.post_processor=je.fromConfig(Y.post_processor),this.decoder=B.fromConfig(Y.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const xe of Y.added_tokens){const Ie=new oe(xe);this.added_tokens.push(Ie),this.model.tokens_to_ids.set(Ie.content,Ie.id),this.model.vocab[Ie.id]=Ie.content,Ie.special&&(this.special_tokens.push(Ie.content),this.all_special_ids.push(Ie.id))}if(this.additional_special_tokens=de.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((xe,Ie)=>Ie.content.length-xe.content.length).map(xe=>`${xe.lstrip?"\\s*":""}(${(0,T.escapeRegExp)(xe.content)})${xe.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=de.model_max_length,this.remove_space=de.remove_space,this.clean_up_tokenization_spaces=de.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=de.do_lowercase_and_remove_accent??!1,de.padding_side&&(this.padding_side=de.padding_side),this.legacy=!1,this.chat_template=de.chat_template??null,Array.isArray(this.chat_template)){const xe=Object.create(null);for(const{name:Ie,template:Xe}of this.chat_template){if(typeof Ie!="string"||typeof Xe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');xe[Ie]=Xe}this.chat_template=xe}this._compiled_template_cache=new Map}getToken(...Y){for(const de of Y){const xe=this._tokenizer_config[de];if(xe)if(typeof xe=="object"){if(xe.__type==="AddedToken")return xe.content;throw Error(`Unknown token: ${xe}`)}else return xe}return null}static async from_pretrained(Y,{progress_callback:de=null,config:xe=null,cache_dir:Ie=null,local_files_only:Xe=!1,revision:ht="main",legacy:gt=null}={}){const ft=await b(Y,{progress_callback:de,config:xe,cache_dir:Ie,local_files_only:Xe,revision:ht,legacy:gt});return new this(...ft)}_call(Y,{text_pair:de=null,add_special_tokens:xe=!0,padding:Ie=!1,truncation:Xe=null,max_length:ht=null,return_tensor:gt=!0,return_token_type_ids:ft=null}={}){const Tt=Array.isArray(Y);let Kt;if(Tt){if(Y.length===0)throw Error("text array must be non-empty");if(de!==null){if(Array.isArray(de)){if(Y.length!==de.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Kt=Y.map((us,Ds)=>this._encode_plus(us,{text_pair:de[Ds],add_special_tokens:xe,return_token_type_ids:ft}))}else Kt=Y.map(us=>this._encode_plus(us,{add_special_tokens:xe,return_token_type_ids:ft}))}else{if(Y==null)throw Error("text may not be null or undefined");if(Array.isArray(de))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Kt=[this._encode_plus(Y,{text_pair:de,add_special_tokens:xe,return_token_type_ids:ft})]}if(ht===null?Ie==="max_length"?ht=this.model_max_length:ht=(0,U.max)(Kt.map(us=>us.input_ids.length))[0]:Xe||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."),ht=Math.min(ht,this.model_max_length??1/0),Ie||Xe)for(let us=0;usht?Xe&&Cr(Kt[us],ht):Ie&&Vs(Kt[us],ht,Ds=>Ds==="input_ids"?this.pad_token_id:0,this.padding_side));const fs={};if(gt){if(!(Ie&&Xe)&&Kt.some(Ds=>{var zt;for(const rs of Object.keys(Ds))if(Ds[rs].length!==((zt=Kt[0][rs])==null?void 0:zt.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const us=[Kt.length,Kt[0].input_ids.length];for(const Ds of Object.keys(Kt[0]))fs[Ds]=new F.Tensor("int64",BigInt64Array.from(Kt.flatMap(zt=>zt[Ds]).map(BigInt)),us)}else{for(const us of Object.keys(Kt[0]))fs[us]=Kt.map(Ds=>Ds[us]);if(!Tt)for(const us of Object.keys(fs))fs[us]=fs[us][0]}return fs}_encode_text(Y){return Y===null?null:(this.added_tokens_regex?Y.split(this.added_tokens_regex).filter(Ie=>Ie):[Y]).map((Ie,Xe)=>{if(this.added_tokens.find(gt=>gt.content===Ie)!==void 0)return Ie;{if(this.remove_space===!0&&(Ie=Ie.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Ie=W(Ie)),this.normalizer!==null&&(Ie=this.normalizer(Ie)),Ie.length===0)return[];const gt=this.pre_tokenizer!==null?this.pre_tokenizer(Ie,{section_index:Xe}):[Ie];return this.model(gt)}}).flat()}_encode_plus(Y,{text_pair:de=null,add_special_tokens:xe=!0,return_token_type_ids:Ie=null}={}){const{tokens:Xe,token_type_ids:ht}=this._tokenize_helper(Y,{pair:de,add_special_tokens:xe}),gt=this.model.convert_tokens_to_ids(Xe),ft={input_ids:gt,attention_mask:new Array(gt.length).fill(1)};return(Ie??this.return_token_type_ids)&&ht&&(ft.token_type_ids=ht),ft}_tokenize_helper(Y,{pair:de=null,add_special_tokens:xe=!1}={}){const Ie=this._encode_text(Y),Xe=this._encode_text(de);return this.post_processor?this.post_processor(Ie,Xe,{add_special_tokens:xe}):{tokens:(0,T.mergeArrays)(Ie??[],Xe??[])}}tokenize(Y,{pair:de=null,add_special_tokens:xe=!1}={}){return this._tokenize_helper(Y,{pair:de,add_special_tokens:xe}).tokens}encode(Y,{text_pair:de=null,add_special_tokens:xe=!0,return_token_type_ids:Ie=null}={}){return this._encode_plus(Y,{text_pair:de,add_special_tokens:xe,return_token_type_ids:Ie}).input_ids}batch_decode(Y,de={}){return Y instanceof F.Tensor&&(Y=Y.tolist()),Y.map(xe=>this.decode(xe,de))}decode(Y,de={}){if(Y instanceof F.Tensor&&(Y=re(Y)),!Array.isArray(Y)||Y.length===0||!(0,T.isIntegralNumber)(Y[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(Y,de)}decode_single(Y,{skip_special_tokens:de=!1,clean_up_tokenization_spaces:xe=null}){let Ie=this.model.convert_ids_to_tokens(Y);de&&(Ie=Ie.filter(ht=>!this.special_tokens.includes(ht)));let Xe=this.decoder?this.decoder(Ie):Ie.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Xe=Xe.replaceAll(this.decoder.end_of_word_suffix," "),de&&(Xe=Xe.trim())),(xe??this.clean_up_tokenization_spaces)&&(Xe=ne(Xe)),Xe}get_chat_template({chat_template:Y=null,tools:de=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const xe=this.chat_template;if(Y!==null&&Object.hasOwn(xe,Y))Y=xe[Y];else if(Y===null)if(de!==null&&"tool_use"in xe)Y=xe.tool_use;else if("default"in xe)Y=xe.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(xe).sort()}.`)}else if(Y===null)if(this.chat_template)Y=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 Y}apply_chat_template(Y,{tools:de=null,documents:xe=null,chat_template:Ie=null,add_generation_prompt:Xe=!1,tokenize:ht=!0,padding:gt=!1,truncation:ft=!1,max_length:Tt=null,return_tensor:Kt=!0,return_dict:fs=!1,tokenizer_kwargs:us={},...Ds}={}){if(Ie=this.get_chat_template({chat_template:Ie,tools:de}),typeof Ie!="string")throw Error(`chat_template must be a string, but got ${typeof Ie}`);let zt=this._compiled_template_cache.get(Ie);zt===void 0&&(zt=new v.Template(Ie),this._compiled_template_cache.set(Ie,zt));const rs=Object.create(null);for(const Gs of sn){const ze=this.getToken(Gs);ze&&(rs[Gs]=ze)}const lr=zt.render({messages:Y,add_generation_prompt:Xe,tools:de,documents:xe,...rs,...Ds});if(ht){const Gs=this._call(lr,{add_special_tokens:!1,padding:gt,truncation:ft,max_length:Tt,return_tensor:Kt,...us});return fs?Gs:Gs.input_ids}return lr}}class rn extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Or extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Fr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class nn extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class fr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Vr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Dr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Wr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Gr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class cr extends Nt{}class it extends Nt{}class xt extends Nt{constructor(Y,de){super(Y,de);_e(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ft extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Ws extends Nt{}class Kr extends Nt{}class Lr extends Nt{}class vs extends Nt{constructor(C,Y){super(C,Y),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(de=>this.languageRegex.test(de)),this.lang_to_token=de=>de}_build_translation_inputs(C,Y,de){return wr(this,C,Y,de)}}class pr extends vs{}class Fs extends Nt{}class Sr extends Nt{}const ss="▁";class Tn extends Nt{constructor(Y,de){super(Y,de);_e(this,"padding_side","left");this.legacy=de.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new kt({replacement:ss,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(Y){if(Y===null)return null;if(this.legacy||Y.length===0)return super._encode_text(Y);let de=super._encode_text(ss+Y.replaceAll(ss," "));return de.length>1&&de[0]===ss&&this.special_tokens.includes(de[1])&&(de=de.slice(1)),de}}class Hr extends Nt{}class di extends Nt{}class Bn extends Nt{}class Rn extends Nt{}class Nn extends Nt{}class qr extends Nt{}class jn extends Nt{}class ci extends Nt{}class Qr extends Nt{}function wr(Ee,C,Y,de){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 xe=de.src_lang,Ie=de.tgt_lang;if(!Ee.language_codes.includes(Ie))throw new Error(`Target language code "${Ie}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);if(xe!==void 0){if(!Ee.language_codes.includes(xe))throw new Error(`Source language code "${xe}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);for(const Xe of Ee.post_processor.config.single)if("SpecialToken"in Xe&&Ee.languageRegex.test(Xe.SpecialToken.id)){Xe.SpecialToken.id=Ee.lang_to_token(xe);break}}return de.forced_bos_token_id=Ee.model.convert_tokens_to_ids([Ee.lang_to_token(Ie)])[0],Ee._call(C,Y)}class hr extends Nt{constructor(C,Y){super(C,Y),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(de=>this.languageRegex.test(de)),this.lang_to_token=de=>de}_build_translation_inputs(C,Y,de){return wr(this,C,Y,de)}}class Pn extends Nt{constructor(C,Y){super(C,Y),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(de=>this.languageRegex.test(de)).map(de=>de.slice(2,-2)),this.lang_to_token=de=>`__${de}__`}_build_translation_inputs(C,Y,de){return wr(this,C,Y,de)}}class on extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(C,{return_timestamps:Y=!1,return_language:de=!1,time_precision:xe=null,force_full_sequences:Ie=!0}={}){if(xe===null)throw Error("Must specify time_precision");let Xe=null;const ht=Y==="word";function gt(){return{language:Xe,timestamp:[null,null],text:""}}const ft=[];let Tt=gt(),Kt=0;const fs=this.timestamp_begin,Ds=fs+1500;let zt=[],rs=[],lr=!1,Gs=null;const ze=new Set(this.all_special_ids);for(const ks of C){const er=ks.tokens,Ot=ht?ks.token_timestamps:null;let dr=null,br=fs;if("stride"in ks){const[bt,Xt,Bs]=ks.stride;if(Kt-=Xt,Gs=bt-Bs,Xt&&(br=Xt/xe+fs),Bs)for(let As=er.length-1;As>=0;--As){const Ks=Number(er[As]);if(Ks>=fs){if(dr!==null&&(Ks-fs)*xe=fs&&Xt<=Ds){const Bs=(Xt-fs)*xe+Kt,As=(0,U.round)(Bs,2);if(dr!==null&&Xt>=dr)lr=!0;else if(lr||zt.length>0&&Xt0?(zt.push(_s),ht&&rs.push(Is)):zt.every(bt=>bt.length===0)&&(Tt=gt(),zt=[],_s=[],rs=[],Is=[])}if(zt.length>0){if(Ie&&Y)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[ks,er]=this.findLongestCommonSequence(zt,rs),Ot=this.decode(ks);Tt.text=Ot,ht&&(Tt.words=this.collateWordTimestamps(ks,er,Xe)),ft.push(Tt)}let rr=Object.create(null);const zr=ft.map(ks=>ks.text).join("");if(Y||de){for(let ks=0;ks0;let ht=Xe?[]:null,gt=Xe?Y[0]:null;for(let ft=1;ftXt===br[Bs]&>[zr+Bs]<=Y[ft][Ot+Bs]).length:_s=er.filter((Xt,Bs)=>Xt===br[Bs]).length;const Is=rr/1e4,bt=_s/rr+Is;_s>1&&bt>Kt&&(Kt=bt,fs=[zr,ks,Ot,dr])}const[Ds,zt,rs,lr]=fs,Gs=Math.floor((zt+Ds)/2),ze=Math.floor((lr+rs)/2);Ie.push(...de.slice(0,Gs)),de=Tt.slice(ze),xe=de.length,Xe&&(ht.push(...gt.slice(0,Gs)),gt=Y[ft].slice(ze))}return Ie.push(...de),Xe?(ht.push(...gt),[Ie,ht]):[Ie,[]]}collateWordTimestamps(C,Y,de){const[xe,Ie,Xe]=this.combineTokensIntoWords(C,de),ht=[];for(let gt=0;gt=xe){const ht=((Xe-xe)*de).toFixed(2);Ie.push(`<|${ht}|>`),Ie.push([])}else Ie[Ie.length-1].push(Xe);return Ie=Ie.map(Xe=>typeof Xe=="string"?Xe:super.decode(Xe,Y)),Ie.join("")}splitTokensOnUnicode(C){const Y=this.decode(C,{decode_with_timestamps:!0}),de="�",xe=[],Ie=[],Xe=[];let ht=[],gt=[],ft=0;for(let Tt=0;Tt=this.model.tokens_to_ids.get("<|endoftext|>"),Ds=Tt.startsWith(" "),zt=Tt.trim(),rs=gt.test(zt);if(us||Ds||rs||Ie.length===0)Ie.push(Tt),Xe.push(Kt),ht.push(fs);else{const lr=Ie.length-1;Ie[lr]+=Tt,Xe[lr].push(...Kt),ht[lr].push(...fs)}}return[Ie,Xe,ht]}mergePunctuations(C,Y,de,xe,Ie){const Xe=structuredClone(C),ht=structuredClone(Y),gt=structuredClone(de);let ft=Xe.length-2,Tt=Xe.length-1;for(;ft>=0;)Xe[ft].startsWith(" ")&&xe.includes(Xe[ft].trim())?(Xe[Tt]=Xe[ft]+Xe[Tt],ht[Tt]=(0,T.mergeArrays)(ht[ft],ht[Tt]),gt[Tt]=(0,T.mergeArrays)(gt[ft],gt[Tt]),Xe[ft]="",ht[ft]=[],gt[ft]=[]):Tt=ft,--ft;for(ft=0,Tt=1;TtKt),ht.filter(Kt=>Kt.length>0),gt.filter(Kt=>Kt.length>0)]}}class En extends Nt{}class Cn extends Nt{}class Sn extends Nt{}class Lt extends Nt{constructor(C,Y){super(C,Y),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(de=>this.languageRegex.test(de)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(C){if(C===null)return null;const[Y,...de]=C.trim().split(this.languageRegex);if(de.length===0)return super._encode_text(Y);if(de.length===2){const[xe,Ie]=de;return this.supported_language_codes.includes(xe)||console.warn(`Unsupported language code "${xe}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,T.mergeArrays)([xe],super._encode_text(Ie))}}}class $n extends Nt{}class Un extends Nt{}class Vn extends Nt{}class Wn extends Nt{}class Xr extends Nt{}class Gn extends Nt{constructor(C,Y){super(C,Y),this.decoder=new St({})}}class kn extends Nt{}class Kn extends Nt{}class os{static async from_pretrained(C,{progress_callback:Y=null,config:de=null,cache_dir:xe=null,local_files_only:Ie=!1,revision:Xe="main",legacy:ht=null}={}){var fs;const[gt,ft]=await b(C,{progress_callback:Y,config:de,cache_dir:xe,local_files_only:Ie,revision:Xe,legacy:ht}),Tt=((fs=ft.tokenizer_class)==null?void 0:fs.replace(/Fast$/,""))??"PreTrainedTokenizer";let Kt=this.TOKENIZER_CLASS_MAPPING[Tt];return Kt||(console.warn(`Unknown tokenizer class "${Tt}", attempting to construct from base class.`),Kt=Nt),new Kt(gt,ft)}}_e(os,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Ws,DistilBertTokenizer:cr,CamembertTokenizer:it,DebertaTokenizer:fr,DebertaV2Tokenizer:Vr,BertTokenizer:rn,HerbertTokenizer:Dr,ConvBertTokenizer:Wr,RoFormerTokenizer:Gr,XLMTokenizer:xt,ElectraTokenizer:Ft,MobileBertTokenizer:Fr,SqueezeBertTokenizer:nn,AlbertTokenizer:Or,GPT2Tokenizer:Kr,BartTokenizer:Lr,MBartTokenizer:vs,MBart50Tokenizer:pr,RobertaTokenizer:Fs,WhisperTokenizer:on,CodeGenTokenizer:En,CLIPTokenizer:Cn,SiglipTokenizer:Sn,MarianTokenizer:Lt,BloomTokenizer:Sr,NllbTokenizer:hr,M2M100Tokenizer:Pn,LlamaTokenizer:Tn,CodeLlamaTokenizer:Hr,XLMRobertaTokenizer:di,MPNetTokenizer:Bn,FalconTokenizer:Rn,GPTNeoXTokenizer:Nn,EsmTokenizer:qr,Wav2Vec2CTCTokenizer:$n,BlenderbotTokenizer:Un,BlenderbotSmallTokenizer:Vn,SpeechT5Tokenizer:Wn,NougatTokenizer:Xr,VitsTokenizer:Gn,Qwen2Tokenizer:jn,GemmaTokenizer:ci,Grok1Tokenizer:Qr,CohereTokenizer:kn,MgpstrTokenizer:Kn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(R,c,s)=>{s.r(c),s.d(c,{RawAudio:()=>we,hamming:()=>x,hanning:()=>b,mel_filter_bank:()=>X,read_audio:()=>v,spectrogram:()=>L,window_function:()=>le});var h=s("./src/utils/hub.js"),T=s("./src/utils/maths.js"),I=s("./src/utils/core.js"),U=s("./src/env.js"),F=s("?7a2c"),_=s("./src/utils/tensor.js");async function v(ie,Pe){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 pe=await(await(0,h.getFile)(ie)).arrayBuffer(),ke=new AudioContext({sampleRate:Pe});typeof Pe>"u"&&console.warn(`No sampling rate provided, using default of ${ke.sampleRate}Hz.`);const Oe=await ke.decodeAudioData(pe);let Ce;if(Oe.numberOfChannels===2){const tt=Math.sqrt(2),Ge=Oe.getChannelData(0),be=Oe.getChannelData(1);Ce=new Float32Array(Ge.length);for(let Z=0;Z2595*Math.log10(1+ie/700),kaldi:ie=>1127*Math.log(1+ie/700),slaney:(ie,Pe=1e3,pe=15,ke=27/Math.log(6.4))=>ie>=Pe?pe+Math.log(ie/Pe)*ke:3*ie/200};function H(ie,Pe="htk"){const pe=O[Pe];if(!pe)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof ie=="number"?pe(ie):ie.map(ke=>pe(ke))}const re={htk:ie=>700*(10**(ie/2595)-1),kaldi:ie=>700*(Math.exp(ie/1127)-1),slaney:(ie,Pe=1e3,pe=15,ke=Math.log(6.4)/27)=>ie>=pe?Pe*Math.exp(ke*(ie-pe)):200*ie/3};function ne(ie,Pe="htk"){const pe=re[Pe];if(!pe)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof ie=="number"?pe(ie):ie.map(ke=>pe(ke))}function G(ie,Pe){const pe=Float64Array.from({length:Pe.length-1},(tt,Ge)=>Pe[Ge+1]-Pe[Ge]),ke=Array.from({length:ie.length},()=>new Array(Pe.length));for(let tt=0;ttnew Array(ie.length));for(let tt=0;ttie+ke*Ce)}function X(ie,Pe,pe,ke,Oe,Ce=null,tt="htk",Ge=!1){if(Ce!==null&&Ce!=="slaney")throw new Error('norm must be one of null or "slaney"');const be=H(pe,tt),Z=H(ke,tt),ce=W(be,Z,Pe+2);let Se=ne(ce,tt),Be;if(Ge){const se=Oe/(ie*2);Be=H(Float64Array.from({length:ie},(Ke,Ue)=>Ue*se),tt),Se=ce}else Be=W(0,Math.floor(Oe/2),ie);const Je=G(Be,Se);if(Ce!==null&&Ce==="slaney")for(let se=0;seOe)throw Error(`frame_length (${pe}) may not be larger than fft_length (${Oe})`);if(Ne!==pe)throw new Error(`Length of the window (${Ne}) must equal frame_length (${pe})`);if(ke<=0)throw new Error("hop_length must be greater than zero");if(Ce===null&&ce!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(tt){if(Ge!=="reflect")throw new Error(`pad_mode="${Ge}" not implemented yet.`);const Re=Math.floor((Oe-1)/2)+1;ie=D(ie,Re,Re)}let je=Math.floor(1+Math.floor((ie.length-pe)/ke));ue!==null&&jeje?Ve&&(pt=ve):pt=ut=ve);const lt=new T.FFT(Oe),mt=new Float64Array(Oe),B=new Float64Array(lt.outputBufferSize),ae=new Float32Array(st*pt);for(let Re=0;Re=1;--ct)mt[ct]-=Z*mt[ct-1];mt[0]*=1-Z}for(let ct=0;ctMath.pow(Ge,.85));break;default:throw new Error(`Unknown window type ${Pe}.`)}if(pe&&(tt=tt.subarray(0,ie)),ke===null)return tt;if(ie>ke)throw new Error(`Length of the window (${ie}) may not be larger than frame_length (${ke})`);return tt}function oe(ie,Pe){let pe=44;const ke=new ArrayBuffer(pe+ie.length*4),Oe=new DataView(ke);Te(Oe,0,"RIFF"),Oe.setUint32(4,36+ie.length*4,!0),Te(Oe,8,"WAVE"),Te(Oe,12,"fmt "),Oe.setUint32(16,16,!0),Oe.setUint16(20,3,!0),Oe.setUint16(22,1,!0),Oe.setUint32(24,Pe,!0),Oe.setUint32(28,Pe*4,!0),Oe.setUint16(32,4,!0),Oe.setUint16(34,32,!0),Te(Oe,36,"data"),Oe.setUint32(40,ie.length*4,!0);for(let Ce=0;Ce{let Ce=await Oe.arrayBuffer();F.writeFileSync(ke,Buffer.from(Ce))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await pe(Pe,this.toBlob())}}},"./src/utils/constants.js":(R,c,s)=>{s.r(c),s.d(c,{CHAT_TEMPLATE_NAME:()=>_,CONFIG_NAME:()=>T,FEATURE_EXTRACTOR_NAME:()=>I,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>h,IMAGE_PROCESSOR_NAME:()=>U,PROCESSOR_NAME:()=>F});const h="https://github.com/huggingface/transformers.js/issues/new/choose",T="config.json",I="preprocessor_config.json",U=I,F="processor_config.json",_="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(R,c,s)=>{s.r(c),s.d(c,{calculateDimensions:()=>v,calculateReflectOffset:()=>O,count:()=>G,dispatchCallback:()=>h,escapeRegExp:()=>I,isIntegralNumber:()=>F,isNullishDimension:()=>_,isTypedArray:()=>U,len:()=>ne,mergeArrays:()=>b,pick:()=>re,pop:()=>w,product:()=>x,reverseDictionary:()=>T,saveBlob:()=>H});function h(W,X){W&&W(X)}function T(W){return Object.fromEntries(Object.entries(W).map(([X,D])=>[D,X]))}function I(W){return W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(W){var X,D,A;return((A=(D=(X=W==null?void 0:W.prototype)==null?void 0:X.__proto__)==null?void 0:D.constructor)==null?void 0:A.name)==="TypedArray"}function F(W){return Number.isInteger(W)||typeof W=="bigint"}function _(W){return W==null||W===-1}function v(W){const X=[];let D=W;for(;Array.isArray(D);)X.push(D.length),D=D[0];return X}function w(W,X,D=void 0){const A=W[X];if(A!==void 0)return delete W[X],A;if(D===void 0)throw Error(`Key ${X} does not exist in object.`);return D}function b(...W){return Array.prototype.concat.apply([],W)}function x(...W){return W.reduce((X,D)=>X.flatMap(A=>D.map(M=>[A,M])))}function O(W,X){return Math.abs((W+X)%(2*X)-X)}function H(W,X){const D=URL.createObjectURL(X),A=document.createElement("a");A.href=D,A.download=W,A.click(),A.remove(),URL.revokeObjectURL(D)}function re(W,X){return Object.assign({},...X.map(D=>{if(W[D]!==void 0)return{[D]:W[D]}}))}function ne(W){let X=0;for(const D of W)++X;return X}function G(W,X){let D=0;for(const A of W)A===X&&++D;return D}},"./src/utils/data-structures.js":(R,c,s)=>{s.r(c),s.d(c,{CharTrie:()=>T,PriorityQueue:()=>h,TokenLattice:()=>U});class h{constructor(v=(b,x)=>b>x,w=1/0){this._heap=[],this._comparator=v,this._maxSize=w}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 w of v)if(this.size0&&this._swap(0,w),this._heap.pop(),this._siftDown(),v}replace(v){const w=this.peek();return this._heap[0]=v,this._siftDown(),w}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,w){return this._comparator(this._heap[v],this._heap[w])}_swap(v,w){const b=this._heap[v];this._heap[v]=this._heap[w],this._heap[w]=b}_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 x=new F(this.bosTokenId,0,0,0,0),O=new F(this.eosTokenId,1,this.len,0,0);this.nodes.push(x.clone()),this.nodes.push(O.clone()),this.beginNodes[this.len].push(O),this.endNodes[0].push(x)}insert(v,w,b,x){const O=this.nodes.length,H=new F(x,O,v,w,b);this.beginNodes[v].push(H),this.endNodes[v+w].push(H),this.nodes.push(H)}viterbi(){const v=this.len;let w=0;for(;w<=v;){if(this.beginNodes[w].length==0)return[];for(let re of this.beginNodes[w]){re.prev=null;let ne=0,G=null;for(let W of this.endNodes[w]){const X=W.backtraceScore+re.score;(G===null||X>ne)&&(G=W.clone(),ne=X)}if(G!==null)re.prev=G,re.backtraceScore=ne;else return[]}++w}const b=[],O=this.beginNodes[v][0].prev;if(O===null)return[];let H=O.clone();for(;H.prev!==null;)b.push(H.clone()),H=H.clone().prev.clone();return b.reverse(),b}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(w=>this.piece(w))}tokenIds(){return this.viterbi().map(w=>w.tokenId)}}class F{constructor(v,w,b,x,O){this.tokenId=v,this.nodeId=w,this.pos=b,this.length=x,this.score=O,this.prev=null,this.backtraceScore=0}clone(){const v=new F(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(R,c,s)=>{s.r(c),s.d(c,{DEVICE_TYPES:()=>h});const h=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":(R,c,s)=>{s.r(c),s.d(c,{DATA_TYPES:()=>U,DEFAULT_DEVICE_DTYPE_MAPPING:()=>F,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>_,isWebGpuFp16Supported:()=>I});var h=s("./src/env.js"),T=s("./src/utils/devices.js");const I=function(){let v;return async function(){if(v===void 0)if(!h.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),U=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),F=Object.freeze({[T.DEVICE_TYPES.wasm]:U.q8}),_=Object.freeze({[U.fp32]:"",[U.fp16]:"_fp16",[U.int8]:"_int8",[U.uint8]:"_uint8",[U.q8]:"_quantized",[U.q4]:"_q4",[U.q4f16]:"_q4f16",[U.bnb4]:"_bnb4"})},"./src/utils/generic.js":(R,c,s)=>{s.r(c),s.d(c,{Callable:()=>h});const h=class{constructor(){let T=function(...I){return T._call(...I)};return Object.setPrototypeOf(T,new.target.prototype)}_call(...T){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(R,c,s)=>{s.r(c),s.d(c,{getFile:()=>w,getModelFile:()=>re,getModelJSON:()=>ne});var h=s("?7a2c"),T=s("?a42a"),I=s("./src/env.js"),U=s("./src/utils/core.js");const F={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 _{constructor(D){if(this.filePath=D,this.headers=new Headers,this.exists=h.existsSync(D),this.exists){this.status=200,this.statusText="OK";let A=h.statSync(D);this.headers.set("content-length",A.size.toString()),this.updateContentType();let M=this;this.body=new ReadableStream({start(P){M.arrayBuffer().then(L=>{P.enqueue(new Uint8Array(L)),P.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const D=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",F[D]??"application/octet-stream")}clone(){let D=new _(this.filePath);return D.exists=this.exists,D.status=this.status,D.statusText=this.statusText,D.headers=new Headers(this.headers),D}async arrayBuffer(){return(await h.promises.readFile(this.filePath)).buffer}async blob(){const D=await h.promises.readFile(this.filePath);return new Blob([D],{type:this.headers.get("content-type")})}async text(){return await h.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(X,D=null,A=null){let M;try{M=new URL(X)}catch{return!1}return!(D&&!D.includes(M.protocol)||A&&!A.includes(M.hostname))}async function w(X){var D;if(I.env.useFS&&!v(X,["http:","https:","blob:"]))return new _(X);if(typeof process<"u"&&((D=process==null?void 0:process.release)==null?void 0:D.name)==="node"){const A=!!(zn!=null&&zn.TESTING_REMOTELY),M=I.env.version,P=new Headers;if(P.set("User-Agent",`transformers.js/${M}; is_ci/${A};`),v(X,["http:","https:"],["huggingface.co","hf.co"])){const le=(zn==null?void 0:zn.HF_TOKEN)??(zn==null?void 0:zn.HF_ACCESS_TOKEN);le&&P.set("Authorization",`Bearer ${le}`)}return fetch(X,{headers:P})}else return fetch(X)}const b={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 x(X,D,A){if(!A)return null;const M=b[X]??`Error (${X}) occurred while trying to load file`;throw Error(`${M}: "${D}".`)}class O{constructor(D){this.path=D}async match(D){let A=T.join(this.path,D),M=new _(A);if(M.exists)return M}async put(D,A){const M=Buffer.from(await A.arrayBuffer());let P=T.join(this.path,D);try{await h.promises.mkdir(T.dirname(P),{recursive:!0}),await h.promises.writeFile(P,M)}catch(L){console.warn("An error occurred while writing the file to cache:",L)}}}async function H(X,...D){for(let A of D)try{let M=await X.match(A);if(M)return M}catch{continue}}async function re(X,D,A=!0,M={}){if(!I.env.allowLocalModels){if(M.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(!I.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,U.dispatchCallback)(M.progress_callback,{status:"initiate",name:X,file:D});let P;if(!P&&I.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{P=await caches.open("transformers-cache")}catch(tt){console.warn("An error occurred while opening the browser cache:",tt)}}if(!P&&I.env.useFSCache&&(P=new O(M.cache_dir??I.env.cacheDir)),!P&&I.env.useCustomCache){if(!I.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!I.env.customCache.match||!I.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");P=I.env.customCache}const L=M.revision??"main";let le=W(X,D),oe=W(I.env.localModelPath,le),Te=W(I.env.remoteHost,I.env.remotePathTemplate.replaceAll("{model}",X).replaceAll("{revision}",encodeURIComponent(L)),D),we=L==="main"?le:W(X,L,D),ie,Pe=P instanceof O?we:Te,pe=!1,ke;P&&(ke=await H(P,oe,Pe));const Oe=ke!==void 0;if(ke===void 0){if(I.env.allowLocalModels)if(v(le,["http:","https:"])){if(M.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${le}.`);if(!I.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${le}.`)}else try{ke=await w(oe),ie=oe}catch(Ge){console.warn(`Unable to load from local path "${oe}": "${Ge}"`)}if(ke===void 0||ke.status===404){if(M.local_files_only||!I.env.allowRemoteModels){if(A)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${oe}".`);return null}if(ke=await w(Te),ke.status!==200)return x(ke.status,Te,A);ie=Pe}pe=P&&typeof Response<"u"&&ke instanceof Response&&ke.status===200}(0,U.dispatchCallback)(M.progress_callback,{status:"download",name:X,file:D});let Ce;return M.progress_callback?Oe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ce=new Uint8Array(await ke.arrayBuffer()),(0,U.dispatchCallback)(M.progress_callback,{status:"progress",name:X,file:D,progress:100,loaded:Ce.length,total:Ce.length})):Ce=await G(ke,tt=>{(0,U.dispatchCallback)(M.progress_callback,{status:"progress",name:X,file:D,...tt})}):Ce=new Uint8Array(await ke.arrayBuffer()),pe&&ie&&await P.match(ie)===void 0&&await P.put(ie,new Response(Ce,{headers:ke.headers})).catch(tt=>{console.warn(`Unable to add response to browser cache: ${tt}.`)}),(0,U.dispatchCallback)(M.progress_callback,{status:"done",name:X,file:D}),Ce}async function ne(X,D,A=!0,M={}){let P=await re(X,D,A,M);if(P===null)return{};let le=new TextDecoder("utf-8").decode(P);return JSON.parse(le)}async function G(X,D){const A=X.headers.get("Content-Length");A===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let M=parseInt(A??"0"),P=new Uint8Array(M),L=0;const le=X.body.getReader();async function oe(){const{done:Te,value:we}=await le.read();if(Te)return;let ie=L+we.length;if(ie>M){M=ie;let pe=new Uint8Array(M);pe.set(P),P=pe}P.set(we,L),L=ie;const Pe=L/M*100;return D({progress:Pe,loaded:L,total:M}),oe()}return await oe(),P}function W(...X){return X=X.map((D,A)=>(A&&(D=D.replace(new RegExp("^/"),"")),A!==X.length-1&&(D=D.replace(new RegExp("/$"),"")),D)),X.join("/")}},"./src/utils/image.js":(R,c,s)=>{s.r(c),s.d(c,{RawImage:()=>H,load_image:()=>re});var h=s("./src/utils/core.js"),T=s("./src/utils/hub.js"),I=s("./src/env.js"),U=s("./src/utils/tensor.js"),F=s("?2b25");let _,v,w;const b=I.apis.IS_BROWSER_ENV||I.apis.IS_WEBWORKER_ENV;if(b)_=(ne,G)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ne,G)},w=self.createImageBitmap,v=self.ImageData;else if(F)w=async ne=>{const W=(await ne.metadata()).channels,{data:X,info:D}=await ne.rotate().raw().toBuffer({resolveWithObject:!0}),A=new H(new Uint8ClampedArray(X),D.width,D.height,D.channels);return W!==void 0&&W!==D.channels&&A.convert(W),A};else throw new Error("Unable to load image processing library.");const x={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},O=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class H{constructor(G,W,X,D){this.data=G,this.width=W,this.height=X,this.channels=D}get size(){return[this.width,this.height]}static async read(G){if(G instanceof H)return G;if(typeof G=="string"||G instanceof URL)return await this.fromURL(G);throw new Error(`Unsupported input type: ${typeof G}`)}static fromCanvas(G){if(!b)throw new Error("fromCanvas() is only supported in browser environments.");const X=G.getContext("2d").getImageData(0,0,G.width,G.height).data;return new H(X,G.width,G.height,4)}static async fromURL(G){const W=await(0,T.getFile)(G);if(W.status!==200)throw new Error(`Unable to read image from "${G}" (${W.status} ${W.statusText})`);const X=await W.blob();return this.fromBlob(X)}static async fromBlob(G){if(b){const W=await w(G),X=_(W.width,W.height).getContext("2d");return X.drawImage(W,0,0),new this(X.getImageData(0,0,W.width,W.height).data,W.width,W.height,4)}else{const W=F(await G.arrayBuffer());return await w(W)}}static fromTensor(G,W="CHW"){if(G.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${G.dims.length} dimensions.`);if(W==="CHW")G=G.transpose(1,2,0);else if(W!=="HWC")throw new Error(`Unsupported channel format: ${W}`);if(!(G.data instanceof Uint8ClampedArray||G.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${G.type}`);switch(G.dims[2]){case 1:case 2:case 3:case 4:return new H(G.data,G.dims[1],G.dims[0],G.dims[2]);default:throw new Error(`Unsupported number of channels: ${G.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const G=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let W=0,X=0;W=0?L=X:oe=-X,D>=0?le=D:Te=-D,P.drawImage(M,L,le,G,W,oe,Te,G,W),new H(P.getImageData(0,0,G,W).data,G,W,4).convert(A)}else{let A=this.toSharp();if(X>=0&&D>=0)A=A.extract({left:Math.floor(X),top:Math.floor(D),width:G,height:W});else if(X<=0&&D<=0){const M=Math.floor(-D),P=Math.floor(-X);A=A.extend({top:M,left:P,right:G-this.width-P,bottom:W-this.height-M})}else{let M=[0,0],P=0;D<0?(M[0]=Math.floor(-D),M[1]=W-this.height-M[0]):P=Math.floor(D);let L=[0,0],le=0;X<0?(L[0]=Math.floor(-X),L[1]=G-this.width-L[0]):le=Math.floor(X),A=A.extend({top:M[0],bottom:M[1],left:L[0],right:L[1]}).extract({left:le,top:P,width:G,height:W})}return await w(A)}}async toBlob(G="image/png",W=1){if(!b)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:G,quality:W})}toTensor(G="CHW"){let W=new U.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(G!=="HWC")if(G==="CHW")W=W.permute(2,0,1);else throw new Error(`Unsupported channel format: ${G}`);return W}toCanvas(){if(!b)throw new Error("toCanvas() is only supported in browser environments.");const G=this.clone().rgba(),W=_(G.width,G.height),X=new v(G.data,G.width,G.height);return W.getContext("2d").putImageData(X,0,0),W}split(){const{data:G,width:W,height:X,channels:D}=this,A=G.constructor,M=G.length/D,P=Array.from({length:D},()=>new A(M));for(let L=0;Lnew H(L,W,X,1))}_update(G,W,X,D=null){return this.data=G,this.width=W,this.height=X,D!==null&&(this.channels=D),this}clone(){return new H(this.data.slice(),this.width,this.height,this.channels)}convert(G){if(this.channels===G)return this;switch(G){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(G){if(b){if(I.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const W=G.split(".").pop().toLowerCase(),X=O.get(W)??"image/png",D=await this.toBlob(X);(0,h.saveBlob)(G,D)}else{if(I.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(G);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(b)throw new Error("toSharp() is only supported in server-side environments.");return F(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const re=H.read.bind(H)},"./src/utils/maths.js":(R,c,s)=>{s.r(c),s.d(c,{FFT:()=>re,bankers_round:()=>W,cos_sim:()=>_,dot:()=>F,dynamic_time_warping:()=>X,interpolate_data:()=>h,log_softmax:()=>U,magnitude:()=>v,max:()=>b,medianFilter:()=>ne,min:()=>w,permute_data:()=>T,round:()=>G,softmax:()=>I});function h(D,[A,M,P],[L,le],oe="bilinear",Te=!1){const we=le/P,ie=L/M,Pe=new D.constructor(L*le*A),pe=M*P,ke=L*le;for(let Oe=0;Oe=0;--Te)L[Te]=we,P[Te]=A[M[Te]],we*=P[Te];const le=M.map((Te,we)=>L[M.indexOf(we)]),oe=new D.constructor(D.length);for(let Te=0;Te=0;--ie)we+=Pe%A[ie]*le[ie],Pe=Math.floor(Pe/A[ie]);oe[we]=D[Te]}return[oe,P]}function I(D){const A=b(D)[0],M=D.map(le=>Math.exp(le-A)),P=M.reduce((le,oe)=>le+oe,0);return M.map(le=>le/P)}function U(D){const A=b(D)[0];let M=0;for(let le=0;lele-A-P)}function F(D,A){let M=0;for(let P=0;PA+M*M,0))}function w(D){if(D.length===0)throw Error("Array must not be empty");let A=D[0],M=0;for(let P=1;PA&&(A=D[P],M=P);return[A,M]}function x(D){return D>0&&(D&D-1)===0}class O{constructor(A){if(this.size=A|0,this.size<=1||!x(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=A<<1,this.table=new Float64Array(this.size*2);for(let P=0;PP;P<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>L&3)<>>1);for(let L=0;L>>1]=A[L];return P}toComplexArray(A,M){const P=M||this.createComplexArray();for(let L=0;L>>1],P[L+1]=0;return P}transform(A,M){if(A===M)throw new Error("Input and output buffers must be different");this._transform4(A,M,1)}realTransform(A,M){if(A===M)throw new Error("Input and output buffers must be different");this._realTransform4(A,M,1)}inverseTransform(A,M){if(A===M)throw new Error("Input and output buffers must be different");this._transform4(A,M,-1);for(let P=0;P>=2;oe>=2;oe>>=2){Te=L/oe<<1;const ke=Te>>>2;for(we=0;we>>1,oe>>>1)}else for(we=0,ie=0;we>>1,oe>>>1,P)}const pe=this.table;for(oe>>=2;oe>=2;oe>>=2){Te=L/oe<<1;const Oe=Te>>>1,Ce=Oe>>>1,tt=Ce>>>1;for(we=0;we>>1;for(let Oe=2;Oe>1;++Pe){const pe=(Pe+1-A)**2/2,ke=Math.sqrt(we**2+ie**2)**pe,Oe=pe*Math.atan2(ie,we),Ce=2*Pe;le[Ce]=ke*Math.cos(Oe),le[Ce+1]=ke*Math.sin(Oe),oe[Ce]=le[Ce],oe[Ce+1]=-le[Ce+1]}this._slicedChirpBuffer=le.subarray(M,P),this._f=new O(L>>1),this._f.transform(this._chirpBuffer,oe)}_transform(A,M,P){const L=this._buffer1,le=this._buffer2,oe=this._outBuffer1,Te=this._outBuffer2,we=this._chirpBuffer,ie=this._slicedChirpBuffer,Pe=this._a;if(P)for(let pe=0;pe>1,Ce=M[Oe];L[pe]=Ce*ie[pe],L[ke]=Ce*ie[ke]}else for(let pe=0;pe=D.length&&(we=2*(D.length-1)-we),P[oe++]=D[we]}P.sort(),M[le]=P[L]}return M}function G(D,A){const M=Math.pow(10,A);return Math.round(D*M)/M}function W(D){const A=Math.round(D);return Math.abs(D)%1===.5?A%2===0?A:A-1:A}function X(D){const A=D.length,M=D[0].length,P=[A+1,M+1],L=Array.from({length:P[0]},()=>Array(P[1]).fill(1/0));L[0][0]=0;const le=Array.from({length:P[0]},()=>Array(P[1]).fill(-1));for(let Pe=1;Pe0||Te>0;)switch(we.push(oe-1),ie.push(Te-1),le[oe][Te]){case 0:--oe,--Te;break;case 1:--oe;break;case 2:--Te;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${oe}, ${Te}]. Please file a bug report.`)}return we.reverse(),ie.reverse(),[we,ie]}},"./src/utils/tensor.js":(R,c,s)=>{s.r(c),s.d(c,{Tensor:()=>F,cat:()=>M,full:()=>ie,full_like:()=>Pe,interpolate:()=>w,interpolate_4d:()=>b,layer_norm:()=>W,matmul:()=>x,mean:()=>oe,mean_pooling:()=>G,ones:()=>pe,ones_like:()=>ke,permute:()=>v,quantize_embeddings:()=>Ge,rand:()=>tt,rfft:()=>O,slice:()=>ne,stack:()=>P,std_mean:()=>le,topk:()=>H,zeros:()=>Oe,zeros_like:()=>Ce});var h=s("./src/utils/maths.js"),T=s("./src/backends/onnx.js"),I=s("./src/ops/registry.js");const U=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 F{constructor(...Z){_e(this,"ort_tensor");return(0,T.isONNXTensor)(Z[0])?this.ort_tensor=Z[0]:this.ort_tensor=new T.Tensor(Z[0],Z[1],Z[2]),new Proxy(this,{get:(ce,Se)=>{if(typeof Se=="string"){let Be=Number(Se);if(Number.isInteger(Be))return ce._getitem(Be)}return ce[Se]},set:(ce,Se,Be)=>ce[Se]=Be})}get dims(){return this.ort_tensor.dims}set dims(Z){this.ort_tensor.dims=Z}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[Z,...ce]=this.dims;if(ce.length>0){const Se=ce.reduce((Be,Je)=>Be*Je);for(let Be=0;Be0){const Be=Se.reduce((Je,se)=>Je*se);return this._subarray(Z,Be,Se)}else return new F(this.type,[this.data[Z]],Se)}indexOf(Z){const ce=this.data;for(let Se=0;SeWe)throw new Error(`Invalid slice: ${ve}`);const Ne=[Math.max(Ve,0),Math.min(We,this.dims[ue])];Se.push(Ne),ce.push(Ne[1]-Ne[0])}else throw new Error(`Invalid slice: ${ve}`)}const Be=Se.map(([ue,ve])=>ve-ue),Je=Be.reduce((ue,ve)=>ue*ve),se=this.data,Ke=new se.constructor(Je),Ue=this.stride();for(let ue=0;ue=0;--Ve){const Ne=Be[Ve];ve+=(We%Ne+Se[Ve][0])*Ue[Ve],We=Math.floor(We/Ne)}Ke[ue]=se[ve]}return new F(this.type,Ke,ce)}permute(...Z){return v(this,Z)}transpose(...Z){return this.permute(...Z)}sum(Z=null,ce=!1){return this.norm(1,Z,ce)}norm(Z="fro",ce=null,Se=!1){if(Z==="fro")Z=2;else if(typeof Z=="string")throw Error(`Unsupported norm: ${Z}`);const Be=this.data,Je=(ue,ve)=>ue+ve**Z;if(ce===null){const ue=Be.reduce(Je,0)**(1/Z);return new F(this.type,[ue],[])}const[se,Ke,Ue]=L(Je,this,ce,Se);if(Z!==1)for(let ue=0;ue=0;--Ue){const Ve=this.dims[Ue];if(Ue!==ce){const We=ue%Ve;Ke+=We*ve,ve*=this.dims[Ue]}ue=Math.floor(ue/Ve)}Be[se]/=Je[Ke]}return this}normalize(Z=2,ce=1){return this.clone().normalize_(Z,ce)}stride(){return Te(this.dims)}squeeze(Z=null){return new F(this.type,this.data,X(this.dims,Z))}squeeze_(Z=null){return this.dims=X(this.dims,Z),this}unsqueeze(Z=null){return new F(this.type,this.data,D(this.dims,Z))}unsqueeze_(Z=null){return this.dims=D(this.dims,Z),this}flatten_(Z=0,ce=-1){ce=(ce+this.dims.length)%this.dims.length;let Se=this.dims.slice(0,Z),Be=this.dims.slice(Z,ce+1),Je=this.dims.slice(ce+1);return this.dims=[...Se,Be.reduce((se,Ke)=>se*Ke,1),...Je],this}flatten(Z=0,ce=-1){return this.clone().flatten_(Z,ce)}view(...Z){let ce=-1;for(let Be=0;BeKe!==ce?Je*se:Je,1);Z[ce]=Se.length/Be}return new F(this.type,Se,Z)}neg_(){const Z=this.data;for(let ce=0;ceZ?1:0;return new F("bool",ce,this.dims)}lt(Z){const ce=new Uint8Array(this.data.length),Se=this.data;for(let Be=0;BeMath.min(se,Ke),this,Z,ce,1/0);return new F(Se,Be,Je)}max(Z=null,ce=!1){if(Z===null){const se=(0,h.max)(this.data)[0];return new F(this.type,[se],[])}const[Se,Be,Je]=L((se,Ke)=>Math.max(se,Ke),this,Z,ce,-1/0);return new F(Se,Be,Je)}argmin(Z=null,ce=!1){if(Z!==null)throw new Error("`dim !== null` not yet implemented.");const Se=(0,h.min)(this.data)[1];return new F("int64",[BigInt(Se)],[])}argmax(Z=null,ce=!1){if(Z!==null)throw new Error("`dim !== null` not yet implemented.");const Se=(0,h.max)(this.data)[1];return new F("int64",[BigInt(Se)],[])}to(Z){if(this.type===Z)return this;if(!U.hasOwnProperty(Z))throw new Error(`Unsupported type: ${Z}`);let ce;const Se=["int64","uint64"].includes(this.type),Be=["int64","uint64"].includes(Z);return Se&&!Be?ce=Number:!Se&&Be&&(ce=BigInt),new F(Z,U[Z].from(this.data,ce),this.dims)}}function _(be,Z){const ce=be.length,Se=Z.reduce((Je,se)=>Je*se);if(ce!==Se)throw Error(`cannot reshape array of size ${ce} into shape (${Z})`);let Be=be;for(let Je=Z.length-1;Je>=0;Je--)Be=Be.reduce((se,Ke)=>{let Ue=se[se.length-1];return Ue.lengthnew F("int64",be,[be.length]);async function ne(be,Z,ce,Se,Be){return await(await I.TensorOpRegistry.slice)({x:be,s:re(Z),e:re(ce),a:re(Se),t:re(Be??new Array(Se.length).fill(1))})}function G(be,Z){const ce=be.data,Se=Z.data,Be=[be.dims[0],be.dims[2]],Je=new ce.constructor(Be[0]*Be[1]),[se,Ke,Ue]=be.dims;let ue=0;for(let ve=0;vece!==1):typeof Z=="number"?be[Z]===1&&be.splice(Z,1):Array.isArray(Z)&&(be=be.filter((ce,Se)=>ce!==1||!Z.includes(Se))),be}function D(be,Z){return Z=A(Z,be.length+1),be=be.slice(),be.splice(Z,0,1),be}function A(be,Z,ce=null,Se=!0){if(Se&&(be<-Z||be>=Z))throw new Error(`IndexError: index ${be} is out of bounds for dimension${ce===null?"":" "+ce} with size ${Z}`);return be<0&&(be=(be%Z+Z)%Z),be}function M(be,Z=0){Z=A(Z,be[0].dims.length);const ce=be[0].dims.slice();ce[Z]=be.reduce((se,Ke)=>se+Ke.dims[Z],0);const Se=ce.reduce((se,Ke)=>se*Ke,1),Be=new be[0].data.constructor(Se),Je=be[0].type;if(Z===0){let se=0;for(const Ke of be){const Ue=Ke.data;Be.set(Ue,se),se+=Ue.length}}else{let se=0;for(let Ke=0;Ke=0;--We){const st=ue[We];let ut=Ne%st;We===Z&&(ut+=se),Ve+=ut*je,je*=ce[We],Ne=Math.floor(Ne/st)}Be[Ve]=Ue[ve]}se+=ue[Z]}}return new F(Je,Be,ce)}function P(be,Z=0){return M(be.map(ce=>ce.unsqueeze(Z)),Z)}function L(be,Z,ce=null,Se=!1,Be=null){const Je=Z.data,se=Z.dims;ce=A(ce,se.length);const Ke=se.slice();Ke[ce]=1;const Ue=new Je.constructor(Je.length/se[ce]);Be!==null&&Ue.fill(Be);for(let ue=0;ue=0;--Ve){const je=se[Ve];if(Ve!==ce){const st=We%je;ve+=st*Ne,Ne*=Ke[Ve]}We=Math.floor(We/je)}Ue[ve]=be(Ue[ve],Je[ue],ue,ve)}return Se||Ke.splice(ce,1),[Z.type,Ue,Ke]}function le(be,Z=null,ce=1,Se=!1){const Be=be.data,Je=be.dims;if(Z===null){const Ne=Be.reduce((pt,lt)=>pt+lt,0)/Be.length,je=Math.sqrt(Be.reduce((pt,lt)=>pt+(lt-Ne)**2,0)/(Be.length-ce)),st=new F(be.type,[Ne],[]);return[new F(be.type,[je],[]),st]}Z=A(Z,Je.length);const se=oe(be,Z,Se),Ke=se.data,[Ue,ue,ve]=L((We,Ne,je,st)=>We+(Ne-Ke[st])**2,be,Z,Se);for(let We=0;Weue+ve,0);return new F(be.type,[Ue/Be.length],[])}Z=A(Z,Se.length);const[Je,se,Ke]=L((Ue,ue)=>Ue+ue,be,Z,ce);if(Se[Z]!==1)for(let Ue=0;Ue=0;--ce)Z[ce]=Se,Se*=be[ce];return Z}function we(be,Z,ce,Se){const Be=be.reduce((Je,se)=>Je*se,1);return new F(ce,new Se(Be).fill(Z),be)}function ie(be,Z){let ce,Se;if(typeof Z=="number")ce="float32",Se=Float32Array;else if(typeof Z=="bigint")ce="int64",Se=BigInt64Array;else if(typeof Z=="boolean")ce="bool",Se=Uint8Array;else throw new Error(`Unsupported data type: ${typeof Z}`);return we(be,Z,ce,Se)}function Pe(be,Z){return ie(be.dims,Z)}function pe(be){return we(be,1n,"int64",BigInt64Array)}function ke(be){return pe(be.dims)}function Oe(be){return we(be,0n,"int64",BigInt64Array)}function Ce(be){return Oe(be.dims)}function tt(be){const Z=be.reduce((ce,Se)=>ce*Se,1);return new F("float32",Float32Array.from({length:Z},()=>Math.random()),be)}function Ge(be,Z){if(be.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(be.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(Z))throw new Error("The precision must be either 'binary' or 'ubinary'");const ce=Z==="binary",Se=ce?"int8":"uint8",Be=ce?Int8Array:Uint8Array,Je=be.data,se=new Be(Je.length/8);for(let Ke=0;Ke0?1:0,ue=Math.floor(Ke/8),ve=Ke%8;se[ue]|=Ue<<7-ve,ce&&ve===0&&(se[ue]-=128)}return new F(Se,se,[be.dims[0],be.dims[1]/8])}}},Af={};function bs(R){var c=Af[R];if(c!==void 0)return c.exports;var s=Af[R]={exports:{}};return Vf[R](s,s.exports,bs),s.exports}bs.m=Vf;(()=>{var R=Object.getPrototypeOf?s=>Object.getPrototypeOf(s):s=>s.__proto__,c;bs.t=function(s,h){if(h&1&&(s=this(s)),h&8||typeof s=="object"&&s&&(h&4&&s.__esModule||h&16&&typeof s.then=="function"))return s;var T=Object.create(null);bs.r(T);var I={};c=c||[null,R({}),R([]),R(R)];for(var U=h&2&&s;typeof U=="object"&&!~c.indexOf(U);U=R(U))Object.getOwnPropertyNames(U).forEach(F=>I[F]=()=>s[F]);return I.default=()=>s,bs.d(T,I),T}})();bs.d=(R,c)=>{for(var s in c)bs.o(c,s)&&!bs.o(R,s)&&Object.defineProperty(R,s,{enumerable:!0,get:c[s]})};bs.o=(R,c)=>Object.prototype.hasOwnProperty.call(R,c);bs.r=R=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(R,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(R,"__esModule",{value:!0})};(()=>{var R;if(typeof import.meta.url=="string"&&(R=import.meta.url),!R)throw new Error("Automatic publicPath is not supported in this browser");R=R.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),bs.p=R})();bs.b=new URL(import.meta.url);var p={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/bs.r(p),bs.d(p,{ASTFeatureExtractor:()=>w.ASTFeatureExtractor,ASTForAudioClassification:()=>s.ASTForAudioClassification,ASTModel:()=>s.ASTModel,ASTPreTrainedModel:()=>s.ASTPreTrainedModel,AlbertForMaskedLM:()=>s.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>s.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>s.AlbertForSequenceClassification,AlbertModel:()=>s.AlbertModel,AlbertPreTrainedModel:()=>s.AlbertPreTrainedModel,AlbertTokenizer:()=>h.AlbertTokenizer,AudioClassificationPipeline:()=>c.AudioClassificationPipeline,AutoConfig:()=>T.AutoConfig,AutoFeatureExtractor:()=>b.AutoFeatureExtractor,AutoImageProcessor:()=>H.AutoImageProcessor,AutoModel:()=>s.AutoModel,AutoModelForAudioClassification:()=>s.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>s.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>s.AutoModelForCTC,AutoModelForCausalLM:()=>s.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>s.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>s.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>s.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>s.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>s.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>s.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>s.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>s.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>s.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>s.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>s.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>s.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>s.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>s.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>s.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>s.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>s.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>s.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>s.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>s.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>s.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>s.AutoModelForVision2Seq,AutoModelForXVector:()=>s.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>s.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>G.AutoProcessor,AutoTokenizer:()=>h.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>c.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>s.BartForConditionalGeneration,BartForSequenceClassification:()=>s.BartForSequenceClassification,BartModel:()=>s.BartModel,BartPretrainedModel:()=>s.BartPretrainedModel,BartTokenizer:()=>h.BartTokenizer,BaseModelOutput:()=>s.BaseModelOutput,BaseStreamer:()=>W.BaseStreamer,BeitFeatureExtractor:()=>O.BeitFeatureExtractor,BeitForImageClassification:()=>s.BeitForImageClassification,BeitModel:()=>s.BeitModel,BeitPreTrainedModel:()=>s.BeitPreTrainedModel,BertForMaskedLM:()=>s.BertForMaskedLM,BertForQuestionAnswering:()=>s.BertForQuestionAnswering,BertForSequenceClassification:()=>s.BertForSequenceClassification,BertForTokenClassification:()=>s.BertForTokenClassification,BertModel:()=>s.BertModel,BertPreTrainedModel:()=>s.BertPreTrainedModel,BertTokenizer:()=>h.BertTokenizer,BitImageProcessor:()=>O.BitImageProcessor,BlenderbotForConditionalGeneration:()=>s.BlenderbotForConditionalGeneration,BlenderbotModel:()=>s.BlenderbotModel,BlenderbotPreTrainedModel:()=>s.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>s.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>s.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>s.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>h.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>h.BlenderbotTokenizer,BloomForCausalLM:()=>s.BloomForCausalLM,BloomModel:()=>s.BloomModel,BloomPreTrainedModel:()=>s.BloomPreTrainedModel,BloomTokenizer:()=>h.BloomTokenizer,CLIPFeatureExtractor:()=>O.CLIPFeatureExtractor,CLIPImageProcessor:()=>O.CLIPImageProcessor,CLIPModel:()=>s.CLIPModel,CLIPPreTrainedModel:()=>s.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>s.CLIPSegForImageSegmentation,CLIPSegModel:()=>s.CLIPSegModel,CLIPSegPreTrainedModel:()=>s.CLIPSegPreTrainedModel,CLIPTextModel:()=>s.CLIPTextModel,CLIPTextModelWithProjection:()=>s.CLIPTextModelWithProjection,CLIPTokenizer:()=>h.CLIPTokenizer,CLIPVisionModel:()=>s.CLIPVisionModel,CLIPVisionModelWithProjection:()=>s.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>s.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>s.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>s.CamembertForSequenceClassification,CamembertForTokenClassification:()=>s.CamembertForTokenClassification,CamembertModel:()=>s.CamembertModel,CamembertPreTrainedModel:()=>s.CamembertPreTrainedModel,CamembertTokenizer:()=>h.CamembertTokenizer,CausalLMOutput:()=>s.CausalLMOutput,CausalLMOutputWithPast:()=>s.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>O.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>s.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>s.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>s.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>w.ClapFeatureExtractor,ClapModel:()=>s.ClapModel,ClapPreTrainedModel:()=>s.ClapPreTrainedModel,ClapTextModelWithProjection:()=>s.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>D.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>s.CodeGenForCausalLM,CodeGenModel:()=>s.CodeGenModel,CodeGenPreTrainedModel:()=>s.CodeGenPreTrainedModel,CodeGenTokenizer:()=>h.CodeGenTokenizer,CodeLlamaTokenizer:()=>h.CodeLlamaTokenizer,CohereForCausalLM:()=>s.CohereForCausalLM,CohereModel:()=>s.CohereModel,CoherePreTrainedModel:()=>s.CoherePreTrainedModel,CohereTokenizer:()=>h.CohereTokenizer,ConvBertForMaskedLM:()=>s.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>s.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>s.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>s.ConvBertForTokenClassification,ConvBertModel:()=>s.ConvBertModel,ConvBertPreTrainedModel:()=>s.ConvBertPreTrainedModel,ConvBertTokenizer:()=>h.ConvBertTokenizer,ConvNextFeatureExtractor:()=>O.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>s.ConvNextForImageClassification,ConvNextImageProcessor:()=>O.ConvNextImageProcessor,ConvNextModel:()=>s.ConvNextModel,ConvNextPreTrainedModel:()=>s.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>s.ConvNextV2ForImageClassification,ConvNextV2Model:()=>s.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>s.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>O.DPTFeatureExtractor,DPTForDepthEstimation:()=>s.DPTForDepthEstimation,DPTImageProcessor:()=>O.DPTImageProcessor,DPTModel:()=>s.DPTModel,DPTPreTrainedModel:()=>s.DPTPreTrainedModel,DebertaForMaskedLM:()=>s.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>s.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>s.DebertaForSequenceClassification,DebertaForTokenClassification:()=>s.DebertaForTokenClassification,DebertaModel:()=>s.DebertaModel,DebertaPreTrainedModel:()=>s.DebertaPreTrainedModel,DebertaTokenizer:()=>h.DebertaTokenizer,DebertaV2ForMaskedLM:()=>s.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>s.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>s.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>s.DebertaV2ForTokenClassification,DebertaV2Model:()=>s.DebertaV2Model,DebertaV2PreTrainedModel:()=>s.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>h.DebertaV2Tokenizer,DecisionTransformerModel:()=>s.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>s.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>O.DeiTFeatureExtractor,DeiTForImageClassification:()=>s.DeiTForImageClassification,DeiTImageProcessor:()=>O.DeiTImageProcessor,DeiTModel:()=>s.DeiTModel,DeiTPreTrainedModel:()=>s.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>s.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>s.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>c.DepthEstimationPipeline,DepthProForDepthEstimation:()=>s.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>s.DepthProPreTrainedModel,DetrFeatureExtractor:()=>O.DetrFeatureExtractor,DetrForObjectDetection:()=>s.DetrForObjectDetection,DetrForSegmentation:()=>s.DetrForSegmentation,DetrImageProcessor:()=>O.DetrImageProcessor,DetrModel:()=>s.DetrModel,DetrObjectDetectionOutput:()=>s.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>s.DetrPreTrainedModel,DetrSegmentationOutput:()=>s.DetrSegmentationOutput,Dinov2ForImageClassification:()=>s.Dinov2ForImageClassification,Dinov2Model:()=>s.Dinov2Model,Dinov2PreTrainedModel:()=>s.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>s.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>s.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>s.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>s.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>s.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>s.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>s.DistilBertForTokenClassification,DistilBertModel:()=>s.DistilBertModel,DistilBertPreTrainedModel:()=>s.DistilBertPreTrainedModel,DistilBertTokenizer:()=>h.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>c.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>O.DonutFeatureExtractor,DonutImageProcessor:()=>O.DonutImageProcessor,DonutSwinModel:()=>s.DonutSwinModel,DonutSwinPreTrainedModel:()=>s.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>s.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>O.EfficientNetImageProcessor,EfficientNetModel:()=>s.EfficientNetModel,EfficientNetPreTrainedModel:()=>s.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>s.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>s.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>s.ElectraForSequenceClassification,ElectraForTokenClassification:()=>s.ElectraForTokenClassification,ElectraModel:()=>s.ElectraModel,ElectraPreTrainedModel:()=>s.ElectraPreTrainedModel,ElectraTokenizer:()=>h.ElectraTokenizer,EosTokenCriteria:()=>X.EosTokenCriteria,EsmForMaskedLM:()=>s.EsmForMaskedLM,EsmForSequenceClassification:()=>s.EsmForSequenceClassification,EsmForTokenClassification:()=>s.EsmForTokenClassification,EsmModel:()=>s.EsmModel,EsmPreTrainedModel:()=>s.EsmPreTrainedModel,EsmTokenizer:()=>h.EsmTokenizer,ExaoneForCausalLM:()=>s.ExaoneForCausalLM,ExaoneModel:()=>s.ExaoneModel,ExaonePreTrainedModel:()=>s.ExaonePreTrainedModel,FFT:()=>_.FFT,FalconForCausalLM:()=>s.FalconForCausalLM,FalconModel:()=>s.FalconModel,FalconPreTrainedModel:()=>s.FalconPreTrainedModel,FalconTokenizer:()=>h.FalconTokenizer,FastViTForImageClassification:()=>s.FastViTForImageClassification,FastViTModel:()=>s.FastViTModel,FastViTPreTrainedModel:()=>s.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>c.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>c.FillMaskPipeline,Florence2ForConditionalGeneration:()=>s.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>s.Florence2PreTrainedModel,Florence2Processor:()=>ne.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>D.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>D.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>O.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>s.GLPNForDepthEstimation,GLPNModel:()=>s.GLPNModel,GLPNPreTrainedModel:()=>s.GLPNPreTrainedModel,GPT2LMHeadModel:()=>s.GPT2LMHeadModel,GPT2Model:()=>s.GPT2Model,GPT2PreTrainedModel:()=>s.GPT2PreTrainedModel,GPT2Tokenizer:()=>h.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>s.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>s.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>s.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>s.GPTJForCausalLM,GPTJModel:()=>s.GPTJModel,GPTJPreTrainedModel:()=>s.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>s.GPTNeoForCausalLM,GPTNeoModel:()=>s.GPTNeoModel,GPTNeoPreTrainedModel:()=>s.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>s.GPTNeoXForCausalLM,GPTNeoXModel:()=>s.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>s.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>h.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>s.Gemma2ForCausalLM,Gemma2Model:()=>s.Gemma2Model,Gemma2PreTrainedModel:()=>s.Gemma2PreTrainedModel,GemmaForCausalLM:()=>s.GemmaForCausalLM,GemmaModel:()=>s.GemmaModel,GemmaPreTrainedModel:()=>s.GemmaPreTrainedModel,GemmaTokenizer:()=>h.GemmaTokenizer,GlmForCausalLM:()=>s.GlmForCausalLM,GlmModel:()=>s.GlmModel,GlmPreTrainedModel:()=>s.GlmPreTrainedModel,GraniteForCausalLM:()=>s.GraniteForCausalLM,GraniteModel:()=>s.GraniteModel,GranitePreTrainedModel:()=>s.GranitePreTrainedModel,Grok1Tokenizer:()=>h.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>s.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>O.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>s.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>ne.GroundingDinoProcessor,GroupViTModel:()=>s.GroupViTModel,GroupViTPreTrainedModel:()=>s.GroupViTPreTrainedModel,HeliumForCausalLM:()=>s.HeliumForCausalLM,HeliumModel:()=>s.HeliumModel,HeliumPreTrainedModel:()=>s.HeliumPreTrainedModel,HerbertTokenizer:()=>h.HerbertTokenizer,HieraForImageClassification:()=>s.HieraForImageClassification,HieraModel:()=>s.HieraModel,HieraPreTrainedModel:()=>s.HieraPreTrainedModel,HubertForCTC:()=>s.HubertForCTC,HubertForSequenceClassification:()=>s.HubertForSequenceClassification,HubertModel:()=>s.HubertModel,HubertPreTrainedModel:()=>s.HubertPreTrainedModel,IJepaForImageClassification:()=>s.IJepaForImageClassification,IJepaModel:()=>s.IJepaModel,IJepaPreTrainedModel:()=>s.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>s.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>O.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>s.Idefics3PreTrainedModel,Idefics3Processor:()=>ne.Idefics3Processor,ImageClassificationPipeline:()=>c.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>c.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>w.ImageFeatureExtractor,ImageMattingOutput:()=>s.ImageMattingOutput,ImageProcessor:()=>x.ImageProcessor,ImageSegmentationPipeline:()=>c.ImageSegmentationPipeline,ImageToImagePipeline:()=>c.ImageToImagePipeline,ImageToTextPipeline:()=>c.ImageToTextPipeline,InterruptableStoppingCriteria:()=>X.InterruptableStoppingCriteria,JAISLMHeadModel:()=>s.JAISLMHeadModel,JAISModel:()=>s.JAISModel,JAISPreTrainedModel:()=>s.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>O.JinaCLIPImageProcessor,JinaCLIPModel:()=>s.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>s.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ne.JinaCLIPProcessor,JinaCLIPTextModel:()=>s.JinaCLIPTextModel,JinaCLIPVisionModel:()=>s.JinaCLIPVisionModel,LlamaForCausalLM:()=>s.LlamaForCausalLM,LlamaModel:()=>s.LlamaModel,LlamaPreTrainedModel:()=>s.LlamaPreTrainedModel,LlamaTokenizer:()=>h.LlamaTokenizer,LlavaForConditionalGeneration:()=>s.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>s.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>O.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>s.LlavaPreTrainedModel,LogitsProcessor:()=>D.LogitsProcessor,LogitsProcessorList:()=>D.LogitsProcessorList,LogitsWarper:()=>D.LogitsWarper,LongT5ForConditionalGeneration:()=>s.LongT5ForConditionalGeneration,LongT5Model:()=>s.LongT5Model,LongT5PreTrainedModel:()=>s.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>s.M2M100ForConditionalGeneration,M2M100Model:()=>s.M2M100Model,M2M100PreTrainedModel:()=>s.M2M100PreTrainedModel,M2M100Tokenizer:()=>h.M2M100Tokenizer,MBart50Tokenizer:()=>h.MBart50Tokenizer,MBartForCausalLM:()=>s.MBartForCausalLM,MBartForConditionalGeneration:()=>s.MBartForConditionalGeneration,MBartForSequenceClassification:()=>s.MBartForSequenceClassification,MBartModel:()=>s.MBartModel,MBartPreTrainedModel:()=>s.MBartPreTrainedModel,MBartTokenizer:()=>h.MBartTokenizer,MPNetForMaskedLM:()=>s.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>s.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>s.MPNetForSequenceClassification,MPNetForTokenClassification:()=>s.MPNetForTokenClassification,MPNetModel:()=>s.MPNetModel,MPNetPreTrainedModel:()=>s.MPNetPreTrainedModel,MPNetTokenizer:()=>h.MPNetTokenizer,MT5ForConditionalGeneration:()=>s.MT5ForConditionalGeneration,MT5Model:()=>s.MT5Model,MT5PreTrainedModel:()=>s.MT5PreTrainedModel,MarianMTModel:()=>s.MarianMTModel,MarianModel:()=>s.MarianModel,MarianPreTrainedModel:()=>s.MarianPreTrainedModel,MarianTokenizer:()=>h.MarianTokenizer,Mask2FormerImageProcessor:()=>O.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>O.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>s.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>O.MaskFormerImageProcessor,MaskFormerModel:()=>s.MaskFormerModel,MaskFormerPreTrainedModel:()=>s.MaskFormerPreTrainedModel,MaskedLMOutput:()=>s.MaskedLMOutput,MaxLengthCriteria:()=>X.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>s.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>s.MgpstrModelOutput,MgpstrPreTrainedModel:()=>s.MgpstrPreTrainedModel,MgpstrProcessor:()=>ne.MgpstrProcessor,MgpstrTokenizer:()=>h.MgpstrTokenizer,MinLengthLogitsProcessor:()=>D.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>D.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>s.MistralForCausalLM,MistralModel:()=>s.MistralModel,MistralPreTrainedModel:()=>s.MistralPreTrainedModel,MobileBertForMaskedLM:()=>s.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>s.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>s.MobileBertForSequenceClassification,MobileBertModel:()=>s.MobileBertModel,MobileBertPreTrainedModel:()=>s.MobileBertPreTrainedModel,MobileBertTokenizer:()=>h.MobileBertTokenizer,MobileLLMForCausalLM:()=>s.MobileLLMForCausalLM,MobileLLMModel:()=>s.MobileLLMModel,MobileLLMPreTrainedModel:()=>s.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>O.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>s.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>O.MobileNetV1ImageProcessor,MobileNetV1Model:()=>s.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>s.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>O.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>s.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>O.MobileNetV2ImageProcessor,MobileNetV2Model:()=>s.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>s.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>O.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>s.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>O.MobileNetV3ImageProcessor,MobileNetV3Model:()=>s.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>s.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>s.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileNetV4Model:()=>s.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>s.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>O.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>s.MobileViTForImageClassification,MobileViTImageProcessor:()=>O.MobileViTImageProcessor,MobileViTModel:()=>s.MobileViTModel,MobileViTPreTrainedModel:()=>s.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>s.MobileViTV2ForImageClassification,MobileViTV2Model:()=>s.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>s.MobileViTV2PreTrainedModel,ModelOutput:()=>s.ModelOutput,ModernBertForMaskedLM:()=>s.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>s.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>s.ModernBertForTokenClassification,ModernBertModel:()=>s.ModernBertModel,ModernBertPreTrainedModel:()=>s.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>s.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>w.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>s.MoonshineForConditionalGeneration,MoonshineModel:()=>s.MoonshineModel,MoonshinePreTrainedModel:()=>s.MoonshinePreTrainedModel,MoonshineProcessor:()=>ne.MoonshineProcessor,MptForCausalLM:()=>s.MptForCausalLM,MptModel:()=>s.MptModel,MptPreTrainedModel:()=>s.MptPreTrainedModel,MultiModalityCausalLM:()=>s.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>s.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>s.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>s.MusicgenForConditionalGeneration,MusicgenModel:()=>s.MusicgenModel,MusicgenPreTrainedModel:()=>s.MusicgenPreTrainedModel,NllbTokenizer:()=>h.NllbTokenizer,NoBadWordsLogitsProcessor:()=>D.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>D.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>s.NomicBertModel,NomicBertPreTrainedModel:()=>s.NomicBertPreTrainedModel,NougatImageProcessor:()=>O.NougatImageProcessor,NougatTokenizer:()=>h.NougatTokenizer,OPTForCausalLM:()=>s.OPTForCausalLM,OPTModel:()=>s.OPTModel,OPTPreTrainedModel:()=>s.OPTPreTrainedModel,ObjectDetectionPipeline:()=>c.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>s.Olmo2ForCausalLM,Olmo2Model:()=>s.Olmo2Model,Olmo2PreTrainedModel:()=>s.Olmo2PreTrainedModel,OlmoForCausalLM:()=>s.OlmoForCausalLM,OlmoModel:()=>s.OlmoModel,OlmoPreTrainedModel:()=>s.OlmoPreTrainedModel,OpenELMForCausalLM:()=>s.OpenELMForCausalLM,OpenELMModel:()=>s.OpenELMModel,OpenELMPreTrainedModel:()=>s.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>O.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>s.OwlViTForObjectDetection,OwlViTImageProcessor:()=>O.OwlViTImageProcessor,OwlViTModel:()=>s.OwlViTModel,OwlViTPreTrainedModel:()=>s.OwlViTPreTrainedModel,OwlViTProcessor:()=>ne.OwlViTProcessor,Owlv2ForObjectDetection:()=>s.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>O.Owlv2ImageProcessor,Owlv2Model:()=>s.Owlv2Model,Owlv2PreTrainedModel:()=>s.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>s.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>s.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ne.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>s.PatchTSMixerForPrediction,PatchTSMixerModel:()=>s.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>s.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>s.PatchTSTForPrediction,PatchTSTModel:()=>s.PatchTSTModel,PatchTSTPreTrainedModel:()=>s.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>s.Phi3ForCausalLM,Phi3Model:()=>s.Phi3Model,Phi3PreTrainedModel:()=>s.Phi3PreTrainedModel,Phi3VForCausalLM:()=>s.Phi3VForCausalLM,Phi3VImageProcessor:()=>O.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>s.Phi3VPreTrainedModel,Phi3VProcessor:()=>ne.Phi3VProcessor,PhiForCausalLM:()=>s.PhiForCausalLM,PhiModel:()=>s.PhiModel,PhiPreTrainedModel:()=>s.PhiPreTrainedModel,Pipeline:()=>c.Pipeline,PreTrainedModel:()=>s.PreTrainedModel,PreTrainedTokenizer:()=>h.PreTrainedTokenizer,PretrainedConfig:()=>T.PretrainedConfig,PretrainedMixin:()=>s.PretrainedMixin,Processor:()=>re.Processor,PvtForImageClassification:()=>s.PvtForImageClassification,PvtImageProcessor:()=>O.PvtImageProcessor,PvtModel:()=>s.PvtModel,PvtPreTrainedModel:()=>s.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>w.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>s.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>s.PyAnnoteModel,PyAnnotePreTrainedModel:()=>s.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ne.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>s.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>c.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>s.Qwen2ForCausalLM,Qwen2Model:()=>s.Qwen2Model,Qwen2PreTrainedModel:()=>s.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>h.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>s.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>O.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>s.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ne.Qwen2VLProcessor,RTDetrForObjectDetection:()=>s.RTDetrForObjectDetection,RTDetrImageProcessor:()=>O.RTDetrImageProcessor,RTDetrModel:()=>s.RTDetrModel,RTDetrObjectDetectionOutput:()=>s.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>s.RTDetrPreTrainedModel,RawAudio:()=>I.RawAudio,RawImage:()=>U.RawImage,RepetitionPenaltyLogitsProcessor:()=>D.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>s.ResNetForImageClassification,ResNetModel:()=>s.ResNetModel,ResNetPreTrainedModel:()=>s.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>s.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>s.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>s.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>s.RoFormerForTokenClassification,RoFormerModel:()=>s.RoFormerModel,RoFormerPreTrainedModel:()=>s.RoFormerPreTrainedModel,RoFormerTokenizer:()=>h.RoFormerTokenizer,RobertaForMaskedLM:()=>s.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>s.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>s.RobertaForSequenceClassification,RobertaForTokenClassification:()=>s.RobertaForTokenClassification,RobertaModel:()=>s.RobertaModel,RobertaPreTrainedModel:()=>s.RobertaPreTrainedModel,RobertaTokenizer:()=>h.RobertaTokenizer,SamImageProcessor:()=>O.SamImageProcessor,SamImageSegmentationOutput:()=>s.SamImageSegmentationOutput,SamModel:()=>s.SamModel,SamPreTrainedModel:()=>s.SamPreTrainedModel,SamProcessor:()=>ne.SamProcessor,SapiensForDepthEstimation:()=>s.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>s.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>s.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>s.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>w.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>O.SegformerFeatureExtractor,SegformerForImageClassification:()=>s.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>s.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>O.SegformerImageProcessor,SegformerModel:()=>s.SegformerModel,SegformerPreTrainedModel:()=>s.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>s.Seq2SeqLMOutput,SequenceClassifierOutput:()=>s.SequenceClassifierOutput,SiglipImageProcessor:()=>O.SiglipImageProcessor,SiglipModel:()=>s.SiglipModel,SiglipPreTrainedModel:()=>s.SiglipPreTrainedModel,SiglipTextModel:()=>s.SiglipTextModel,SiglipTokenizer:()=>h.SiglipTokenizer,SiglipVisionModel:()=>s.SiglipVisionModel,SpeechT5FeatureExtractor:()=>w.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>s.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>s.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>s.SpeechT5HifiGan,SpeechT5Model:()=>s.SpeechT5Model,SpeechT5PreTrainedModel:()=>s.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ne.SpeechT5Processor,SpeechT5Tokenizer:()=>h.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>s.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>s.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>s.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>s.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>s.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>h.SqueezeBertTokenizer,StableLmForCausalLM:()=>s.StableLmForCausalLM,StableLmModel:()=>s.StableLmModel,StableLmPreTrainedModel:()=>s.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>s.Starcoder2ForCausalLM,Starcoder2Model:()=>s.Starcoder2Model,Starcoder2PreTrainedModel:()=>s.Starcoder2PreTrainedModel,StoppingCriteria:()=>X.StoppingCriteria,StoppingCriteriaList:()=>X.StoppingCriteriaList,StyleTextToSpeech2Model:()=>s.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>s.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>c.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>D.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>s.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>O.Swin2SRImageProcessor,Swin2SRModel:()=>s.Swin2SRModel,Swin2SRPreTrainedModel:()=>s.Swin2SRPreTrainedModel,SwinForImageClassification:()=>s.SwinForImageClassification,SwinModel:()=>s.SwinModel,SwinPreTrainedModel:()=>s.SwinPreTrainedModel,T5ForConditionalGeneration:()=>s.T5ForConditionalGeneration,T5Model:()=>s.T5Model,T5PreTrainedModel:()=>s.T5PreTrainedModel,T5Tokenizer:()=>h.T5Tokenizer,TableTransformerForObjectDetection:()=>s.TableTransformerForObjectDetection,TableTransformerModel:()=>s.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>s.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>s.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>D.TemperatureLogitsWarper,Tensor:()=>F.Tensor,Text2TextGenerationPipeline:()=>c.Text2TextGenerationPipeline,TextClassificationPipeline:()=>c.TextClassificationPipeline,TextGenerationPipeline:()=>c.TextGenerationPipeline,TextStreamer:()=>W.TextStreamer,TextToAudioPipeline:()=>c.TextToAudioPipeline,TokenClassificationPipeline:()=>c.TokenClassificationPipeline,TokenClassifierOutput:()=>s.TokenClassifierOutput,TokenizerModel:()=>h.TokenizerModel,TopKLogitsWarper:()=>D.TopKLogitsWarper,TopPLogitsWarper:()=>D.TopPLogitsWarper,TrOCRForCausalLM:()=>s.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>s.TrOCRPreTrainedModel,TranslationPipeline:()=>c.TranslationPipeline,UniSpeechForCTC:()=>s.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>s.UniSpeechForSequenceClassification,UniSpeechModel:()=>s.UniSpeechModel,UniSpeechPreTrainedModel:()=>s.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>s.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>s.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>s.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>s.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>s.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ne.VLChatProcessor,VLMImageProcessor:()=>O.VLMImageProcessor,ViTFeatureExtractor:()=>O.ViTFeatureExtractor,ViTForImageClassification:()=>s.ViTForImageClassification,ViTImageProcessor:()=>O.ViTImageProcessor,ViTMAEModel:()=>s.ViTMAEModel,ViTMAEPreTrainedModel:()=>s.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>s.ViTMSNForImageClassification,ViTMSNModel:()=>s.ViTMSNModel,ViTMSNPreTrainedModel:()=>s.ViTMSNPreTrainedModel,ViTModel:()=>s.ViTModel,ViTPreTrainedModel:()=>s.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>s.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>s.VitMatteForImageMatting,VitMatteImageProcessor:()=>O.VitMatteImageProcessor,VitMattePreTrainedModel:()=>s.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>s.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>O.VitPoseImageProcessor,VitPosePreTrainedModel:()=>s.VitPosePreTrainedModel,VitsModel:()=>s.VitsModel,VitsModelOutput:()=>s.VitsModelOutput,VitsPreTrainedModel:()=>s.VitsPreTrainedModel,VitsTokenizer:()=>h.VitsTokenizer,Wav2Vec2BertForCTC:()=>s.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>s.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>s.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>s.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>h.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>w.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>s.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>s.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>s.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>s.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>s.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>ne.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>ne.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>s.WavLMForAudioFrameClassification,WavLMForCTC:()=>s.WavLMForCTC,WavLMForSequenceClassification:()=>s.WavLMForSequenceClassification,WavLMForXVector:()=>s.WavLMForXVector,WavLMModel:()=>s.WavLMModel,WavLMPreTrainedModel:()=>s.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>w.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>s.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>s.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>w.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>s.WhisperForConditionalGeneration,WhisperModel:()=>s.WhisperModel,WhisperPreTrainedModel:()=>s.WhisperPreTrainedModel,WhisperProcessor:()=>ne.WhisperProcessor,WhisperTextStreamer:()=>W.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>D.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>h.WhisperTokenizer,XLMForQuestionAnswering:()=>s.XLMForQuestionAnswering,XLMForSequenceClassification:()=>s.XLMForSequenceClassification,XLMForTokenClassification:()=>s.XLMForTokenClassification,XLMModel:()=>s.XLMModel,XLMPreTrainedModel:()=>s.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>s.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>s.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>s.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>s.XLMRobertaForTokenClassification,XLMRobertaModel:()=>s.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>s.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>h.XLMRobertaTokenizer,XLMTokenizer:()=>h.XLMTokenizer,XLMWithLMHeadModel:()=>s.XLMWithLMHeadModel,XVectorOutput:()=>s.XVectorOutput,YolosFeatureExtractor:()=>O.YolosFeatureExtractor,YolosForObjectDetection:()=>s.YolosForObjectDetection,YolosImageProcessor:()=>O.YolosImageProcessor,YolosModel:()=>s.YolosModel,YolosObjectDetectionOutput:()=>s.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>s.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>c.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>c.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>c.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>c.ZeroShotObjectDetectionPipeline,bankers_round:()=>_.bankers_round,cat:()=>F.cat,cos_sim:()=>_.cos_sim,dot:()=>_.dot,dynamic_time_warping:()=>_.dynamic_time_warping,env:()=>R.env,full:()=>F.full,full_like:()=>F.full_like,getKeyValueShapes:()=>T.getKeyValueShapes,hamming:()=>I.hamming,hanning:()=>I.hanning,interpolate:()=>F.interpolate,interpolate_4d:()=>F.interpolate_4d,interpolate_data:()=>_.interpolate_data,is_chinese_char:()=>h.is_chinese_char,layer_norm:()=>F.layer_norm,load_image:()=>U.load_image,log_softmax:()=>_.log_softmax,magnitude:()=>_.magnitude,matmul:()=>F.matmul,max:()=>_.max,mean:()=>F.mean,mean_pooling:()=>F.mean_pooling,medianFilter:()=>_.medianFilter,mel_filter_bank:()=>I.mel_filter_bank,min:()=>_.min,ones:()=>F.ones,ones_like:()=>F.ones_like,permute:()=>F.permute,permute_data:()=>_.permute_data,pipeline:()=>c.pipeline,quantize_embeddings:()=>F.quantize_embeddings,rand:()=>F.rand,read_audio:()=>I.read_audio,rfft:()=>F.rfft,round:()=>_.round,slice:()=>F.slice,softmax:()=>_.softmax,spectrogram:()=>I.spectrogram,stack:()=>F.stack,std_mean:()=>F.std_mean,topk:()=>F.topk,window_function:()=>I.window_function,zeros:()=>F.zeros,zeros_like:()=>F.zeros_like});var R=bs("./src/env.js"),c=bs("./src/pipelines.js"),s=bs("./src/models.js"),h=bs("./src/tokenizers.js"),T=bs("./src/configs.js"),I=bs("./src/utils/audio.js"),U=bs("./src/utils/image.js"),F=bs("./src/utils/tensor.js"),_=bs("./src/utils/maths.js"),v=bs("./src/base/feature_extraction_utils.js"),w=bs("./src/models/feature_extractors.js"),b=bs("./src/models/auto/feature_extraction_auto.js"),x=bs("./src/base/image_processors_utils.js"),O=bs("./src/models/image_processors.js"),H=bs("./src/models/auto/image_processing_auto.js"),re=bs("./src/base/processing_utils.js"),ne=bs("./src/models/processors.js"),G=bs("./src/models/auto/processing_auto.js"),W=bs("./src/generation/streamers.js"),X=bs("./src/generation/stopping_criteria.js"),D=bs("./src/generation/logits_process.js")})();p.ASTFeatureExtractor;p.ASTForAudioClassification;p.ASTModel;p.ASTPreTrainedModel;p.AlbertForMaskedLM;p.AlbertForQuestionAnswering;p.AlbertForSequenceClassification;p.AlbertModel;p.AlbertPreTrainedModel;p.AlbertTokenizer;p.AudioClassificationPipeline;p.AutoConfig;p.AutoFeatureExtractor;p.AutoImageProcessor;p.AutoModel;p.AutoModelForAudioClassification;p.AutoModelForAudioFrameClassification;p.AutoModelForCTC;p.AutoModelForCausalLM;p.AutoModelForDepthEstimation;p.AutoModelForDocumentQuestionAnswering;p.AutoModelForImageClassification;p.AutoModelForImageFeatureExtraction;p.AutoModelForImageMatting;p.AutoModelForImageSegmentation;p.AutoModelForImageToImage;p.AutoModelForMaskGeneration;p.AutoModelForMaskedLM;p.AutoModelForNormalEstimation;p.AutoModelForObjectDetection;p.AutoModelForPoseEstimation;p.AutoModelForQuestionAnswering;p.AutoModelForSemanticSegmentation;p.AutoModelForSeq2SeqLM;p.AutoModelForSequenceClassification;p.AutoModelForSpeechSeq2Seq;p.AutoModelForTextToSpectrogram;p.AutoModelForTextToWaveform;p.AutoModelForTokenClassification;p.AutoModelForUniversalSegmentation;p.AutoModelForVision2Seq;p.AutoModelForXVector;p.AutoModelForZeroShotObjectDetection;p.AutoProcessor;var zg=p.AutoTokenizer;p.AutomaticSpeechRecognitionPipeline;p.BartForConditionalGeneration;p.BartForSequenceClassification;p.BartModel;p.BartPretrainedModel;p.BartTokenizer;p.BaseModelOutput;p.BaseStreamer;p.BeitFeatureExtractor;p.BeitForImageClassification;p.BeitModel;p.BeitPreTrainedModel;p.BertForMaskedLM;p.BertForQuestionAnswering;p.BertForSequenceClassification;p.BertForTokenClassification;p.BertModel;p.BertPreTrainedModel;p.BertTokenizer;p.BitImageProcessor;p.BlenderbotForConditionalGeneration;p.BlenderbotModel;p.BlenderbotPreTrainedModel;p.BlenderbotSmallForConditionalGeneration;p.BlenderbotSmallModel;p.BlenderbotSmallPreTrainedModel;p.BlenderbotSmallTokenizer;p.BlenderbotTokenizer;p.BloomForCausalLM;p.BloomModel;p.BloomPreTrainedModel;p.BloomTokenizer;p.CLIPFeatureExtractor;p.CLIPImageProcessor;p.CLIPModel;p.CLIPPreTrainedModel;p.CLIPSegForImageSegmentation;p.CLIPSegModel;p.CLIPSegPreTrainedModel;p.CLIPTextModel;p.CLIPTextModelWithProjection;p.CLIPTokenizer;p.CLIPVisionModel;p.CLIPVisionModelWithProjection;p.CamembertForMaskedLM;p.CamembertForQuestionAnswering;p.CamembertForSequenceClassification;p.CamembertForTokenClassification;p.CamembertModel;p.CamembertPreTrainedModel;p.CamembertTokenizer;p.CausalLMOutput;p.CausalLMOutputWithPast;p.ChineseCLIPFeatureExtractor;p.ChineseCLIPModel;p.ChineseCLIPPreTrainedModel;p.ClapAudioModelWithProjection;p.ClapFeatureExtractor;p.ClapModel;p.ClapPreTrainedModel;p.ClapTextModelWithProjection;p.ClassifierFreeGuidanceLogitsProcessor;p.CodeGenForCausalLM;p.CodeGenModel;p.CodeGenPreTrainedModel;p.CodeGenTokenizer;p.CodeLlamaTokenizer;p.CohereForCausalLM;p.CohereModel;p.CoherePreTrainedModel;p.CohereTokenizer;p.ConvBertForMaskedLM;p.ConvBertForQuestionAnswering;p.ConvBertForSequenceClassification;p.ConvBertForTokenClassification;p.ConvBertModel;p.ConvBertPreTrainedModel;p.ConvBertTokenizer;p.ConvNextFeatureExtractor;p.ConvNextForImageClassification;p.ConvNextImageProcessor;p.ConvNextModel;p.ConvNextPreTrainedModel;p.ConvNextV2ForImageClassification;p.ConvNextV2Model;p.ConvNextV2PreTrainedModel;p.DPTFeatureExtractor;p.DPTForDepthEstimation;p.DPTImageProcessor;p.DPTModel;p.DPTPreTrainedModel;p.DebertaForMaskedLM;p.DebertaForQuestionAnswering;p.DebertaForSequenceClassification;p.DebertaForTokenClassification;p.DebertaModel;p.DebertaPreTrainedModel;p.DebertaTokenizer;p.DebertaV2ForMaskedLM;p.DebertaV2ForQuestionAnswering;p.DebertaV2ForSequenceClassification;p.DebertaV2ForTokenClassification;p.DebertaV2Model;p.DebertaV2PreTrainedModel;p.DebertaV2Tokenizer;p.DecisionTransformerModel;p.DecisionTransformerPreTrainedModel;p.DeiTFeatureExtractor;p.DeiTForImageClassification;p.DeiTImageProcessor;p.DeiTModel;p.DeiTPreTrainedModel;p.DepthAnythingForDepthEstimation;p.DepthAnythingPreTrainedModel;p.DepthEstimationPipeline;p.DepthProForDepthEstimation;p.DepthProPreTrainedModel;p.DetrFeatureExtractor;p.DetrForObjectDetection;p.DetrForSegmentation;p.DetrImageProcessor;p.DetrModel;p.DetrObjectDetectionOutput;p.DetrPreTrainedModel;p.DetrSegmentationOutput;p.Dinov2ForImageClassification;p.Dinov2Model;p.Dinov2PreTrainedModel;p.Dinov2WithRegistersForImageClassification;p.Dinov2WithRegistersModel;p.Dinov2WithRegistersPreTrainedModel;p.DistilBertForMaskedLM;p.DistilBertForQuestionAnswering;p.DistilBertForSequenceClassification;p.DistilBertForTokenClassification;p.DistilBertModel;p.DistilBertPreTrainedModel;p.DistilBertTokenizer;p.DocumentQuestionAnsweringPipeline;p.DonutFeatureExtractor;p.DonutImageProcessor;p.DonutSwinModel;p.DonutSwinPreTrainedModel;p.EfficientNetForImageClassification;p.EfficientNetImageProcessor;p.EfficientNetModel;p.EfficientNetPreTrainedModel;p.ElectraForMaskedLM;p.ElectraForQuestionAnswering;p.ElectraForSequenceClassification;p.ElectraForTokenClassification;p.ElectraModel;p.ElectraPreTrainedModel;p.ElectraTokenizer;p.EosTokenCriteria;p.EsmForMaskedLM;p.EsmForSequenceClassification;p.EsmForTokenClassification;p.EsmModel;p.EsmPreTrainedModel;p.EsmTokenizer;p.ExaoneForCausalLM;p.ExaoneModel;p.ExaonePreTrainedModel;p.FFT;p.FalconForCausalLM;p.FalconModel;p.FalconPreTrainedModel;p.FalconTokenizer;p.FastViTForImageClassification;p.FastViTModel;p.FastViTPreTrainedModel;p.FeatureExtractionPipeline;p.FeatureExtractor;p.FillMaskPipeline;p.Florence2ForConditionalGeneration;p.Florence2PreTrainedModel;p.Florence2Processor;p.ForcedBOSTokenLogitsProcessor;p.ForcedEOSTokenLogitsProcessor;p.GLPNFeatureExtractor;p.GLPNForDepthEstimation;p.GLPNModel;p.GLPNPreTrainedModel;p.GPT2LMHeadModel;p.GPT2Model;p.GPT2PreTrainedModel;p.GPT2Tokenizer;p.GPTBigCodeForCausalLM;p.GPTBigCodeModel;p.GPTBigCodePreTrainedModel;p.GPTJForCausalLM;p.GPTJModel;p.GPTJPreTrainedModel;p.GPTNeoForCausalLM;p.GPTNeoModel;p.GPTNeoPreTrainedModel;p.GPTNeoXForCausalLM;p.GPTNeoXModel;p.GPTNeoXPreTrainedModel;p.GPTNeoXTokenizer;p.Gemma2ForCausalLM;p.Gemma2Model;p.Gemma2PreTrainedModel;p.GemmaForCausalLM;p.GemmaModel;p.GemmaPreTrainedModel;p.GemmaTokenizer;p.GlmForCausalLM;p.GlmModel;p.GlmPreTrainedModel;p.GraniteForCausalLM;p.GraniteModel;p.GranitePreTrainedModel;p.Grok1Tokenizer;p.GroundingDinoForObjectDetection;p.GroundingDinoImageProcessor;p.GroundingDinoPreTrainedModel;p.GroundingDinoProcessor;p.GroupViTModel;p.GroupViTPreTrainedModel;p.HeliumForCausalLM;p.HeliumModel;p.HeliumPreTrainedModel;p.HerbertTokenizer;p.HieraForImageClassification;p.HieraModel;p.HieraPreTrainedModel;p.HubertForCTC;p.HubertForSequenceClassification;p.HubertModel;p.HubertPreTrainedModel;p.IJepaForImageClassification;p.IJepaModel;p.IJepaPreTrainedModel;p.Idefics3ForConditionalGeneration;p.Idefics3ImageProcessor;p.Idefics3PreTrainedModel;p.Idefics3Processor;p.ImageClassificationPipeline;p.ImageFeatureExtractionPipeline;p.ImageFeatureExtractor;p.ImageMattingOutput;p.ImageProcessor;p.ImageSegmentationPipeline;p.ImageToImagePipeline;p.ImageToTextPipeline;p.InterruptableStoppingCriteria;p.JAISLMHeadModel;p.JAISModel;p.JAISPreTrainedModel;p.JinaCLIPImageProcessor;p.JinaCLIPModel;p.JinaCLIPPreTrainedModel;p.JinaCLIPProcessor;p.JinaCLIPTextModel;p.JinaCLIPVisionModel;p.LlamaForCausalLM;p.LlamaModel;p.LlamaPreTrainedModel;p.LlamaTokenizer;p.LlavaForConditionalGeneration;p.LlavaOnevisionForConditionalGeneration;p.LlavaOnevisionImageProcessor;p.LlavaPreTrainedModel;p.LogitsProcessor;p.LogitsProcessorList;p.LogitsWarper;p.LongT5ForConditionalGeneration;p.LongT5Model;p.LongT5PreTrainedModel;p.M2M100ForConditionalGeneration;p.M2M100Model;p.M2M100PreTrainedModel;p.M2M100Tokenizer;p.MBart50Tokenizer;p.MBartForCausalLM;p.MBartForConditionalGeneration;p.MBartForSequenceClassification;p.MBartModel;p.MBartPreTrainedModel;p.MBartTokenizer;p.MPNetForMaskedLM;p.MPNetForQuestionAnswering;p.MPNetForSequenceClassification;p.MPNetForTokenClassification;p.MPNetModel;p.MPNetPreTrainedModel;p.MPNetTokenizer;p.MT5ForConditionalGeneration;p.MT5Model;p.MT5PreTrainedModel;p.MarianMTModel;p.MarianModel;p.MarianPreTrainedModel;p.MarianTokenizer;p.Mask2FormerImageProcessor;p.MaskFormerFeatureExtractor;p.MaskFormerForInstanceSegmentation;p.MaskFormerImageProcessor;p.MaskFormerModel;p.MaskFormerPreTrainedModel;p.MaskedLMOutput;p.MaxLengthCriteria;p.MgpstrForSceneTextRecognition;p.MgpstrModelOutput;p.MgpstrPreTrainedModel;p.MgpstrProcessor;p.MgpstrTokenizer;p.MinLengthLogitsProcessor;p.MinNewTokensLengthLogitsProcessor;p.MistralForCausalLM;p.MistralModel;p.MistralPreTrainedModel;p.MobileBertForMaskedLM;p.MobileBertForQuestionAnswering;p.MobileBertForSequenceClassification;p.MobileBertModel;p.MobileBertPreTrainedModel;p.MobileBertTokenizer;p.MobileLLMForCausalLM;p.MobileLLMModel;p.MobileLLMPreTrainedModel;p.MobileNetV1FeatureExtractor;p.MobileNetV1ForImageClassification;p.MobileNetV1ImageProcessor;p.MobileNetV1Model;p.MobileNetV1PreTrainedModel;p.MobileNetV2FeatureExtractor;p.MobileNetV2ForImageClassification;p.MobileNetV2ImageProcessor;p.MobileNetV2Model;p.MobileNetV2PreTrainedModel;p.MobileNetV3FeatureExtractor;p.MobileNetV3ForImageClassification;p.MobileNetV3ImageProcessor;p.MobileNetV3Model;p.MobileNetV3PreTrainedModel;p.MobileNetV4FeatureExtractor;p.MobileNetV4ForImageClassification;p.MobileNetV4ImageProcessor;p.MobileNetV4Model;p.MobileNetV4PreTrainedModel;p.MobileViTFeatureExtractor;p.MobileViTForImageClassification;p.MobileViTImageProcessor;p.MobileViTModel;p.MobileViTPreTrainedModel;p.MobileViTV2ForImageClassification;p.MobileViTV2Model;p.MobileViTV2PreTrainedModel;p.ModelOutput;p.ModernBertForMaskedLM;p.ModernBertForSequenceClassification;p.ModernBertForTokenClassification;p.ModernBertModel;p.ModernBertPreTrainedModel;p.Moondream1ForConditionalGeneration;p.MoonshineFeatureExtractor;p.MoonshineForConditionalGeneration;p.MoonshineModel;p.MoonshinePreTrainedModel;p.MoonshineProcessor;p.MptForCausalLM;p.MptModel;p.MptPreTrainedModel;p.MultiModalityCausalLM;p.MultiModalityPreTrainedModel;p.MusicgenForCausalLM;p.MusicgenForConditionalGeneration;p.MusicgenModel;p.MusicgenPreTrainedModel;p.NllbTokenizer;p.NoBadWordsLogitsProcessor;p.NoRepeatNGramLogitsProcessor;p.NomicBertModel;p.NomicBertPreTrainedModel;p.NougatImageProcessor;p.NougatTokenizer;p.OPTForCausalLM;p.OPTModel;p.OPTPreTrainedModel;p.ObjectDetectionPipeline;p.Olmo2ForCausalLM;p.Olmo2Model;p.Olmo2PreTrainedModel;p.OlmoForCausalLM;p.OlmoModel;p.OlmoPreTrainedModel;p.OpenELMForCausalLM;p.OpenELMModel;p.OpenELMPreTrainedModel;p.OwlViTFeatureExtractor;p.OwlViTForObjectDetection;p.OwlViTImageProcessor;p.OwlViTModel;p.OwlViTPreTrainedModel;p.OwlViTProcessor;p.Owlv2ForObjectDetection;p.Owlv2ImageProcessor;p.Owlv2Model;p.Owlv2PreTrainedModel;p.PaliGemmaForConditionalGeneration;p.PaliGemmaPreTrainedModel;p.PaliGemmaProcessor;p.PatchTSMixerForPrediction;p.PatchTSMixerModel;p.PatchTSMixerPreTrainedModel;p.PatchTSTForPrediction;p.PatchTSTModel;p.PatchTSTPreTrainedModel;p.Phi3ForCausalLM;p.Phi3Model;p.Phi3PreTrainedModel;p.Phi3VForCausalLM;p.Phi3VImageProcessor;p.Phi3VPreTrainedModel;p.Phi3VProcessor;p.PhiForCausalLM;p.PhiModel;p.PhiPreTrainedModel;p.Pipeline;p.PreTrainedModel;p.PreTrainedTokenizer;p.PretrainedConfig;p.PretrainedMixin;p.Processor;p.PvtForImageClassification;p.PvtImageProcessor;p.PvtModel;p.PvtPreTrainedModel;p.PyAnnoteFeatureExtractor;p.PyAnnoteForAudioFrameClassification;p.PyAnnoteModel;p.PyAnnotePreTrainedModel;p.PyAnnoteProcessor;p.QuestionAnsweringModelOutput;p.QuestionAnsweringPipeline;p.Qwen2ForCausalLM;p.Qwen2Model;p.Qwen2PreTrainedModel;p.Qwen2Tokenizer;p.Qwen2VLForConditionalGeneration;p.Qwen2VLImageProcessor;p.Qwen2VLPreTrainedModel;p.Qwen2VLProcessor;p.RTDetrForObjectDetection;p.RTDetrImageProcessor;p.RTDetrModel;p.RTDetrObjectDetectionOutput;p.RTDetrPreTrainedModel;p.RawAudio;p.RawImage;p.RepetitionPenaltyLogitsProcessor;p.ResNetForImageClassification;p.ResNetModel;p.ResNetPreTrainedModel;p.RoFormerForMaskedLM;p.RoFormerForQuestionAnswering;p.RoFormerForSequenceClassification;p.RoFormerForTokenClassification;p.RoFormerModel;p.RoFormerPreTrainedModel;p.RoFormerTokenizer;p.RobertaForMaskedLM;p.RobertaForQuestionAnswering;p.RobertaForSequenceClassification;p.RobertaForTokenClassification;p.RobertaModel;p.RobertaPreTrainedModel;p.RobertaTokenizer;p.SamImageProcessor;p.SamImageSegmentationOutput;p.SamModel;p.SamPreTrainedModel;p.SamProcessor;p.SapiensForDepthEstimation;p.SapiensForNormalEstimation;p.SapiensForSemanticSegmentation;p.SapiensPreTrainedModel;p.SeamlessM4TFeatureExtractor;p.SegformerFeatureExtractor;p.SegformerForImageClassification;p.SegformerForSemanticSegmentation;p.SegformerImageProcessor;p.SegformerModel;p.SegformerPreTrainedModel;p.Seq2SeqLMOutput;p.SequenceClassifierOutput;p.SiglipImageProcessor;p.SiglipModel;p.SiglipPreTrainedModel;p.SiglipTextModel;p.SiglipTokenizer;p.SiglipVisionModel;p.SpeechT5FeatureExtractor;p.SpeechT5ForSpeechToText;p.SpeechT5ForTextToSpeech;p.SpeechT5HifiGan;p.SpeechT5Model;p.SpeechT5PreTrainedModel;p.SpeechT5Processor;p.SpeechT5Tokenizer;p.SqueezeBertForMaskedLM;p.SqueezeBertForQuestionAnswering;p.SqueezeBertForSequenceClassification;p.SqueezeBertModel;p.SqueezeBertPreTrainedModel;p.SqueezeBertTokenizer;p.StableLmForCausalLM;p.StableLmModel;p.StableLmPreTrainedModel;p.Starcoder2ForCausalLM;p.Starcoder2Model;p.Starcoder2PreTrainedModel;p.StoppingCriteria;p.StoppingCriteriaList;p.StyleTextToSpeech2Model;p.StyleTextToSpeech2PreTrainedModel;p.SummarizationPipeline;p.SuppressTokensAtBeginLogitsProcessor;p.Swin2SRForImageSuperResolution;p.Swin2SRImageProcessor;p.Swin2SRModel;p.Swin2SRPreTrainedModel;p.SwinForImageClassification;p.SwinModel;p.SwinPreTrainedModel;p.T5ForConditionalGeneration;p.T5Model;p.T5PreTrainedModel;p.T5Tokenizer;p.TableTransformerForObjectDetection;p.TableTransformerModel;p.TableTransformerObjectDetectionOutput;p.TableTransformerPreTrainedModel;p.TemperatureLogitsWarper;p.Tensor;p.Text2TextGenerationPipeline;p.TextClassificationPipeline;p.TextGenerationPipeline;p.TextStreamer;p.TextToAudioPipeline;p.TokenClassificationPipeline;p.TokenClassifierOutput;p.TokenizerModel;p.TopKLogitsWarper;p.TopPLogitsWarper;p.TrOCRForCausalLM;p.TrOCRPreTrainedModel;p.TranslationPipeline;p.UniSpeechForCTC;p.UniSpeechForSequenceClassification;p.UniSpeechModel;p.UniSpeechPreTrainedModel;p.UniSpeechSatForAudioFrameClassification;p.UniSpeechSatForCTC;p.UniSpeechSatForSequenceClassification;p.UniSpeechSatModel;p.UniSpeechSatPreTrainedModel;p.VLChatProcessor;p.VLMImageProcessor;p.ViTFeatureExtractor;p.ViTForImageClassification;p.ViTImageProcessor;p.ViTMAEModel;p.ViTMAEPreTrainedModel;p.ViTMSNForImageClassification;p.ViTMSNModel;p.ViTMSNPreTrainedModel;p.ViTModel;p.ViTPreTrainedModel;p.VisionEncoderDecoderModel;p.VitMatteForImageMatting;p.VitMatteImageProcessor;p.VitMattePreTrainedModel;p.VitPoseForPoseEstimation;p.VitPoseImageProcessor;p.VitPosePreTrainedModel;p.VitsModel;p.VitsModelOutput;p.VitsPreTrainedModel;p.VitsTokenizer;p.Wav2Vec2BertForCTC;p.Wav2Vec2BertForSequenceClassification;p.Wav2Vec2BertModel;p.Wav2Vec2BertPreTrainedModel;p.Wav2Vec2CTCTokenizer;p.Wav2Vec2FeatureExtractor;p.Wav2Vec2ForAudioFrameClassification;p.Wav2Vec2ForCTC;p.Wav2Vec2ForSequenceClassification;p.Wav2Vec2Model;p.Wav2Vec2PreTrainedModel;p.Wav2Vec2Processor;p.Wav2Vec2ProcessorWithLM;p.WavLMForAudioFrameClassification;p.WavLMForCTC;p.WavLMForSequenceClassification;p.WavLMForXVector;p.WavLMModel;p.WavLMPreTrainedModel;p.WeSpeakerFeatureExtractor;p.WeSpeakerResNetModel;p.WeSpeakerResNetPreTrainedModel;p.WhisperFeatureExtractor;p.WhisperForConditionalGeneration;p.WhisperModel;p.WhisperPreTrainedModel;p.WhisperProcessor;p.WhisperTextStreamer;p.WhisperTimeStampLogitsProcessor;p.WhisperTokenizer;p.XLMForQuestionAnswering;p.XLMForSequenceClassification;p.XLMForTokenClassification;p.XLMModel;p.XLMPreTrainedModel;p.XLMRobertaForMaskedLM;p.XLMRobertaForQuestionAnswering;p.XLMRobertaForSequenceClassification;p.XLMRobertaForTokenClassification;p.XLMRobertaModel;p.XLMRobertaPreTrainedModel;p.XLMRobertaTokenizer;p.XLMTokenizer;p.XLMWithLMHeadModel;p.XVectorOutput;p.YolosFeatureExtractor;p.YolosForObjectDetection;p.YolosImageProcessor;p.YolosModel;p.YolosObjectDetectionOutput;p.YolosPreTrainedModel;p.ZeroShotAudioClassificationPipeline;p.ZeroShotClassificationPipeline;p.ZeroShotImageClassificationPipeline;p.ZeroShotObjectDetectionPipeline;p.bankers_round;p.cat;p.cos_sim;p.dot;p.dynamic_time_warping;p.env;p.full;p.full_like;p.getKeyValueShapes;p.hamming;p.hanning;p.interpolate;p.interpolate_4d;p.interpolate_data;p.is_chinese_char;p.layer_norm;p.load_image;p.log_softmax;p.magnitude;p.matmul;p.max;p.mean;p.mean_pooling;p.medianFilter;p.mel_filter_bank;p.min;p.ones;p.ones_like;p.permute;p.permute_data;p.pipeline;p.quantize_embeddings;p.rand;p.read_audio;p.rfft;p.round;p.slice;p.softmax;p.spectrogram;p.stack;p.std_mean;p.topk;p.window_function;p.zeros;p.zeros_like;function Of(R,c){if(R){var s=R.props;if(s){var h=c.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),T=Object.prototype.hasOwnProperty.call(s,h)?h:c;return R.type.extends.props[c].type===Boolean&&s[T]===""?!0:s[T]}}return null}var Kc={_loadedStyleNames:new Set,getLoadedStyleNames:function(){return this._loadedStyleNames},isStyleNameLoaded:function(c){return this._loadedStyleNames.has(c)},setLoadedStyleName:function(c){this._loadedStyleNames.add(c)},deleteLoadedStyleName:function(c){this._loadedStyleNames.delete(c)},clearLoadedStyleNames:function(){this._loadedStyleNames.clear()}};function Bg(){var R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"pc",c=Mg();return"".concat(R).concat(c.replace("v-","").replaceAll("-","_"))}var Ff=vn.extend({name:"common"});function Yc(R){"@babel/helpers - typeof";return Yc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},Yc(R)}function Rg(R){return qf(R)||Ng(R)||Hf(R)||Kf()}function Ng(R){if(typeof Symbol<"u"&&R[Symbol.iterator]!=null||R["@@iterator"]!=null)return Array.from(R)}function Hc(R,c){return qf(R)||jg(R,c)||Hf(R,c)||Kf()}function Kf(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Hf(R,c){if(R){if(typeof R=="string")return Df(R,c);var s={}.toString.call(R).slice(8,-1);return s==="Object"&&R.constructor&&(s=R.constructor.name),s==="Map"||s==="Set"?Array.from(R):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?Df(R,c):void 0}}function Df(R,c){(c==null||c>R.length)&&(c=R.length);for(var s=0,h=Array(c);s1?s-1:0),T=1;T0&&arguments[0]!==void 0?arguments[0]:function(){};Kc.clearLoadedStyleNames(),Ga.on("theme:change",c)},_removeThemeListeners:function(){Ga.off("theme:change",this._loadCoreStyles),Ga.off("theme:change",this._load),Ga.off("theme:change",this._themeScopedListener)},_getHostInstance:function(c){return c?this.$options.hostName?c.$.type.name===this.$options.hostName?c:this._getHostInstance(c.$parentInstance):c.$parentInstance:void 0},_getPropValue:function(c){var s;return this[c]||((s=this._getHostInstance(this))===null||s===void 0?void 0:s[c])},_getOptionValue:function(c){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return vg(c,s,h)},_getPTValue:function(){var c,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},I=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,U=/./g.test(h)&&!!T[h.split(".")[0]],F=this._getPropValue("ptOptions")||((c=this.$primevueConfig)===null||c===void 0?void 0:c.ptOptions)||{},_=F.mergeSections,v=_===void 0?!0:_,w=F.mergeProps,b=w===void 0?!1:w,x=I?U?this._useGlobalPT(this._getPTClassValue,h,T):this._useDefaultPT(this._getPTClassValue,h,T):void 0,O=U?void 0:this._getPTSelf(s,this._getPTClassValue,h,ys(ys({},T),{},{global:x||{}})),H=this._getPTDatasets(h);return v||!v&&O?b?this._mergeProps(b,x,O,H):ys(ys(ys({},x),O),H):ys(ys({},O),H)},_getPTSelf:function(){for(var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length,h=new Array(s>1?s-1:0),T=1;T0&&arguments[0]!==void 0?arguments[0]:"",T="data-pc-",I=h==="root"&&Uh((c=this.pt)===null||c===void 0?void 0:c["data-pc-section"]);return h!=="transition"&&ys(ys({},h==="root"&&ys(ys(Qc({},"".concat(T,"name"),Gc(I?(s=this.pt)===null||s===void 0?void 0:s["data-pc-section"]:this.$.type.name)),I&&Qc({},"".concat(T,"extend"),Gc(this.$.type.name))),{},Qc({},"".concat(this.$attrSelector),""))),{},Qc({},"".concat(T,"section"),Gc(h)))},_getPTClassValue:function(){var c=this._getOptionValue.apply(this,arguments);return Nh(c)||Rf(c)?{class:c}:c},_getPT:function(c){var s=this,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",T=arguments.length>2?arguments[2]:void 0,I=function(F){var _,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,w=T?T(F):F,b=Gc(h),x=Gc(s.$name);return(_=v?b!==x?w==null?void 0:w[b]:void 0:w==null?void 0:w[b])!==null&&_!==void 0?_:w};return c!=null&&c.hasOwnProperty("_usept")?{_usept:c._usept,originalValue:I(c.originalValue),value:I(c.value)}:I(c,!0)},_usePT:function(c,s,h,T){var I=function(re){return s(re,h,T)};if(c!=null&&c.hasOwnProperty("_usept")){var U,F=c._usept||((U=this.$primevueConfig)===null||U===void 0?void 0:U.ptOptions)||{},_=F.mergeSections,v=_===void 0?!0:_,w=F.mergeProps,b=w===void 0?!1:w,x=I(c.originalValue),O=I(c.value);return x===void 0&&O===void 0?void 0:Nh(O)?O:Nh(x)?x:v||!v&&O?b?this._mergeProps(b,x,O):ys(ys({},x),O):O}return I(c)},_useGlobalPT:function(c,s,h){return this._usePT(this.globalPT,c,s,h)},_useDefaultPT:function(c,s,h){return this._usePT(this.defaultPT,c,s,h)},ptm:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this._getPTValue(this.pt,c,ys(ys({},this.$params),s))},ptmi:function(){var c,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},T=qi(this.$_attrsWithoutPT,this.ptm(s,h));return T!=null&&T.hasOwnProperty("id")&&((c=T.id)!==null&&c!==void 0||(T.id=this.$id)),T},ptmo:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._getPTValue(c,s,ys({instance:this},h),!1)},cx:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.isUnstyled?void 0:this._getOptionValue(this.$style.classes,c,ys(ys({},this.$params),s))},sx:function(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s){var T=this._getOptionValue(this.$style.inlineStyles,c,ys(ys({},this.$params),h)),I=this._getOptionValue(Ff.inlineStyles,c,ys(ys({},this.$params),h));return[I,T]}}},computed:{globalPT:function(){var c,s=this;return this._getPT((c=this.$primevueConfig)===null||c===void 0?void 0:c.pt,void 0,function(h){return $f(h,{instance:s})})},defaultPT:function(){var c,s=this;return this._getPT((c=this.$primevueConfig)===null||c===void 0?void 0:c.pt,void 0,function(h){return s._getOptionValue(h,s.$name,ys({},s.$params))||$f(h,ys({},s.$params))})},isUnstyled:function(){var c;return this.unstyled!==void 0?this.unstyled:(c=this.$primevueConfig)===null||c===void 0?void 0:c.unstyled},$id:function(){return this.$attrs.id||this.uid},$inProps:function(){var c,s=Object.keys(((c=this.$.vnode)===null||c===void 0?void 0:c.props)||{});return Object.fromEntries(Object.entries(this.$props).filter(function(h){var T=Hc(h,1),I=T[0];return s==null?void 0:s.includes(I)}))},$theme:function(){var c;return(c=this.$primevueConfig)===null||c===void 0?void 0:c.theme},$style:function(){return ys(ys({classes:void 0,inlineStyles:void 0,load:function(){},loadCSS:function(){},loadStyle:function(){}},(this._getHostInstance(this)||{}).$style),this.$options.style)},$styleOptions:function(){var c;return{nonce:(c=this.$primevueConfig)===null||c===void 0||(c=c.csp)===null||c===void 0?void 0:c.nonce}},$primevueConfig:function(){var c;return(c=this.$primevue)===null||c===void 0?void 0:c.config},$name:function(){return this.$options.hostName||this.$.type.name},$params:function(){var c=this._getHostInstance(this)||this.$parent;return{instance:this,props:this.$props,state:this.$data,attrs:this.$attrs,parent:{instance:c,props:c==null?void 0:c.$props,state:c==null?void 0:c.$data,attrs:c==null?void 0:c.$attrs}}},$_attrsPT:function(){return Object.entries(this.$attrs||{}).filter(function(c){var s=Hc(c,1),h=s[0];return h==null?void 0:h.startsWith("pt:")}).reduce(function(c,s){var h=Hc(s,2),T=h[0],I=h[1],U=T.split(":"),F=Rg(U),_=F.slice(1);return _==null||_.reduce(function(v,w,b,x){return!v[w]&&(v[w]=b===x.length-1?I:{}),v[w]},c),c},{})},$_attrsWithoutPT:function(){return Object.entries(this.$attrs||{}).filter(function(c){var s=Hc(c,1),h=s[0];return!(h!=null&&h.startsWith("pt:"))}).reduce(function(c,s){var h=Hc(s,2),T=h[0],I=h[1];return c[T]=I,c},{})}}},Wg=({dt:R})=>` +.p-splitter { + display: flex; + flex-wrap: nowrap; + border: 1px solid ${R("splitter.border.color")}; + background: ${R("splitter.background")}; + border-radius: ${R("border.radius.md")}; + color: ${R("splitter.color")}; +} + +.p-splitter-vertical { + flex-direction: column; +} + +.p-splitter-gutter { + flex-grow: 0; + flex-shrink: 0; + display: flex; + align-items: center; + justify-content: center; + z-index: 1; + background: ${R("splitter.gutter.background")}; +} + +.p-splitter-gutter-handle { + border-radius: ${R("splitter.handle.border.radius")}; + background: ${R("splitter.handle.background")}; + transition: outline-color ${R("splitter.transition.duration")}, box-shadow ${R("splitter.transition.duration")}; + outline-color: transparent; +} + +.p-splitter-gutter-handle:focus-visible { + box-shadow: ${R("splitter.handle.focus.ring.shadow")}; + outline: ${R("splitter.handle.focus.ring.width")} ${R("splitter.handle.focus.ring.style")} ${R("splitter.handle.focus.ring.color")}; + outline-offset: ${R("splitter.handle.focus.ring.offset")}; +} + +.p-splitter-horizontal.p-splitter-resizing { + cursor: col-resize; + user-select: none; +} + +.p-splitter-vertical.p-splitter-resizing { + cursor: row-resize; + user-select: none; +} + +.p-splitter-horizontal > .p-splitter-gutter > .p-splitter-gutter-handle { + height: ${R("splitter.handle.size")}; + width: 100%; +} + +.p-splitter-vertical > .p-splitter-gutter > .p-splitter-gutter-handle { + width: ${R("splitter.handle.size")}; + height: 100%; +} + +.p-splitter-horizontal > .p-splitter-gutter { + cursor: col-resize; +} + +.p-splitter-vertical > .p-splitter-gutter { + cursor: row-resize; +} + +.p-splitterpanel { + flex-grow: 1; + overflow: hidden; +} + +.p-splitterpanel-nested { + display: flex; +} + +.p-splitterpanel .p-splitter { + flex-grow: 1; + border: 0 none; +} +`,Gg={root:function(c){var s=c.props;return["p-splitter p-component","p-splitter-"+s.layout]},gutter:"p-splitter-gutter",gutterHandle:"p-splitter-gutter-handle"},Kg={root:function(c){var s=c.props;return[{display:"flex","flex-wrap":"nowrap"},s.layout==="vertical"?{"flex-direction":"column"}:""]}},Hg=vn.extend({name:"splitter",style:Wg,classes:Gg,inlineStyles:Kg}),qg={name:"BaseSplitter",extends:Qf,props:{layout:{type:String,default:"horizontal"},gutterSize:{type:Number,default:4},stateKey:{type:String,default:null},stateStorage:{type:String,default:"session"},step:{type:Number,default:5}},style:Hg,provide:function(){return{$pcSplitter:this,$parentInstance:this}}};function zf(R){return Jg(R)||Yg(R)||Xg(R)||Qg()}function Qg(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Xg(R,c){if(R){if(typeof R=="string")return Gh(R,c);var s={}.toString.call(R).slice(8,-1);return s==="Object"&&R.constructor&&(s=R.constructor.name),s==="Map"||s==="Set"?Array.from(R):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?Gh(R,c):void 0}}function Yg(R){if(typeof Symbol<"u"&&R[Symbol.iterator]!=null||R["@@iterator"]!=null)return Array.from(R)}function Jg(R){if(Array.isArray(R))return Gh(R)}function Gh(R,c){(c==null||c>R.length)&&(c=R.length);for(var s=0,h=Array(c);s100||c<0||s>100||s<0||this.prevPanelMinSize>c||this.nextPanelMinSize>s)},unbindMouseListeners:function(){this.mouseMoveListener&&(document.removeEventListener("mousemove",this.mouseMoveListener),this.mouseMoveListener=null),this.mouseUpListener&&(document.removeEventListener("mouseup",this.mouseUpListener),this.mouseUpListener=null)},unbindTouchListeners:function(){this.touchMoveListener&&(document.removeEventListener("touchmove",this.touchMoveListener),this.touchMoveListener=null),this.touchEndListener&&(document.removeEventListener("touchend",this.touchEndListener),this.touchEndListener=null)},clear:function(){this.dragging=!1,this.size=null,this.startPos=null,this.prevPanelElement=null,this.nextPanelElement=null,this.prevPanelSize=null,this.nextPanelSize=null,this.gutterElement=null,this.prevPanelIndex=null},isStateful:function(){return this.stateKey!=null},getStorage:function(){switch(this.stateStorage){case"local":return window.localStorage;case"session":return window.sessionStorage;default:throw new Error(this.stateStorage+' is not a valid value for the state storage, supported values are "local" and "session".')}},saveState:function(){Rf(this.panelSizes)&&this.getStorage().setItem(this.stateKey,JSON.stringify(this.panelSizes))},restoreState:function(){var c=this,s=this.getStorage(),h=s.getItem(this.stateKey);if(h){this.panelSizes=JSON.parse(h);var T=zf(this.$el.children).filter(function(I){return I.getAttribute("data-pc-name")==="splitterpanel"});return T.forEach(function(I,U){I.style.flexBasis="calc("+c.panelSizes[U]+"% - "+(c.panels.length-1)*c.gutterSize+"px)"}),!0}return!1},resetState:function(){this.initializePanels()}},computed:{panels:function(){var c=this,s=[];return this.$slots.default().forEach(function(h){c.isSplitterPanel(h)?s.push(h):h.children instanceof Array&&h.children.forEach(function(T){c.isSplitterPanel(T)&&s.push(T)})}),s},gutterStyle:function(){return this.horizontal?{width:this.gutterSize+"px"}:{height:this.gutterSize+"px"}},horizontal:function(){return this.layout==="horizontal"},getPTOptions:function(){var c;return{context:{nested:(c=this.$parentInstance)===null||c===void 0?void 0:c.nestedState}}},prevPanelMinSize:function(){var c=Of(this.panels[this.prevPanelIndex],"minSize");return this.panels[this.prevPanelIndex].props&&c?c:0},nextPanelMinSize:function(){var c=Of(this.panels[this.prevPanelIndex+1],"minSize");return this.panels[this.prevPanelIndex+1].props&&c?c:0}}},Zg=["onMousedown","onTouchstart","onTouchmove","onTouchend"],ey=["aria-orientation","aria-valuenow","onKeydown"];function ty(R,c,s,h,T,I){return Zs(),or("div",qi({class:R.cx("root"),style:R.sx("root"),"data-p-resizing":!1},R.ptmi("root",I.getPTOptions)),[(Zs(!0),or(ih,null,Hh(I.panels,function(U,F){return Zs(),or(ih,{key:F},[(Zs(),Vh($g(U),{tabindex:"-1"})),F!==I.panels.length-1?(Zs(),or("div",qi({key:0,ref_for:!0,ref:"gutter",class:R.cx("gutter"),role:"separator",tabindex:"-1",onMousedown:function(v){return I.onGutterMouseDown(v,F)},onTouchstart:function(v){return I.onGutterTouchStart(v,F)},onTouchmove:function(v){return I.onGutterTouchMove(v,F)},onTouchend:function(v){return I.onGutterTouchEnd(v,F)},"data-p-gutter-resizing":!1},R.ptm("gutter")),[Js("div",qi({class:R.cx("gutterHandle"),tabindex:"0",style:[I.gutterStyle],"aria-orientation":R.layout,"aria-valuenow":T.prevSize,onKeyup:c[0]||(c[0]=function(){return I.onGutterKeyUp&&I.onGutterKeyUp.apply(I,arguments)}),onKeydown:function(v){return I.onGutterKeyDown(v,F)},ref_for:!0},R.ptm("gutterHandle")),null,16,ey)],16,Zg)):Wh("",!0)],64)}),128))],16)}Xf.render=ty;var sy={root:function(c){var s=c.instance;return["p-splitterpanel",{"p-splitterpanel-nested":s.isNested}]}},ry=vn.extend({name:"splitterpanel",classes:sy}),ny={name:"BaseSplitterPanel",extends:Qf,props:{size:{type:Number,default:null},minSize:{type:Number,default:null}},style:ry,provide:function(){return{$pcSplitterPanel:this,$parentInstance:this}}},Kh={name:"SplitterPanel",extends:ny,inheritAttrs:!1,data:function(){return{nestedState:null}},computed:{isNested:function(){var c=this;return this.$slots.default().some(function(s){return c.nestedState=s.type.name==="Splitter"?!0:null,c.nestedState})},getPTOptions:function(){return{context:{nested:this.isNested}}}}};function iy(R,c,s,h,T,I){return Zs(),or("div",qi({ref:"container",class:R.cx("root")},R.ptmi("root",I.getPTOptions)),[kg(R.$slots,"default")],16)}Kh.render=iy;const oy={class:"relative h-full"},ay=["disabled"],ly={class:"flex items-center gap-1"},uy={class:"flex items-center gap-1"},dy={key:0,class:"flex flex-1 flex-col items-center justify-center py-8 text-gray-500 dark:text-gray-400"},cy={key:1,class:"flex flex-1 flex-col items-center justify-center py-8 text-gray-500 dark:text-gray-400"},py={key:2,class:"flex flex-1 items-center justify-center text-gray-500 dark:text-gray-400"},hy={key:3,class:"flex flex-1 items-center justify-center text-gray-500 dark:text-gray-400"},my={key:4,class:"f overflow-auto"},fy={class:"flex flex-wrap"},_y=lh({__name:"TokenizerView",props:{modelId:null},setup(R){const c=R,s=xn(""),h=xn([]),T=xn(!1),I=xn(!1);xn();let U=null;oh(()=>c.modelId,async v=>{if(v){T.value=!0,I.value=!0;try{U=await zg.from_pretrained(v),s.value&&F()}catch(w){console.error(w)}T.value=!1,I.value=!1}});function F(){if(!U||!s.value){h.value=[];return}const w=U.encode(s.value).map(b=>({id:b,text:U.decode([b])}));h.value=w}oh(s,F);const _=Ig(()=>({characters:s.value.length,tokens:h.value.length}));return(v,w)=>{const b=Lg;return Zs(),Vh(Ys(Xf),{class:"f flex gap-1 overflow-auto"},{default:jh(()=>[ah(Ys(Kh),null,{default:jh(()=>[Js("div",oy,[Nf(Js("textarea",{"onUpdate:modelValue":w[0]||(w[0]=x=>qh(s)?s.value=x:null),placeholder:"输入要分词的文本...",class:"h-full min-h-[200px] w-full resize-none overflow-y-scroll border-2 border-gray-200 rounded-lg bg-white p-4 text-gray-800 outline-none transition-colors dark:border-gray-700 focus:border-green-500 dark:bg-gray-900 dark:text-gray-200 focus:shadow-[0_0_0_2px_rgba(34,197,94,0.2)]",disabled:Ys(T)},null,8,ay),[[jf,Ys(s)]]),Js("div",{class:Ag(["absolute bottom-2 left-3 flex gap-3 rounded-sm bg-white p-2 pb-0 pl-0 text-sm text-gray-500 dark:text-gray-400",{"opacity-50":Ys(T)}])},[Js("div",ly,[w[1]||(w[1]=Js("div",{"i-carbon-text-font":"",class:"h-4 w-4"},null,-1)),kf(" "+Xc(Ys(_).characters),1)]),Js("div",uy,[w[2]||(w[2]=Js("div",{"i-carbon-code":"",class:"h-4 w-4"},null,-1)),kf(" "+Xc(Ys(_).tokens),1)])],2)])]),_:1}),ah(Ys(Kh),{class:"flex border-2 border-gray-200 rounded-lg bg-white p-4 dark:border-gray-700 dark:bg-gray-900"},{default:jh(()=>[Ys(I)?(Zs(),or("div",dy,w[3]||(w[3]=[Js("div",{class:"mb-4 h-8 w-8 animate-spin border-2 border-gray-300 border-t-green-500 rounded-full"},null,-1),Js("div",{class:"mb-2 text-base font-medium"}," 正在下载分词器... ",-1),Js("div",{class:"text-sm"}," 首次加载可能需要一些时间 ",-1)]))):Ys(T)?(Zs(),or("div",cy,w[4]||(w[4]=[Js("div",{class:"mb-4 h-8 w-8 animate-spin border-2 border-gray-300 border-t-green-500 rounded-full"},null,-1),Js("div",{class:"mb-2 text-base font-medium"}," 初始化分词器中... ",-1)]))):Ys(h).length===0&&Ys(s)?(Zs(),or("div",py," 无法分词当前文本 ")):Ys(h).length===0?(Zs(),or("div",hy," 在左侧输入文本以查看分词结果 ")):(Zs(),or("div",my,[Js("div",fy,[(Zs(!0),or(ih,null,Hh(Ys(h),(x,O)=>(Zs(),Vh(b,{id:x.id,key:O,token:x.text},null,8,["id","token"]))),128))])]))]),_:1})]),_:1})}}}),gy=Uf(_y,[["__scopeId","data-v-27bd75a7"]]);typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Bf=()=>{};function yy(R,c){function s(...h){return new Promise((T,I)=>{Promise.resolve(R(()=>c.apply(this,h),{fn:c,thisArg:this,args:h})).then(T).catch(I)})}return s}function wy(R,c={}){let s,h,T=Bf;const I=_=>{clearTimeout(_),T(),T=Bf};let U;return _=>{const v=If(R),w=If(c.maxWait);return s&&I(s),v<=0||w!==void 0&&w<=0?(h&&(I(h),h=null),Promise.resolve(_())):new Promise((b,x)=>{T=c.rejectOnCancel?x:b,U=_,w&&!h&&(h=setTimeout(()=>{s&&I(s),h=null,b(U())},w)),s=setTimeout(()=>{h&&I(h),h=null,b(_())},v)})}}function by(R,c=200,s={}){return yy(wy(c,s),R)}const My={class:"w-full"},vy={class:"relative"},xy={key:0,class:"absolute right-3 top-1/2 -translate-y-1/2"},Ty={key:0,class:"mt-2 px-2 text-sm text-gray-500 dark:text-gray-400"},Py={key:1,class:"mt-2 max-h-64 overflow-auto border border-gray-200 rounded-lg bg-white shadow-sm dark:border-gray-700 dark:bg-gray-900"},Ey=["onClick"],Cy=lh({__name:"ModelSearch",props:{modelId:null},emits:["update:model-id"],setup(R,{emit:c}){const s=R,h=c,T=xn(""),I=xn([]),U=xn(!1),F=xn(!1);async function _(b){if(!b){I.value=[];return}U.value=!0;try{const O=await(await fetch(`https://huggingface.co/api/models?search=${b}`)).json();I.value=O.map(H=>H.id)}catch(x){console.error(x),I.value=[]}U.value=!1}const v=by(_,300);oh(T,b=>{F.value||v(b),F.value=!1});function w(b){F.value=!0,T.value=b,I.value=[],h("update:model-id",b)}return oh(()=>s.modelId,b=>{b&&!T.value&&(F.value=!0,T.value=b)}),(b,x)=>(Zs(),or("div",My,[Js("div",vy,[Nf(Js("input",{"onUpdate:modelValue":x[0]||(x[0]=O=>qh(T)?T.value=O:null),type:"text",placeholder:"搜索模型...",class:"w-full border-2 border-gray-200 rounded-lg bg-white px-4 py-3 text-gray-800 outline-none transition-colors dark:border-gray-700 focus:border-green-500 dark:bg-gray-900 dark:text-gray-200"},null,512),[[jf,Ys(T)]]),Ys(U)?(Zs(),or("div",xy,x[1]||(x[1]=[Js("div",{class:"h-5 w-5 animate-spin border-2 border-gray-300 border-t-green-500 rounded-full"},null,-1)]))):Wh("",!0)]),Ys(U)&&!Ys(I).length?(Zs(),or("div",Ty," 搜索中... ")):Ys(I).length?(Zs(),or("div",Py,[(Zs(!0),or(ih,null,Hh(Ys(I),O=>(Zs(),or("div",{key:O,class:"cursor-pointer border-b border-gray-100 px-4 py-3 text-gray-800 transition-colors last:border-b-0 dark:border-gray-800 hover:bg-green-50 dark:text-gray-200 hover:text-green-700 dark:hover:bg-gray-800 dark:hover:text-green-400",onClick:H=>w(O)},Xc(O),9,Ey))),128))])):Wh("",!0)]))}}),Sy=Uf(Cy,[["__scopeId","data-v-0b7a71d0"]]),$y={class:"h-screen flex flex-col"},ky={class:"flex flex-1 flex-col gap-4 px-8 pb-8"},Oy=lh({__name:"index",setup(R){const c=xn("");return(s,h)=>{const T=Sy,I=gy;return Zs(),or("div",$y,[h[1]||(h[1]=Js("div",{class:"flex-none p-8"},[Js("h1",{class:"text-2xl font-bold"}," Tokenizer 查看器 ")],-1)),Js("div",ky,[ah(T,{"model-id":Ys(c),"onUpdate:modelId":h[0]||(h[0]=U=>qh(c)?c.value=U:null),class:"flex-none"},null,8,["model-id"]),ah(I,{"model-id":Ys(c),class:""},null,8,["model-id"])])])}}});export{Oy as default};