var Af=Object.defineProperty;var If=(or,Qr,Yn)=>Qr in or?Af(or,Qr,{enumerable:!0,configurable:!0,writable:!0,value:Yn}):or[Qr]=Yn;var ge=(or,Qr,Yn)=>If(or,typeof Qr!="symbol"?Qr+"":Qr,Yn);(function(){"use strict";var or={},Qr={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(De,A,r)=>{De.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(De,A,r)=>{r.r(A),r.d(A,{Environment:()=>Ze,Interpreter:()=>at,Template:()=>gt,parse:()=>se,tokenize:()=>M});var f=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),L=Object.freeze({set:f.Set,for:f.For,in:f.In,is:f.Is,if:f.If,else:f.Else,endif:f.EndIf,elif:f.ElseIf,endfor:f.EndFor,and:f.And,or:f.Or,not:f.Not,"not in":f.NotIn,macro:f.Macro,endmacro:f.EndMacro,true:f.BooleanLiteral,false:f.BooleanLiteral,none:f.NullLiteral,True:f.BooleanLiteral,False:f.BooleanLiteral,None:f.NullLiteral}),N=class{constructor(O,ne){this.value=O,this.type=ne}};function J(O){return/\w/.test(O)}function U(O){return/[0-9]/.test(O)}var w=[["{%",f.OpenStatement],["%}",f.CloseStatement],["{{",f.OpenExpression],["}}",f.CloseExpression],["(",f.OpenParen],[")",f.CloseParen],["{",f.OpenCurlyBracket],["}",f.CloseCurlyBracket],["[",f.OpenSquareBracket],["]",f.CloseSquareBracket],[",",f.Comma],[".",f.Dot],[":",f.Colon],["|",f.Pipe],["<=",f.ComparisonBinaryOperator],[">=",f.ComparisonBinaryOperator],["==",f.ComparisonBinaryOperator],["!=",f.ComparisonBinaryOperator],["<",f.ComparisonBinaryOperator],[">",f.ComparisonBinaryOperator],["+",f.AdditiveBinaryOperator],["-",f.AdditiveBinaryOperator],["*",f.MultiplicativeBinaryOperator],["/",f.MultiplicativeBinaryOperator],["%",f.MultiplicativeBinaryOperator],["=",f.Equals]],v=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function y(O,ne={}){return O.endsWith(` `)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),ne.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),ne.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function M(O,ne={}){var rt,pt,It;const K=[],pe=y(O,ne);let Oe=0;const Qe=St=>{let Ft="";for(;St(pe[Oe]);){if(pe[Oe]==="\\"){if(++Oe,Oe>=pe.length)throw new SyntaxError("Unexpected end of input");const At=pe[Oe++],ns=v.get(At);if(ns===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);Ft+=ns;continue}if(Ft+=pe[Oe++],Oe>=pe.length)throw new SyntaxError("Unexpected end of input")}return Ft};e:for(;Oe0){K.push(new N(At,f.Text));continue}}Qe(At=>/\s/.test(At));const Ft=pe[Oe];if(Ft==="-"||Ft==="+"){const At=(pt=K.at(-1))==null?void 0:pt.type;if(At===f.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${Ft}`);switch(At){case f.Identifier:case f.NumericLiteral:case f.BooleanLiteral:case f.NullLiteral:case f.StringLiteral:case f.CloseParen:case f.CloseSquareBracket:break;default:{++Oe;const ns=Qe(U);K.push(new N(`${Ft}${ns}`,ns.length>0?f.NumericLiteral:f.UnaryOperator));continue}}}for(const[At,ns]of w)if(pe.slice(Oe,Oe+At.length)===At){K.push(new N(At,ns)),Oe+=At.length;continue e}if(Ft==="'"||Ft==='"'){++Oe;const At=Qe(ns=>ns!==Ft);K.push(new N(At,f.StringLiteral)),++Oe;continue}if(U(Ft)){const At=Qe(U);K.push(new N(At,f.NumericLiteral));continue}if(J(Ft)){const At=Qe(J),ns=Object.hasOwn(L,At)?L[At]:f.Identifier;ns===f.In&&((It=K.at(-1))==null?void 0:It.type)===f.Not?(K.pop(),K.push(new N("not in",f.NotIn))):K.push(new N(At,ns));continue}throw new SyntaxError(`Unexpected character: ${Ft}`)}return K}var b=class{constructor(){ge(this,"type","Statement")}},D=class extends b{constructor(ne){super();ge(this,"type","Program");this.body=ne}},H=class extends b{constructor(ne,K,pe){super();ge(this,"type","If");this.test=ne,this.body=K,this.alternate=pe}},re=class extends b{constructor(ne,K,pe,Oe){super();ge(this,"type","For");this.loopvar=ne,this.iterable=K,this.body=pe,this.defaultBlock=Oe}},ie=class extends b{constructor(ne,K){super();ge(this,"type","Set");this.assignee=ne,this.value=K}},z=class extends b{constructor(ne,K,pe){super();ge(this,"type","Macro");this.name=ne,this.args=K,this.body=pe}},V=class extends b{constructor(){super(...arguments);ge(this,"type","Expression")}},Q=class extends V{constructor(ne,K,pe){super();ge(this,"type","MemberExpression");this.object=ne,this.property=K,this.computed=pe}},F=class extends V{constructor(ne,K){super();ge(this,"type","CallExpression");this.callee=ne,this.args=K}},$=class extends V{constructor(ne){super();ge(this,"type","Identifier");this.value=ne}},g=class extends V{constructor(ne){super();ge(this,"type","Literal");this.value=ne}},C=class extends g{constructor(){super(...arguments);ge(this,"type","NumericLiteral")}},T=class extends g{constructor(){super(...arguments);ge(this,"type","StringLiteral")}},ee=class extends g{constructor(){super(...arguments);ge(this,"type","BooleanLiteral")}},Y=class extends g{constructor(){super(...arguments);ge(this,"type","NullLiteral")}},le=class extends g{constructor(){super(...arguments);ge(this,"type","ArrayLiteral")}},de=class extends g{constructor(){super(...arguments);ge(this,"type","TupleLiteral")}},fe=class extends g{constructor(){super(...arguments);ge(this,"type","ObjectLiteral")}},Ce=class extends V{constructor(ne,K,pe){super();ge(this,"type","BinaryExpression");this.operator=ne,this.left=K,this.right=pe}},Te=class extends V{constructor(ne,K){super();ge(this,"type","FilterExpression");this.operand=ne,this.filter=K}},Le=class extends V{constructor(ne,K){super();ge(this,"type","SelectExpression");this.iterable=ne,this.test=K}},qe=class extends V{constructor(ne,K,pe){super();ge(this,"type","TestExpression");this.operand=ne,this.negate=K,this.test=pe}},Ue=class extends V{constructor(ne,K){super();ge(this,"type","UnaryExpression");this.operator=ne,this.argument=K}},ut=class extends V{constructor(ne=void 0,K=void 0,pe=void 0){super();ge(this,"type","SliceExpression");this.start=ne,this.stop=K,this.step=pe}},ue=class extends V{constructor(ne,K){super();ge(this,"type","KeywordArgumentExpression");this.key=ne,this.value=K}};function se(O){const ne=new D([]);let K=0;function pe(nt,_t){const Ot=O[K++];if(!Ot||Ot.type!==nt)throw new Error(`Parser Error: ${_t}. ${Ot.type} !== ${nt}.`);return Ot}function Oe(){switch(O[K].type){case f.Text:return pt();case f.OpenStatement:return It();case f.OpenExpression:return St();default:throw new SyntaxError(`Unexpected token type: ${O[K].type}`)}}function Qe(...nt){return K+nt.length<=O.length&&nt.some((_t,Ot)=>_t!==O[K+Ot].type)}function rt(...nt){return K+nt.length<=O.length&&nt.every((_t,Ot)=>_t===O[K+Ot].type)}function pt(){return new T(pe(f.Text,"Expected text token").value)}function It(){pe(f.OpenStatement,"Expected opening statement token");let nt;switch(O[K].type){case f.Set:++K,nt=Ft(),pe(f.CloseStatement,"Expected closing statement token");break;case f.If:++K,nt=At(),pe(f.OpenStatement,"Expected {% token"),pe(f.EndIf,"Expected endif token"),pe(f.CloseStatement,"Expected %} token");break;case f.Macro:++K,nt=ns(),pe(f.OpenStatement,"Expected {% token"),pe(f.EndMacro,"Expected endmacro token"),pe(f.CloseStatement,"Expected %} token");break;case f.For:++K,nt=ks(),pe(f.OpenStatement,"Expected {% token"),pe(f.EndFor,"Expected endfor token"),pe(f.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[K].type}`)}return nt}function St(){pe(f.OpenExpression,"Expected opening expression token");const nt=As();return pe(f.CloseExpression,"Expected closing expression token"),nt}function Ft(){const nt=As();if(rt(f.Equals)){++K;const _t=Ft();return new ie(nt,_t)}return nt}function At(){var ls,vr,ts,tr,Nr,en,jr,Tr;const nt=As();pe(f.CloseStatement,"Expected closing statement token");const _t=[],Ot=[];for(;!(((ls=O[K])==null?void 0:ls.type)===f.OpenStatement&&(((vr=O[K+1])==null?void 0:vr.type)===f.ElseIf||((ts=O[K+1])==null?void 0:ts.type)===f.Else||((tr=O[K+1])==null?void 0:tr.type)===f.EndIf));)_t.push(Oe());if(((Nr=O[K])==null?void 0:Nr.type)===f.OpenStatement&&((en=O[K+1])==null?void 0:en.type)!==f.EndIf)if(++K,rt(f.ElseIf))pe(f.ElseIf,"Expected elseif token"),Ot.push(At());else for(pe(f.Else,"Expected else token"),pe(f.CloseStatement,"Expected closing statement token");!(((jr=O[K])==null?void 0:jr.type)===f.OpenStatement&&((Tr=O[K+1])==null?void 0:Tr.type)===f.EndIf);)Ot.push(Oe());return new H(nt,_t,Ot)}function ns(){const nt=lr();if(nt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const _t=Rr();pe(f.CloseStatement,"Expected closing statement token");const Ot=[];for(;Qe(f.OpenStatement,f.EndMacro);)Ot.push(Oe());return new z(nt,_t,Ot)}function gs(nt=!1){const _t=nt?lr:As,Ot=[_t()],ls=rt(f.Comma);for(;ls&&(++K,Ot.push(_t()),!!rt(f.Comma)););return ls?new de(Ot):Ot[0]}function ks(){const nt=gs(!0);if(!(nt instanceof $||nt instanceof de))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${nt.type} instead`);pe(f.In,"Expected `in` keyword following loop variable");const _t=As();pe(f.CloseStatement,"Expected closing statement token");const Ot=[];for(;Qe(f.OpenStatement,f.EndFor)&&Qe(f.OpenStatement,f.Else);)Ot.push(Oe());const ls=[];if(rt(f.OpenStatement,f.Else))for(++K,++K,pe(f.CloseStatement,"Expected closing statement token");Qe(f.OpenStatement,f.EndFor);)ls.push(Oe());return new re(nt,_t,Ot,ls)}function As(){return Qs()}function Qs(){const nt=ir();if(rt(f.If)){++K;const _t=ir();if(rt(f.Else)){++K;const Ot=ir();return new H(_t,[nt],[Ot])}else return new Le(nt,_t)}return nt}function ir(){let nt=Yr();for(;rt(f.Or);){const _t=O[K];++K;const Ot=Yr();nt=new Ce(_t,nt,Ot)}return nt}function Yr(){let nt=Br();for(;rt(f.And);){const _t=O[K];++K;const Ot=Br();nt=new Ce(_t,nt,Ot)}return nt}function Br(){let nt;for(;rt(f.Not);){const _t=O[K];++K;const Ot=Br();nt=new Ue(_t,Ot)}return nt??br()}function br(){let nt=Nt();for(;rt(f.ComparisonBinaryOperator)||rt(f.In)||rt(f.NotIn);){const _t=O[K];++K;const Ot=Nt();nt=new Ce(_t,nt,Ot)}return nt}function Nt(){let nt=pr();for(;rt(f.AdditiveBinaryOperator);){const _t=O[K];++K;const Ot=pr();nt=new Ce(_t,nt,Ot)}return nt}function Jr(){const nt=Ar();return rt(f.OpenParen)?Sr(nt):nt}function Sr(nt){let _t=new F(nt,Rr());return rt(f.OpenParen)&&(_t=Sr(_t)),_t}function Rr(){pe(f.OpenParen,"Expected opening parenthesis for arguments list");const nt=$r();return pe(f.CloseParen,"Expected closing parenthesis for arguments list"),nt}function $r(){const nt=[];for(;!rt(f.CloseParen);){let _t=As();if(rt(f.Equals)){if(++K,!(_t instanceof $))throw new SyntaxError("Expected identifier for keyword argument");const Ot=As();_t=new ue(_t,Ot)}nt.push(_t),rt(f.Comma)&&++K}return nt}function ar(){const nt=[];let _t=!1;for(;!rt(f.CloseSquareBracket);)rt(f.Colon)?(nt.push(void 0),++K,_t=!0):(nt.push(As()),rt(f.Colon)&&(++K,_t=!0));if(nt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(_t){if(nt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ut(...nt)}return nt[0]}function Ar(){let nt=lr();for(;rt(f.Dot)||rt(f.OpenSquareBracket);){const _t=O[K];++K;let Ot;const ls=_t.type!==f.Dot;if(ls)Ot=ar(),pe(f.CloseSquareBracket,"Expected closing square bracket");else if(Ot=lr(),Ot.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");nt=new Q(nt,Ot,ls)}return nt}function pr(){let nt=Ir();for(;rt(f.MultiplicativeBinaryOperator);){const _t=O[K];++K;const Ot=Ir();nt=new Ce(_t,nt,Ot)}return nt}function Ir(){let nt=Zr();for(;rt(f.Is);){++K;const _t=rt(f.Not);_t&&++K;let Ot=lr();if(Ot instanceof ee?Ot=new $(Ot.value.toString()):Ot instanceof Y&&(Ot=new $("none")),!(Ot instanceof $))throw new SyntaxError("Expected identifier for the test");nt=new qe(nt,_t,Ot)}return nt}function Zr(){let nt=Jr();for(;rt(f.Pipe);){++K;let _t=lr();if(!(_t instanceof $))throw new SyntaxError("Expected identifier for the filter");rt(f.OpenParen)&&(_t=Sr(_t)),nt=new Te(nt,_t)}return nt}function lr(){const nt=O[K];switch(nt.type){case f.NumericLiteral:return++K,new C(Number(nt.value));case f.StringLiteral:return++K,new T(nt.value);case f.BooleanLiteral:return++K,new ee(nt.value.toLowerCase()==="true");case f.NullLiteral:return++K,new Y(null);case f.Identifier:return++K,new $(nt.value);case f.OpenParen:{++K;const _t=gs();if(O[K].type!==f.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[K].type} instead`);return++K,_t}case f.OpenSquareBracket:{++K;const _t=[];for(;!rt(f.CloseSquareBracket);)_t.push(As()),rt(f.Comma)&&++K;return++K,new le(_t)}case f.OpenCurlyBracket:{++K;const _t=new Map;for(;!rt(f.CloseCurlyBracket);){const Ot=As();pe(f.Colon,"Expected colon between key and value in object literal");const ls=As();_t.set(Ot,ls),rt(f.Comma)&&++K}return++K,new fe(_t)}default:throw new SyntaxError(`Unexpected token: ${nt.type}`)}}for(;K=0?(ne=(ne??(ne=0))<0?Math.max(O.length+ne,0):Math.min(ne,O.length),K=(K??(K=O.length))<0?Math.max(O.length+K,0):Math.min(K,O.length)):(ne=(ne??(ne=O.length-1))<0?Math.max(O.length+ne,-1):Math.min(ne,O.length-1),K=(K??(K=-1))<-1?Math.max(O.length+K,-1):Math.min(K,O.length-1));const Qe=[];for(let rt=ne;Oe*rtne.toUpperCase())}var et=class{constructor(O=void 0){ge(this,"type","RuntimeValue");ge(this,"value");ge(this,"builtins",new Map);this.value=O}__bool__(){return new Je(!!this.value)}},Xe=class extends et{constructor(){super(...arguments);ge(this,"type","NumericValue")}},oe=class extends et{constructor(){super(...arguments);ge(this,"type","StringValue");ge(this,"builtins",new Map([["upper",new je(()=>new oe(this.value.toUpperCase()))],["lower",new je(()=>new oe(this.value.toLowerCase()))],["strip",new je(()=>new oe(this.value.trim()))],["title",new je(()=>new oe(Be(this.value)))],["length",new Xe(this.value.length)],["rstrip",new je(()=>new oe(this.value.trimEnd()))],["lstrip",new je(()=>new oe(this.value.trimStart()))]]))}},Je=class extends et{constructor(){super(...arguments);ge(this,"type","BooleanValue")}},Fe=class extends et{constructor(){super(...arguments);ge(this,"type","ObjectValue");ge(this,"builtins",new Map([["get",new je(([ne,K])=>{if(!(ne instanceof oe))throw new Error(`Object key must be a string: got ${ne.type}`);return this.value.get(ne.value)??K??new Ve})],["items",new je(()=>new ve(Array.from(this.value.entries()).map(([ne,K])=>new ve([new oe(ne),K]))))]]))}__bool__(){return new Je(this.value.size>0)}},ce=class extends Fe{constructor(){super(...arguments);ge(this,"type","KeywordArgumentsValue")}},ve=class extends et{constructor(){super(...arguments);ge(this,"type","ArrayValue");ge(this,"builtins",new Map([["length",new Xe(this.value.length)]]))}__bool__(){return new Je(this.value.length>0)}},Re=class extends ve{constructor(){super(...arguments);ge(this,"type","TupleValue")}},je=class extends et{constructor(){super(...arguments);ge(this,"type","FunctionValue")}},Ve=class extends et{constructor(){super(...arguments);ge(this,"type","NullValue")}},Ne=class extends et{constructor(){super(...arguments);ge(this,"type","UndefinedValue")}},Ze=class{constructor(O){ge(this,"variables",new Map([["namespace",new je(O=>{if(O.length===0)return new Fe(new Map);if(O.length!==1||!(O[0]instanceof Fe))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));ge(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof je],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const ne=O.value;return O.type==="StringValue"&&ne===ne.toLowerCase()}],["upper",O=>{const ne=O.value;return O.type==="StringValue"&&ne===ne.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,ne)=>O.value===ne.value],["eq",(O,ne)=>O.value===ne.value]]));this.parent=O}set(O,ne){return this.declareVariable(O,ft(ne))}declareVariable(O,ne){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,ne),ne}setVariable(O,ne){return this.variables.set(O,ne),ne}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new Ne}catch{return new Ne}}},at=class{constructor(O){ge(this,"global");this.global=O??new Ze}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,ne){const K=this.evaluate(O.left,ne);switch(O.operator.value){case"and":return K.__bool__().value?this.evaluate(O.right,ne):K;case"or":return K.__bool__().value?K:this.evaluate(O.right,ne)}const pe=this.evaluate(O.right,ne);switch(O.operator.value){case"==":return new Je(K.value==pe.value);case"!=":return new Je(K.value!=pe.value)}if(K instanceof Ne||pe instanceof Ne)throw new Error("Cannot perform operation on undefined values");if(K instanceof Ve||pe instanceof Ve)throw new Error("Cannot perform operation on null values");if(K instanceof Xe&&pe instanceof Xe)switch(O.operator.value){case"+":return new Xe(K.value+pe.value);case"-":return new Xe(K.value-pe.value);case"*":return new Xe(K.value*pe.value);case"/":return new Xe(K.value/pe.value);case"%":return new Xe(K.value%pe.value);case"<":return new Je(K.value":return new Je(K.value>pe.value);case">=":return new Je(K.value>=pe.value);case"<=":return new Je(K.value<=pe.value)}else if(K instanceof ve&&pe instanceof ve)switch(O.operator.value){case"+":return new ve(K.value.concat(pe.value))}else if(pe instanceof ve){const Oe=pe.value.find(Qe=>Qe.value===K.value)!==void 0;switch(O.operator.value){case"in":return new Je(Oe);case"not in":return new Je(!Oe)}}if(K instanceof oe||pe instanceof oe)switch(O.operator.value){case"+":return new oe(K.value.toString()+pe.value.toString())}if(K instanceof oe&&pe instanceof oe)switch(O.operator.value){case"in":return new Je(pe.value.includes(K.value));case"not in":return new Je(!pe.value.includes(K.value))}if(K instanceof oe&&pe instanceof Fe)switch(O.operator.value){case"in":return new Je(pe.value.has(K.value));case"not in":return new Je(!pe.value.has(K.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${K.type} and ${pe.type}`)}evaluateArguments(O,ne){const K=[],pe=new Map;for(const Oe of O)if(Oe.type==="KeywordArgumentExpression"){const Qe=Oe;pe.set(Qe.key.value,this.evaluate(Qe.value,ne))}else{if(pe.size>0)throw new Error("Positional arguments must come before keyword arguments");K.push(this.evaluate(Oe,ne))}return[K,pe]}evaluateFilterExpression(O,ne){const K=this.evaluate(O.operand,ne);if(O.filter.type==="Identifier"){const pe=O.filter;if(pe.value==="tojson")return new oe(dt(K));if(K instanceof ve)switch(pe.value){case"list":return K;case"first":return K.value[0];case"last":return K.value[K.value.length-1];case"length":return new Xe(K.value.length);case"reverse":return new ve(K.value.reverse());case"sort":return new ve(K.value.sort((Oe,Qe)=>{if(Oe.type!==Qe.type)throw new Error(`Cannot compare different types: ${Oe.type} and ${Qe.type}`);switch(Oe.type){case"NumericValue":return Oe.value-Qe.value;case"StringValue":return Oe.value.localeCompare(Qe.value);default:throw new Error(`Cannot compare type: ${Oe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${pe.value}`)}else if(K instanceof oe)switch(pe.value){case"length":return new Xe(K.value.length);case"upper":return new oe(K.value.toUpperCase());case"lower":return new oe(K.value.toLowerCase());case"title":return new oe(Be(K.value));case"capitalize":return new oe(K.value.charAt(0).toUpperCase()+K.value.slice(1));case"trim":return new oe(K.value.trim());case"indent":return new oe(K.value.split(` `).map((Oe,Qe)=>Qe===0||Oe.length===0?Oe:" "+Oe).join(` `));case"string":return K;default:throw new Error(`Unknown StringValue filter: ${pe.value}`)}else if(K instanceof Xe)switch(pe.value){case"abs":return new Xe(Math.abs(K.value));default:throw new Error(`Unknown NumericValue filter: ${pe.value}`)}else if(K instanceof Fe)switch(pe.value){case"items":return new ve(Array.from(K.value.entries()).map(([Oe,Qe])=>new ve([new oe(Oe),Qe])));case"length":return new Xe(K.value.size);default:throw new Error(`Unknown ObjectValue filter: ${pe.value}`)}throw new Error(`Cannot apply filter "${pe.value}" to type: ${K.type}`)}else if(O.filter.type==="CallExpression"){const pe=O.filter;if(pe.callee.type!=="Identifier")throw new Error(`Unknown filter: ${pe.callee.type}`);const Oe=pe.callee.value;if(Oe==="tojson"){const[,Qe]=this.evaluateArguments(pe.args,ne),rt=Qe.get("indent")??new Ve;if(!(rt instanceof Xe||rt instanceof Ve))throw new Error("If set, indent must be a number");return new oe(dt(K,rt.value))}if(K instanceof ve){switch(Oe){case"selectattr":case"rejectattr":{const Qe=Oe==="selectattr";if(K.value.some(At=>!(At instanceof Fe)))throw new Error(`\`${Oe}\` can only be applied to array of objects`);if(pe.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${Oe}\` must be strings`);const[rt,pt,It]=pe.args.map(At=>this.evaluate(At,ne));let St;if(pt){const At=ne.tests.get(pt.value);if(!At)throw new Error(`Unknown test: ${pt.value}`);St=At}else St=(...At)=>At[0].__bool__().value;const Ft=K.value.filter(At=>{const ns=At.value.get(rt.value),gs=ns?St(ns,It):!1;return Qe?gs:!gs});return new ve(Ft)}case"map":{const[,Qe]=this.evaluateArguments(pe.args,ne);if(Qe.has("attribute")){const rt=Qe.get("attribute");if(!(rt instanceof oe))throw new Error("attribute must be a string");const pt=Qe.get("default"),It=K.value.map(St=>{if(!(St instanceof Fe))throw new Error("items in map must be an object");return St.value.get(rt.value)??pt??new Ne});return new ve(It)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Oe}`)}else if(K instanceof oe){switch(Oe){case"indent":{const[Qe,rt]=this.evaluateArguments(pe.args,ne),pt=Qe.at(0)??rt.get("width")??new Xe(4);if(!(pt instanceof Xe))throw new Error("width must be a number");const It=Qe.at(1)??rt.get("first")??new Je(!1),St=Qe.at(2)??rt.get("blank")??new Je(!1),Ft=K.value.split(` `),At=" ".repeat(pt.value),ns=Ft.map((gs,ks)=>!It.value&&ks===0||!St.value&&gs.length===0?gs:At+gs);return new oe(ns.join(` `))}}throw new Error(`Unknown StringValue filter: ${Oe}`)}else throw new Error(`Cannot apply filter "${Oe}" to type: ${K.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,ne){const K=this.evaluate(O.operand,ne),pe=ne.tests.get(O.test.value);if(!pe)throw new Error(`Unknown test: ${O.test.value}`);const Oe=pe(K);return new Je(O.negate?!Oe:Oe)}evaluateUnaryExpression(O,ne){const K=this.evaluate(O.argument,ne);switch(O.operator.value){case"not":return new Je(!K.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,ne){return this.evaluateBlock(O.body,ne)}evaluateBlock(O,ne){let K="";for(const pe of O){const Oe=this.evaluate(pe,ne);Oe.type!=="NullValue"&&Oe.type!=="UndefinedValue"&&(K+=Oe.value)}return new oe(K)}evaluateIdentifier(O,ne){return ne.lookupVariable(O.value)}evaluateCallExpression(O,ne){const[K,pe]=this.evaluateArguments(O.args,ne);pe.size>0&&K.push(new ce(pe));const Oe=this.evaluate(O.callee,ne);if(Oe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Oe.type}`);return Oe.value(K,ne)}evaluateSliceExpression(O,ne,K){if(!(O instanceof ve||O instanceof oe))throw new Error("Slice object must be an array or string");const pe=this.evaluate(ne.start,K),Oe=this.evaluate(ne.stop,K),Qe=this.evaluate(ne.step,K);if(!(pe instanceof Xe||pe instanceof Ne))throw new Error("Slice start must be numeric or undefined");if(!(Oe instanceof Xe||Oe instanceof Ne))throw new Error("Slice stop must be numeric or undefined");if(!(Qe instanceof Xe||Qe instanceof Ne))throw new Error("Slice step must be numeric or undefined");return O instanceof ve?new ve(Ee(O.value,pe.value,Oe.value,Qe.value)):new oe(Ee(Array.from(O.value),pe.value,Oe.value,Qe.value).join(""))}evaluateMemberExpression(O,ne){const K=this.evaluate(O.object,ne);let pe;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(K,O.property,ne);pe=this.evaluate(O.property,ne)}else pe=new oe(O.property.value);let Oe;if(K instanceof Fe){if(!(pe instanceof oe))throw new Error(`Cannot access property with non-string: got ${pe.type}`);Oe=K.value.get(pe.value)??K.builtins.get(pe.value)}else if(K instanceof ve||K instanceof oe)if(pe instanceof Xe)Oe=K.value.at(pe.value),K instanceof oe&&(Oe=new oe(K.value.at(pe.value)));else if(pe instanceof oe)Oe=K.builtins.get(pe.value);else throw new Error(`Cannot access property with non-string/non-number: got ${pe.type}`);else{if(!(pe instanceof oe))throw new Error(`Cannot access property with non-string: got ${pe.type}`);Oe=K.builtins.get(pe.value)}return Oe instanceof et?Oe:new Ne}evaluateSet(O,ne){const K=this.evaluate(O.value,ne);if(O.assignee.type==="Identifier"){const pe=O.assignee.value;ne.setVariable(pe,K)}else if(O.assignee.type==="MemberExpression"){const pe=O.assignee,Oe=this.evaluate(pe.object,ne);if(!(Oe instanceof Fe))throw new Error("Cannot assign to member of non-object");if(pe.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Oe.value.set(pe.property.value,K)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new Ve}evaluateIf(O,ne){const K=this.evaluate(O.test,ne);return this.evaluateBlock(K.__bool__().value?O.body:O.alternate,ne)}evaluateFor(O,ne){const K=new Ze(ne);let pe,Oe;if(O.iterable.type==="SelectExpression"){const St=O.iterable;Oe=this.evaluate(St.iterable,K),pe=St.test}else Oe=this.evaluate(O.iterable,K);if(!(Oe instanceof ve))throw new Error(`Expected iterable type in for loop: got ${Oe.type}`);const Qe=[],rt=[];for(let St=0;Stgs.setVariable(O.loopvar.value,At);else if(O.loopvar.type==="TupleLiteral"){const gs=O.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const ks=At;if(gs.value.length!==ks.value.length)throw new Error(`Too ${gs.value.length>ks.value.length?"few":"many"} items to unpack`);ns=As=>{for(let Qs=0;Qs0?Qe[St-1]:new Ne],["nextitem",St{var rt;const Oe=new Ze(pe);K=K.slice();let Qe;((rt=K.at(-1))==null?void 0:rt.type)==="KeywordArgumentsValue"&&(Qe=K.pop());for(let pt=0;ptthis.evaluate(K,ne)));case"TupleLiteral":return new Re(O.value.map(K=>this.evaluate(K,ne)));case"ObjectLiteral":{const K=new Map;for(const[pe,Oe]of O.value){const Qe=this.evaluate(pe,ne);if(!(Qe instanceof oe))throw new Error(`Object keys must be strings: got ${Qe.type}`);K.set(Qe.value,this.evaluate(Oe,ne))}return new Fe(K)}case"Identifier":return this.evaluateIdentifier(O,ne);case"CallExpression":return this.evaluateCallExpression(O,ne);case"MemberExpression":return this.evaluateMemberExpression(O,ne);case"UnaryExpression":return this.evaluateUnaryExpression(O,ne);case"BinaryExpression":return this.evaluateBinaryExpression(O,ne);case"FilterExpression":return this.evaluateFilterExpression(O,ne);case"TestExpression":return this.evaluateTestExpression(O,ne);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function ft(O){switch(typeof O){case"number":return new Xe(O);case"string":return new oe(O);case"boolean":return new Je(O);case"undefined":return new Ne;case"object":return O===null?new Ve:Array.isArray(O)?new ve(O.map(ft)):new Fe(new Map(Object.entries(O).map(([ne,K])=>[ne,ft(K)])));case"function":return new je((ne,K)=>{const pe=O(...ne.map(Oe=>Oe.value))??null;return ft(pe)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function dt(O,ne,K){const pe=K??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const Oe=ne?" ".repeat(ne):"",Qe=` `+Oe.repeat(pe),rt=Qe+Oe;if(O.type==="ArrayValue"){const pt=O.value.map(It=>dt(It,ne,pe+1));return ne?`[${rt}${pt.join(`,${rt}`)}${Qe}]`:`[${pt.join(", ")}]`}else{const pt=Array.from(O.value.entries()).map(([It,St])=>{const Ft=`"${It}": ${dt(St,ne,pe+1)}`;return ne?`${rt}${Ft}`:Ft});return ne?`{${pt.join(",")}${Qe}}`:`{${pt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var gt=class{constructor(O){ge(this,"parsed");const ne=M(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=se(ne)}render(O){const ne=new Ze;ne.set("false",!1),ne.set("true",!0),ne.set("raise_exception",Oe=>{throw new Error(Oe)}),ne.set("range",he);for(const[Oe,Qe]of Object.entries(O))ne.set(Oe,Qe);return new at(ne).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(De,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>N,resolveBackendAndExecutionProviders:()=>U});const f=new Map,L=[],N=(w,v,y)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const M=f.get(w);if(M===void 0)f.set(w,{backend:v,priority:y});else{if(M.priority>y)return;if(M.priority===y&&M.backend!==v)throw new Error(`cannot register backend "${w}" using priority ${y}`)}if(y>=0){const b=L.indexOf(w);b!==-1&&L.splice(b,1);for(let D=0;D{const v=f.get(w);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const y=!!v.initPromise;try{return y||(v.initPromise=v.backend.init(w)),await v.initPromise,v.initialized=!0,v.backend}catch(M){return y||(v.error=`${M}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},U=async w=>{const v=w.executionProviders||[],y=v.map(ie=>typeof ie=="string"?ie:ie.name),M=y.length===0?L:y;let b;const D=[],H=new Set;for(const ie of M){const z=await J(ie);typeof z=="string"?D.push({name:ie,err:z}):(b||(b=z),b===z&&H.add(ie))}if(!b)throw new Error(`no available backend found. ERR: ${D.map(ie=>`[${ie.name}] ${ie.err}`).join(", ")}`);for(const{name:ie,err:z}of D)y.includes(ie)&&console.warn(`removing requested execution provider "${ie}" from session options because it is not available: ${z}`);const re=v.filter(ie=>H.has(typeof ie=="string"?ie:ie.name));return[b,new Proxy(w,{get:(ie,z)=>z==="executionProviders"?re:Reflect.get(ie,z)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(De,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(De,A,r)=>{r.r(A),r.d(A,{env:()=>N});var f=r("./node_modules/onnxruntime-common/dist/esm/version.js");let L="warning";const N={wasm:{},webgl:{},webgpu:{},versions:{common:f.version},set logLevel(J){if(J!==void 0){if(typeof J!="string"||["verbose","info","warning","error","fatal"].indexOf(J)===-1)throw new Error(`Unsupported logging level: ${J}`);L=J}},get logLevel(){return L}};Object.defineProperty(N,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(De,A,r)=>{r.r(A),r.d(A,{env:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const L=f.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>N.InferenceSession,TRACE:()=>U.TRACE,TRACE_FUNC_BEGIN:()=>U.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>U.TRACE_FUNC_END,Tensor:()=>J.Tensor,TrainingSession:()=>w.TrainingSession,env:()=>L.env,registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),L=r("./node_modules/onnxruntime-common/dist/esm/env.js"),N=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),J=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var U=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var w=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>J});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),L=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),N=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class J{constructor(w){this.handler=w}async run(w,v,y){(0,N.TRACE_FUNC_BEGIN)();const M={};let b={};if(typeof w!="object"||w===null||w instanceof L.Tensor||Array.isArray(w))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let D=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof L.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(v)){if(v.length===0)throw new TypeError("'fetches' cannot be an empty array.");D=!1;for(const ie of v){if(typeof ie!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ie)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ie}.`);M[ie]=null}if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else{let ie=!1;const z=Object.getOwnPropertyNames(v);for(const V of this.outputNames)if(z.indexOf(V)!==-1){const Q=v[V];(Q===null||Q instanceof L.Tensor)&&(ie=!0,D=!1,M[V]=Q)}if(ie){if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else b=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ie of this.inputNames)if(typeof w[ie]>"u")throw new Error(`input '${ie}' is missing in 'feeds'.`);if(D)for(const ie of this.outputNames)M[ie]=null;const H=await this.handler.run(w,M,b),re={};for(const ie in H)if(Object.hasOwnProperty.call(H,ie)){const z=H[ie];z instanceof L.Tensor?re[ie]=z:re[ie]=new L.Tensor(z.type,z.data,z.dims)}return(0,N.TRACE_FUNC_END)(),re}async release(){return this.handler.dispose()}static async create(w,v,y,M){(0,N.TRACE_FUNC_BEGIN)();let b,D={};if(typeof w=="string"){if(b=w,typeof v=="object"&&v!==null)D=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(w instanceof Uint8Array){if(b=w,typeof v=="object"&&v!==null)D=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(w instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&w instanceof SharedArrayBuffer){const z=w;let V=0,Q=w.byteLength;if(typeof v=="object"&&v!==null)D=v;else if(typeof v=="number"){if(V=v,!Number.isSafeInteger(V))throw new RangeError("'byteOffset' must be an integer.");if(V<0||V>=z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${z.byteLength}).`);if(Q=w.byteLength-V,typeof y=="number"){if(Q=y,!Number.isSafeInteger(Q))throw new RangeError("'byteLength' must be an integer.");if(Q<=0||V+Q>z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${z.byteLength-V}].`);if(typeof M=="object"&&M!==null)D=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else if(typeof y<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof v<"u")throw new TypeError("'options' must be an object.");b=new Uint8Array(z,V,Q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[H,re]=await(0,f.resolveBackendAndExecutionProviders)(D),ie=await H.createInferenceSessionHandler(b,re);return(0,N.TRACE_FUNC_END)(),new J(ie)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const L=f.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(De,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>f,tensorToImageData:()=>L});const f=(N,J)=>{const U=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);U.width=N.dims[3],U.height=N.dims[2];const w=U.getContext("2d");if(w!=null){let v,y;(J==null?void 0:J.tensorLayout)!==void 0&&J.tensorLayout==="NHWC"?(v=N.dims[2],y=N.dims[3]):(v=N.dims[3],y=N.dims[2]);const M=(J==null?void 0:J.format)!==void 0?J.format:"RGB",b=J==null?void 0:J.norm;let D,H;b===void 0||b.mean===void 0?D=[255,255,255,255]:typeof b.mean=="number"?D=[b.mean,b.mean,b.mean,b.mean]:(D=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(D[3]=b.mean[3])),b===void 0||b.bias===void 0?H=[0,0,0,0]:typeof b.bias=="number"?H=[b.bias,b.bias,b.bias,b.bias]:(H=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(H[3]=b.bias[3]));const re=y*v;let ie=0,z=re,V=re*2,Q=-1;M==="RGBA"?(ie=0,z=re,V=re*2,Q=re*3):M==="RGB"?(ie=0,z=re,V=re*2):M==="RBG"&&(ie=0,V=re,z=re*2);for(let F=0;F{const U=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let w;if(U!=null){let v,y,M;(J==null?void 0:J.tensorLayout)!==void 0&&J.tensorLayout==="NHWC"?(v=N.dims[2],y=N.dims[1],M=N.dims[3]):(v=N.dims[3],y=N.dims[2],M=N.dims[1]);const b=J!==void 0&&J.format!==void 0?J.format:"RGB",D=J==null?void 0:J.norm;let H,re;D===void 0||D.mean===void 0?H=[255,255,255,255]:typeof D.mean=="number"?H=[D.mean,D.mean,D.mean,D.mean]:(H=[D.mean[0],D.mean[1],D.mean[2],255],D.mean[3]!==void 0&&(H[3]=D.mean[3])),D===void 0||D.bias===void 0?re=[0,0,0,0]:typeof D.bias=="number"?re=[D.bias,D.bias,D.bias,D.bias]:(re=[D.bias[0],D.bias[1],D.bias[2],0],D.bias[3]!==void 0&&(re[3]=D.bias[3]));const ie=y*v;if(J!==void 0&&(J.format!==void 0&&M===4&&J.format!=="RGBA"||M===3&&J.format!=="RGB"&&J.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const z=4;let V=0,Q=1,F=2,$=3,g=0,C=ie,T=ie*2,ee=-1;b==="RGBA"?(g=0,C=ie,T=ie*2,ee=ie*3):b==="RGB"?(g=0,C=ie,T=ie*2):b==="RBG"&&(g=0,T=ie,C=ie*2),w=U.createImageData(v,y);for(let Y=0;Y{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(De,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>L,tensorFromGpuBuffer:()=>U,tensorFromImage:()=>N,tensorFromMLTensor:()=>w,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>J});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const L=(y,M)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(M.height===void 0||M.width===void 0)throw new Error("Image height and width must be defined");if(M.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:b,width:D}=M,H=M.norm??{mean:255,bias:0};let re,ie;typeof H.mean=="number"?re=[H.mean,H.mean,H.mean,H.mean]:re=[H.mean[0],H.mean[1],H.mean[2],H.mean[3]??255],typeof H.bias=="number"?ie=[H.bias,H.bias,H.bias,H.bias]:ie=[H.bias[0],H.bias[1],H.bias[2],H.bias[3]??0];const z=M.format!==void 0?M.format:"RGBA",V=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",Q=b*D,F=V==="RGBA"?new Float32Array(Q*4):new Float32Array(Q*3);let $=4,g=0,C=1,T=2,ee=3,Y=0,le=Q,de=Q*2,fe=-1;z==="RGB"&&($=3,g=0,C=1,T=2,ee=-1),V==="RGBA"?fe=Q*3:V==="RBG"?(Y=0,de=Q,le=Q*2):V==="BGR"&&(de=0,le=Q,Y=Q*2);for(let Te=0;Te{const b=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,D=typeof ImageData<"u"&&y instanceof ImageData,H=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,re=typeof y=="string";let ie,z=M??{};const V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Q=F=>typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||F instanceof OffscreenCanvas?F.getContext("2d"):null;if(b){const F=V();F.width=y.width,F.height=y.height;const $=Q(F);if($!=null){let g=y.height,C=y.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(g=M.resizedHeight,C=M.resizedWidth),M!==void 0){if(z=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");z.tensorFormat="RGBA",z.height=g,z.width=C}else z.tensorFormat="RGBA",z.height=g,z.width=C;$.drawImage(y,0,0),ie=$.getImageData(0,0,C,g).data}else throw new Error("Can not access image data")}else if(D){let F,$;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(F=M.resizedHeight,$=M.resizedWidth):(F=y.height,$=y.width),M!==void 0&&(z=M),z.format="RGBA",z.height=F,z.width=$,M!==void 0){const g=V();g.width=$,g.height=F;const C=Q(g);if(C!=null)C.putImageData(y,0,0),ie=C.getImageData(0,0,$,F).data;else throw new Error("Can not access image data")}else ie=y.data}else if(H){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const F=V();F.width=y.width,F.height=y.height;const $=Q(F);if($!=null){const g=y.height,C=y.width;return $.drawImage(y,0,0,C,g),ie=$.getImageData(0,0,C,g).data,z.height=g,z.width=C,L(ie,z)}else throw new Error("Can not access image data")}else{if(re)return new Promise((F,$)=>{const g=V(),C=Q(g);if(!y||!C)return $();const T=new Image;T.crossOrigin="Anonymous",T.src=y,T.onload=()=>{g.width=T.width,g.height=T.height,C.drawImage(T,0,0,g.width,g.height);const ee=C.getImageData(0,0,g.width,g.height);z.height=g.height,z.width=g.width,F(L(ee.data,z))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ie!==void 0)return L(ie,z);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(y,M)=>{const{width:b,height:D,download:H,dispose:re}=M,ie=[1,D,b,4];return new f.Tensor({location:"texture",type:"float32",texture:y,dims:ie,download:H,dispose:re})},U=(y,M)=>{const{dataType:b,dims:D,download:H,dispose:re}=M;return new f.Tensor({location:"gpu-buffer",type:b??"float32",gpuBuffer:y,dims:D,download:H,dispose:re})},w=(y,M)=>{const{dataType:b,dims:D,download:H,dispose:re}=M;return new f.Tensor({location:"ml-tensor",type:b??"float32",mlTensor:y,dims:D,download:H,dispose:re})},v=(y,M,b)=>new f.Tensor({location:"cpu-pinned",type:y,data:M,dims:b??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(De,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>L,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>f,checkTypedArray:()=>J});const f=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),L=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let N=!1;const J=()=>{if(!N){N=!0;const U=typeof BigInt64Array<"u"&&BigInt64Array.from,w=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;U&&(f.set("int64",BigInt64Array),L.set(BigInt64Array,"int64")),w&&(f.set("uint64",BigUint64Array),L.set(BigUint64Array,"uint64")),v?(f.set("float16",Float16Array),L.set(Float16Array,"float16")):f.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>U});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),L=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),N=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),J=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class U{constructor(v,y,M){(0,N.checkTypedArray)();let b,D;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,b=v.type,D=v.dims,v.location){case"cpu-pinned":{const re=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(!re)throw new TypeError(`unsupported type "${b}" to create tensor from pinned buffer`);if(!(v.data instanceof re))throw new TypeError(`buffer should be of type ${re.name}`);this.cpuData=v.data;break}case"texture":{if(b!=="float32")throw new TypeError(`unsupported type "${b}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint8"&&b!=="bool"&&b!=="uint4"&&b!=="int4")throw new TypeError(`unsupported type "${b}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint64"&&b!=="int8"&&b!=="uint8"&&b!=="bool")throw new TypeError(`unsupported type "${b}" to create tensor from MLTensor`);this.mlTensorData=v.mlTensor,this.downloader=v.download,this.disposer=v.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let re,ie;if(typeof v=="string")if(b=v,ie=M,v==="string"){if(!Array.isArray(y))throw new TypeError("A string tensor's data must be a string array.");re=y}else{const z=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(z===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(y)){if(v==="float16"&&z===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${z.name} as data.`);v==="uint64"||v==="int64"?re=z.from(y,BigInt):re=z.from(y)}else if(y instanceof z)re=y;else if(y instanceof Uint8ClampedArray)if(v==="uint8")re=Uint8Array.from(y);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${b} tensor's data must be type of ${z}`)}else if(ie=y,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const z=typeof v[0];if(z==="string")b="string",re=v;else if(z==="boolean")b="bool",re=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${z}.`)}else if(v instanceof Uint8ClampedArray)b="uint8",re=Uint8Array.from(v);else{const z=N.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(z===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);b=z,re=v}if(ie===void 0)ie=[re.length];else if(!Array.isArray(ie))throw new TypeError("A tensor's dims must be a number array");D=ie,this.cpuData=re,this.dataLocation="cpu"}const H=(0,J.calculateSize)(D);if(this.cpuData&&H!==this.cpuData.length&&!((b==="uint4"||b==="int4")&&Math.ceil(H/2)===this.cpuData.length))throw new Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=b,this.dims=D,this.size=H}static async fromImage(v,y){return(0,L.tensorFromImage)(v,y)}static fromTexture(v,y){return(0,L.tensorFromTexture)(v,y)}static fromGpuBuffer(v,y){return(0,L.tensorFromGpuBuffer)(v,y)}static fromMLTensor(v,y){return(0,L.tensorFromMLTensor)(v,y)}static fromPinnedBuffer(v,y,M){return(0,L.tensorFromPinnedBuffer)(v,y,M)}toDataURL(v){return(0,f.tensorToDataURL)(this,v)}toImageData(v){return(0,f.tensorToImageData)(this,v)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(v){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const y=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=y,v&&this.disposer&&(this.disposer(),this.disposer=void 0),y}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(v){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,J.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(De,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>L,tensorReshape:()=>N});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const L=J=>{let U=1;for(let w=0;w{switch(J.location){case"cpu":return new f.Tensor(J.type,J.data,U);case"cpu-pinned":return new f.Tensor({location:"cpu-pinned",data:J.data,type:J.type,dims:U});case"texture":return new f.Tensor({location:"texture",texture:J.texture,type:J.type,dims:U});case"gpu-buffer":return new f.Tensor({location:"gpu-buffer",gpuBuffer:J.gpuBuffer,type:J.type,dims:U});case"ml-tensor":return new f.Tensor({location:"ml-tensor",mlTensor:J.mlTensor,type:J.type,dims:U});default:throw new Error(`tensorReshape: tensor location ${J.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const L=f.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(De,A,r)=>{r.r(A),r.d(A,{TRACE:()=>L,TRACE_FUNC_BEGIN:()=>J,TRACE_FUNC_END:()=>U});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const L=(w,v)=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||console.timeStamp(`${w}::ORT::${v}`)},N=(w,v)=>{var b;const y=((b=new Error().stack)==null?void 0:b.split(/\r\n|\r|\n/g))||[];let M=!1;for(let D=0;D{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||N("BEGIN",w)},U=w=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||N("END",w)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(De,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>J});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),L=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const N="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class J{constructor(w,v,y){this.handler=w,this.hasOptimizerModel=v,this.hasEvalModel=y}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(w,v){const y=w.evalModel||"",M=w.optimizerModel||"",b=v||{},[D,H]=await(0,f.resolveBackendAndExecutionProviders)(b);if(D.createTrainingSessionHandler){const re=await D.createTrainingSessionHandler(w.checkpointState,w.trainModel,y,M,H);return new J(re,!!w.optimizerModel,!!w.evalModel)}else throw new Error(N)}typeNarrowingForRunStep(w,v,y,M,b){const D={};let H={};if(typeof y!="object"||y===null||y instanceof L.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof M=="object"){if(M===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(M instanceof L.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(M)){if(M.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const ie of M){if(typeof ie!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ie)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ie}.`);D[ie]=null}if(typeof b=="object"&&b!==null)H=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ie=!1;const z=Object.getOwnPropertyNames(M);for(const V of v)if(z.indexOf(V)!==-1){const Q=M[V];(Q===null||Q instanceof L.Tensor)&&(ie=!0,re=!1,D[V]=Q)}if(ie){if(typeof b=="object"&&b!==null)H=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else H=M}}else if(typeof M<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ie of w)if(typeof y[ie]>"u")throw new Error(`input '${ie}' is missing in 'feeds'.`);if(re)for(const ie of v)D[ie]=null;return[D,H]}convertHandlerReturnTypeToMapOfTensors(w){const v={};for(const y in w)if(Object.hasOwnProperty.call(w,y)){const M=w[y];M instanceof L.Tensor?v[y]=M:v[y]=new L.Tensor(M.type,M.data,M.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(w,v,y){const[M,b]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,w,v,y),D=await this.handler.runTrainStep(w,M,b);return this.convertHandlerReturnTypeToMapOfTensors(D)}async runOptimizerStep(w){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(w||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(w,v,y){if(this.hasEvalModel){const[M,b]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,w,v,y),D=await this.handler.runEvalStep(w,M,b);return this.convertHandlerReturnTypeToMapOfTensors(D)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(w=!0){return this.handler.getParametersSize(w)}async loadParametersBuffer(w,v=!0){const y=await this.getParametersSize(v);if(w.length!==4*y)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(w,v)}async getContiguousParameters(w=!0){return this.handler.getContiguousParameters(w)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(De,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>L});var f=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const L=f.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(De,A,r)=>{r.r(A),r.d(A,{version:()=>f});const f="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>dt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>Ve,TRACE_FUNC_END:()=>Ne,Tensor:()=>ce,default:()=>c_,env:()=>T,registerBackend:()=>H});/*! * ONNX Runtime Web v1.21.0-dev.20241205-d27fecd3d3 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var f=Object.defineProperty,L=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyNames,J=Object.prototype.hasOwnProperty,U=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),w=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var s in t)f(e,s,{get:t[s],enumerable:!0})},y=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of N(t))!J.call(e,o)&&o!==s&&f(e,o,{get:()=>t[o],enumerable:!(n=L(t,o))||n.enumerable});return e},M=e=>y(f({},"__esModule",{value:!0}),e),b,D,H,re,ie,z=w(()=>{b=new Map,D=[],H=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=b.get(e);if(n===void 0)b.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=D.indexOf(e);o!==-1&&D.splice(o,1);for(let a=0;a{let t=b.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ie=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?D:s,o,a=[],i=new Set;for(let p of n){let h=await re(p);typeof h=="string"?a.push({name:p,err:h}):(o||(o=h),o===h&&i.add(p))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let d=t.filter(p=>i.has(typeof p=="string"?p:p.name));return[o,new Proxy(e,{get:(p,h)=>h==="executionProviders"?d:Reflect.get(p,h)})]}}),V=w(()=>{z()}),Q,F=w(()=>{Q="1.21.0-dev.20241205-6ed77cc374"}),$,g,C=w(()=>{F(),$="warning",g={wasm:{},webgl:{},webgpu:{},versions:{common:Q},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);$=e}},get logLevel(){return $}},Object.defineProperty(g,"logLevel",{enumerable:!0})}),T,ee=w(()=>{C(),T=g}),Y,le,de=w(()=>{Y=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let o,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[3]):(o=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,h;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let k=a*o,S=0,u=k,B=k*2,R=-1;i==="RGBA"?(S=0,u=k,B=k*2,R=k*3):i==="RGB"?(S=0,u=k,B=k*2):i==="RBG"&&(S=0,B=k,u=k*2);for(let j=0;j{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let o,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[1],i=e.dims[3]):(o=e.dims[3],a=e.dims[2],i=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let S=a*o;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,B=0,R=1,j=2,Z=3,te=0,X=S,_e=S*2,me=-1;d==="RGBA"?(te=0,X=S,_e=S*2,me=S*3):d==="RGB"?(te=0,X=S,_e=S*2):d==="RBG"&&(te=0,_e=S,X=S*2),n=s.createImageData(o,a);for(let ye=0;ye{Fe(),fe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,o=t.norm??{mean:255,bias:0},a,i;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),S=4,u=0,B=1,R=2,j=3,Z=0,te=h,X=h*2,_e=-1;d==="RGB"&&(S=3,u=0,B=1,R=2,j=-1),p==="RGBA"?_e=h*3:p==="RBG"?(Z=0,X=h,te=h*2):p==="BGR"&&(X=0,te=h,Z=h*2);for(let me=0;me{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,d=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(s){let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,B=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=u,d.width=B}else d.tensorFormat="RGBA",d.height=u,d.width=B;S.drawImage(e,0,0),i=S.getImageData(0,0,B,u).data}else throw new Error("Can not access image data")}else if(n){let k,S;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,S=t.resizedWidth):(k=e.height,S=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=k,d.width=S,t!==void 0){let u=p();u.width=S,u.height=k;let B=h(u);if(B!=null)B.putImageData(e,0,0),i=B.getImageData(0,0,S,k).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;return S.drawImage(e,0,0,B,u),i=S.getImageData(0,0,B,u).data,d.height=u,d.width=B,fe(i,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,S)=>{let u=p(),B=h(u);if(!e||!B)return S();let R=new Image;R.crossOrigin="Anonymous",R.src=e,R.onload=()=>{u.width=R.width,u.height=R.height,B.drawImage(R,0,0,u.width,u.height);let j=B.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,k(fe(j.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return fe(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Te=(e,t)=>{let{width:s,height:n,download:o,dispose:a}=t,i=[1,n,s,4];return new Je({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:a})},Le=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:a}=t;return new Je({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:o,dispose:a})},qe=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:a}=t;return new Je({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:o,dispose:a})},Ue=(e,t,s)=>new Je({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),ue,se,he,Ee,Be=w(()=>{ue=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),he=!1,Ee=()=>{if(!he){he=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(ue.set("int64",BigInt64Array),se.set(BigInt64Array,"int64")),t&&(ue.set("uint64",BigUint64Array),se.set(BigUint64Array,"uint64")),s?(ue.set("float16",Float16Array),se.set(Float16Array,"float16")):ue.set("float16",Uint16Array)}}}),et,Xe,oe=w(()=>{Fe(),et=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Je(e.type,e.data,t);case"cpu-pinned":return new Je({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Je({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Je({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Je({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Je,Fe=w(()=>{de(),ut(),Be(),oe(),Je=class{constructor(e,t,s){Ee();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=ue.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}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 i,d;if(typeof e=="string")if(n=e,d=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let p=ue.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?i=p.from(t,BigInt):i=p.from(t)}else if(t instanceof p)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${p}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",i=e;else if(p==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let p=se.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,i=e}if(d===void 0)d=[i.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");o=d,this.cpuData=i,this.dataLocation="cpu"}let a=et(o);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=o,this.size=a}static async fromImage(e,t){return Ce(e,t)}static fromTexture(e,t){return Te(e,t)}static fromGpuBuffer(e,t){return Le(e,t)}static fromMLTensor(e,t){return qe(e,t)}static fromPinnedBuffer(e,t,s){return Ue(e,t,s)}toDataURL(e){return Y(this,e)}toImageData(e){return le(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,e)}}}),ce,ve=w(()=>{Fe(),ce=Je}),Re,je,Ve,Ne,Ze=w(()=>{C(),Re=(e,t)=>{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||console.timeStamp(`${e}::ORT::${t}`)},je=(e,t)=>{var o;let s=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||je("BEGIN",e)},Ne=e=>{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||je("END",e)}}),at,ft=w(()=>{z(),ve(),Ze(),at=class Ym{constructor(t){this.handler=t}async run(t,s,n){Ve();let o={},a={};if(typeof t!="object"||t===null||t instanceof ce||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof ce)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(s);for(let S of this.outputNames)if(k.indexOf(S)!==-1){let u=s[S];(u===null||u instanceof ce)&&(h=!0,i=!1,o[S]=u)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)o[h]=null;let d=await this.handler.run(t,o,a),p={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let k=d[h];k instanceof ce?p[h]=k:p[h]=new ce(k.type,k.data,k.dims)}return Ne(),p}async release(){return this.handler.dispose()}static async create(t,s,n,o){Ve();let a,i={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,S=0,u=t.byteLength;if(typeof s=="object"&&s!==null)i=s;else if(typeof s=="number"){if(S=s,!Number.isSafeInteger(S))throw new RangeError("'byteOffset' must be an integer.");if(S<0||S>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(u=t.byteLength-S,typeof n=="number"){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||S+u>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-S}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(k,S,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,p]=await ie(i),h=await d.createInferenceSessionHandler(a,p);return Ne(),new Ym(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),dt,gt=w(()=>{ft(),dt=at}),O=w(()=>{}),ne=w(()=>{}),K=w(()=>{}),pe=w(()=>{}),Oe={};v(Oe,{InferenceSession:()=>dt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>Ve,TRACE_FUNC_END:()=>Ne,Tensor:()=>ce,env:()=>T,registerBackend:()=>H});var Qe=w(()=>{V(),ee(),gt(),ve(),O(),ne(),Ze(),K(),pe()}),rt=w(()=>{}),pt={};v(pt,{default:()=>Ft});var It,St,Ft,At=w(()=>{var e;wh(),Ot(),$r(),It="ort-wasm-proxy-worker",St=((e=globalThis.self)==null?void 0:e.name)===It,St&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":nt(n.wasm).then(()=>{Mc(n).then(()=>{postMessage({type:s})},o=>{postMessage({type:s,err:o})})},o=>{postMessage({type:s,err:o})});break;case"init-ep":{let{epName:o,env:a}=n;Xr(a,o).then(()=>{postMessage({type:s})},i=>{postMessage({type:s,err:i})});break}case"copy-from":{let{buffer:o}=n,a=_p(o);postMessage({type:s,out:a});break}case"create":{let{model:o,options:a}=n;Bp(o,a).then(i=>{postMessage({type:s,out:i})},i=>{postMessage({type:s,err:i})});break}case"release":Rp(n),postMessage({type:s});break;case"run":{let{sessionId:o,inputIndices:a,inputs:i,outputIndices:d,options:p}=n;jp(o,a,i,d,new Array(d.length).fill(null),p).then(h=>{h.some(k=>k[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:h},Wp([...i,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":Up(n),postMessage({type:s});break;default:}}catch(o){postMessage({type:s,err:o})}}),Ft=St?null:t=>new Worker(t??ir,{type:"module",name:It})}),ns={};v(ns,{default:()=>As});var gs,ks,As,Qs=w(()=>{var e;ks=(gs=self.location.href,async function(t={}){function s(){return jt.buffer!=Gt.buffer&&Es(),Gt}function n(){return jt.buffer!=Gt.buffer&&Es(),Cs}function o(){return jt.buffer!=Gt.buffer&&Es(),ot}function a(){return jt.buffer!=Gt.buffer&&Es(),Et}function i(){return jt.buffer!=Gt.buffer&&Es(),cs}function d(){return jt.buffer!=Gt.buffer&&Es(),Ls}function p(){return jt.buffer!=Gt.buffer&&Es(),Mr}function h(){return jt.buffer!=Gt.buffer&&Es(),Lo}var k,S,u=Object.assign({},t),B=new Promise((l,m)=>{k=l,S=m}),R=typeof window=="object",j=typeof importScripts=="function",Z=j&&self.name=="em-pthread";u.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(u.Fb||(u.Fb=new Map)).set(l,m)},u.unmountExternalData=()=>{delete u.Fb};var te=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let X=()=>{let l=(E,I,G)=>(...we)=>{let Ke=mn,tt=I==null?void 0:I();we=E(...we);let bt=I==null?void 0:I();return tt!==bt&&(E=bt,G(tt),I=G=null),mn!=Ke?new Promise((kt,Vt)=>{uh={resolve:kt,reject:Vt}}):we},m=E=>async(...I)=>{var G;try{if(u.Gb)throw Error("Session already started");let we=u.Gb={hc:I[0],errors:[]},Ke=await E(...I);if(u.Gb!==we)throw Error("Session mismatch");(G=u.Hb)==null||G.flush();let tt=we.errors;if(0kt),0u._OrtCreateSession,E=>u._OrtCreateSession=E),u._OrtRun=m(l(u._OrtRun,()=>u._OrtRun,E=>u._OrtRun=E)),u._OrtRunWithBinding=m(l(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,E=>u._OrtRunWithBinding=E)),u._OrtBindInput=l(u._OrtBindInput,()=>u._OrtBindInput,E=>u._OrtBindInput=E),X=void 0};u.jsepInit=(l,m)=>{if(X==null||X(),l==="webgpu"){[u.Hb,u.Vb,u.Zb,u.Ob,u.Yb,u.kb,u.$b,u.cc,u.Wb,u.Xb,u.ac]=m;let E=u.Hb;u.jsepRegisterBuffer=(I,G,we,Ke)=>E.registerBuffer(I,G,we,Ke),u.jsepGetBuffer=I=>E.getBuffer(I),u.jsepCreateDownloader=(I,G,we)=>E.createDownloader(I,G,we),u.jsepOnCreateSession=I=>{E.onCreateSession(I)},u.jsepOnReleaseSession=I=>{E.onReleaseSession(I)},u.jsepOnRunStart=I=>E.onRunStart(I),u.dc=(I,G)=>{E.upload(I,G)}}else if(l==="webnn"){[u.Hb,u.bc,u.Pb,u.jsepEnsureTensor,u.ec,u.jsepDownloadTensor]=m,u.jsepReleaseTensorId=u.Pb;let E=u.Hb;u.jsepOnRunStart=I=>E.onRunStart(I),u.jsepRegisterMLContext=(I,G)=>{E.registerMLContext(I,G)},u.jsepOnReleaseSession=I=>{E.onReleaseSession(I)},u.jsepCreateMLTensorDownloader=(I,G)=>E.createMLTensorDownloader(I,G),u.jsepRegisterMLTensor=(I,G,we)=>E.registerMLTensor(I,G,we),u.jsepCreateMLContext=I=>E.createMLContext(I),u.jsepRegisterMLConstant=(I,G,we,Ke,tt)=>E.registerMLConstant(I,G,we,Ke,tt,u.Fb)}};var _e,me,ye=Object.assign({},u),$e="./this.program",Ae=(l,m)=>{throw m},Ge="";(R||j)&&(j?Ge=self.location.href:typeof document<"u"&&document.currentScript&&(Ge=document.currentScript.src),gs&&(Ge=gs),Ge=Ge.startsWith("blob:")?"":Ge.substr(0,Ge.replace(/[?#].*/,"").lastIndexOf("/")+1),j&&(me=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),_e=(l,m,E)=>{var I=new XMLHttpRequest;I.open("GET",l,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?m(I.response):E()},I.onerror=E,I.send(null)});var lt,xt=console.log.bind(console),Kt=console.error.bind(console),Yt=xt,Ct=Kt;if(Object.assign(u,ye),ye=null,Z){let l=function(m){try{var E=m.data,I=E.cmd;if(I==="load"){let G=[];self.onmessage=we=>G.push(we),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let we of G)l(we);self.onmessage=l};for(let we of E.handlers)u[we]&&!u[we].proxy||(u[we]=(...Ke)=>{postMessage({Nb:"callHandler",pc:we,args:Ke})},we=="print"&&(Yt=u[we]),we=="printErr"&&(Ct=u[we]));jt=E.wasmMemory,Es(),Jt(E.wasmModule)}else if(I==="run"){hh(E.pthread_ptr,0,0,1,0,0),ah(E.pthread_ptr),m_(),Uh(),$t||(Rm(),$t=!0);try{__(E.start_routine,E.arg)}catch(G){if(G!="unwind")throw G}}else I==="cancel"?Ma()&&Sp(-1):E.target!=="setimmediate"&&(I==="checkMailbox"?$t&&yp():I&&(Ct(`worker: received unknown command ${I}`),Ct(E)))}catch(G){throw Nm(),G}};var Jt,$t=!1;Ct=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Ma()})},u.instantiateWasm=(m,E)=>new Promise(I=>{Jt=G=>{G=new WebAssembly.Instance(G,zh()),E(G),I()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}u.wasmBinary&&(lt=u.wasmBinary);var jt,vs,Ht,Gt,Cs,ot,Et,cs,Ls,Mr,Hs,cn,Lo,Is=!1;function Es(){var l=jt.buffer;u.HEAP8=Gt=new Int8Array(l),u.HEAP16=ot=new Int16Array(l),u.HEAPU8=Cs=new Uint8Array(l),u.HEAPU16=Et=new Uint16Array(l),u.HEAP32=cs=new Int32Array(l),u.HEAPU32=Ls=new Uint32Array(l),u.HEAPF32=Mr=new Float32Array(l),u.HEAPF64=Lo=new Float64Array(l),u.HEAP64=Hs=new BigInt64Array(l),u.HEAPU64=cn=new BigUint64Array(l)}if(!Z){if(!((jt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof te))throw Ct("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");Es()}var Gn=[],Tc=[],qp=[],xc=0,Ec=null;function Ih(){if(--xc==0&&Ec){var l=Ec;Ec=null,l()}}function Kn(l){throw Ct(l="Aborted("+l+")"),Is=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),S(l),l}var Xp,Oh=l=>l.startsWith("data:application/octet-stream;base64,"),Fh=l=>l.startsWith("file://");function Dh(l){if(l==Xp&<)return new Uint8Array(lt);if(me)return me(l);throw"both async and sync fetching of the wasm failed"}function Lh(l,m,E){return function(I){if(!lt&&(R||j)){if(typeof fetch=="function"&&!Fh(I))return fetch(I,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${I}'`;return G.arrayBuffer()}).catch(()=>Dh(I));if(_e)return new Promise((G,we)=>{_e(I,Ke=>G(new Uint8Array(Ke)),we)})}return Promise.resolve().then(()=>Dh(I))}(l).then(I=>WebAssembly.instantiate(I,m)).then(E,I=>{Ct(`failed to asynchronously prepare wasm: ${I}`),Kn(I)})}function zh(){return{a:{O:h_,Aa:p_,b:g_,aa:Kh,B:Xh,qa:Qh,Y:Jh,_:Zh,ra:em,oa:tm,ha:sm,na:rm,L:nm,Z:om,W:im,pa:am,X:lm,va:w_,F:y_,Q:M_,P:v_,E:x_,u:E_,q:P_,G:C_,A:F_,R:D_,ua:L_,ka:z_,U:B_,ba:R_,H:N_,ja:ah,ta:j_,t:U_,Ba:W_,x:K_,n:H_,l:X_,c:oh,o:Q_,j:Z_,w:ef,p:tf,f:sf,s:rf,m:nf,e:of,k:af,i:lf,h:uf,d:df,ea:cf,fa:pf,ga:hf,ca:vm,da:Tm,T:mf,g:_f,D:ff,I:gf,M:wf,y:yf,sa:Mf,V:bf,v:Em,z:vf,N:Tf,S:xf,za:Ef,ya:Pf,la:km,ma:Sm,$:eh,C:$m,K:Am,ia:Im,J:Om,a:jt,xa:Zp,wa:Lm,r:Sf}}}var Qp={874308:(l,m,E,I,G)=>{if(u===void 0||!u.Fb)return 1;if((l=zs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=u.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),I=Number(I>>>0),m+E>l.byteLength)return 3;try{let we=l.subarray(m,m+E);switch(G){case 0:n().set(we,I>>>0);break;case 1:u.dc(I,we);break;default:return 4}return 0}catch{return 4}},875023:(l,m,E)=>{u.ec(l,n().subarray(m>>>0,m+E>>>0))},875086:()=>u.bc(),875127:l=>{u.Pb(l)},875163:()=>{u.Wb()},875194:()=>{u.Xb()},875223:()=>{u.ac()},875248:l=>u.Vb(l),875281:l=>u.Zb(l),875313:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E),!0)},875376:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E))},875433:()=>typeof wasmOffsetConverter<"u",875490:l=>{u.kb("Abs",l,void 0)},875541:l=>{u.kb("Neg",l,void 0)},875592:l=>{u.kb("Floor",l,void 0)},875645:l=>{u.kb("Ceil",l,void 0)},875697:l=>{u.kb("Reciprocal",l,void 0)},875755:l=>{u.kb("Sqrt",l,void 0)},875807:l=>{u.kb("Exp",l,void 0)},875858:l=>{u.kb("Erf",l,void 0)},875909:l=>{u.kb("Sigmoid",l,void 0)},875964:(l,m,E)=>{u.kb("HardSigmoid",l,{alpha:m,beta:E})},876043:l=>{u.kb("Log",l,void 0)},876094:l=>{u.kb("Sin",l,void 0)},876145:l=>{u.kb("Cos",l,void 0)},876196:l=>{u.kb("Tan",l,void 0)},876247:l=>{u.kb("Asin",l,void 0)},876299:l=>{u.kb("Acos",l,void 0)},876351:l=>{u.kb("Atan",l,void 0)},876403:l=>{u.kb("Sinh",l,void 0)},876455:l=>{u.kb("Cosh",l,void 0)},876507:l=>{u.kb("Asinh",l,void 0)},876560:l=>{u.kb("Acosh",l,void 0)},876613:l=>{u.kb("Atanh",l,void 0)},876666:l=>{u.kb("Tanh",l,void 0)},876718:l=>{u.kb("Not",l,void 0)},876769:(l,m,E)=>{u.kb("Clip",l,{min:m,max:E})},876838:l=>{u.kb("Clip",l,void 0)},876890:(l,m)=>{u.kb("Elu",l,{alpha:m})},876948:l=>{u.kb("Gelu",l,void 0)},877e3:l=>{u.kb("Relu",l,void 0)},877052:(l,m)=>{u.kb("LeakyRelu",l,{alpha:m})},877116:(l,m)=>{u.kb("ThresholdedRelu",l,{alpha:m})},877186:(l,m)=>{u.kb("Cast",l,{to:m})},877244:l=>{u.kb("Add",l,void 0)},877295:l=>{u.kb("Sub",l,void 0)},877346:l=>{u.kb("Mul",l,void 0)},877397:l=>{u.kb("Div",l,void 0)},877448:l=>{u.kb("Pow",l,void 0)},877499:l=>{u.kb("Equal",l,void 0)},877552:l=>{u.kb("Greater",l,void 0)},877607:l=>{u.kb("GreaterOrEqual",l,void 0)},877669:l=>{u.kb("Less",l,void 0)},877721:l=>{u.kb("LessOrEqual",l,void 0)},877780:(l,m,E,I,G)=>{u.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},877955:(l,m,E,I,G)=>{u.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878129:(l,m,E,I,G)=>{u.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878303:(l,m,E,I,G)=>{u.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878478:(l,m,E,I,G)=>{u.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878652:(l,m,E,I,G)=>{u.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878825:(l,m,E,I,G)=>{u.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878998:(l,m,E,I,G)=>{u.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},879175:(l,m,E,I,G)=>{u.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},879355:(l,m,E,I,G)=>{u.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},879535:l=>{u.kb("Where",l,void 0)},879588:(l,m,E)=>{u.kb("Transpose",l,{perm:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},879712:(l,m,E,I)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:zs(E),format:I?"NHWC":"NCHW"})},879845:(l,m,E,I)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:zs(E),format:I?"NHWC":"NCHW"})},879978:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We,as)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:I,kernelShape:[G],pads:[we,Ke],strides:[tt],wIsConst:()=>!!s()[kt>>>0],outputPadding:Vt?Array.from(i().subarray(Number(Vt)>>>0,Number(ps)>>>0)):[],outputShape:Ms?Array.from(i().subarray(Number(Ms)>>>0,Number(We)>>>0)):[],activation:zs(as)})},880411:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We)=>{u.kb("ConvTranspose",l,{format:tt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:I,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!s()[bt>>>0],outputPadding:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],outputShape:ps?Array.from(i().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[],activation:zs(We)})},881072:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We,as)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:I,kernelShape:[G],pads:[we,Ke],strides:[tt],wIsConst:()=>!!s()[kt>>>0],outputPadding:Vt?Array.from(i().subarray(Number(Vt)>>>0,Number(ps)>>>0)):[],outputShape:Ms?Array.from(i().subarray(Number(Ms)>>>0,Number(We)>>>0)):[],activation:zs(as)})},881505:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We)=>{u.kb("ConvTranspose",l,{format:tt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:I,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!s()[bt>>>0],outputPadding:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],outputShape:ps?Array.from(i().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[],activation:zs(We)})},882166:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882257:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We)=>{u.kb("AveragePool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],strides:ps?Array.from(i().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},882736:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882827:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We)=>{u.kb("AveragePool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],strides:ps?Array.from(i().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},883306:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883393:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We)=>{u.kb("MaxPool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],strides:ps?Array.from(i().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},883868:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883955:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We)=>{u.kb("MaxPool",l,{format:We?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],strides:ps?Array.from(i().subarray(Number(ps)>>>0,Number(Ms)>>>0)):[]})},884430:(l,m,E,I,G)=>{u.kb("Gemm",l,{alpha:m,beta:E,transA:I,transB:G})},884534:l=>{u.kb("MatMul",l,void 0)},884588:(l,m,E,I)=>{u.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:I})},884696:(l,m,E,I)=>{u.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:I})},884804:(l,m)=>{u.kb("Softmax",l,{axis:m})},884867:(l,m)=>{u.kb("Concat",l,{axis:m})},884927:(l,m,E,I,G)=>{u.kb("Split",l,{axis:m,numOutputs:E,splitSizes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},885083:l=>{u.kb("Expand",l,void 0)},885137:(l,m)=>{u.kb("Gather",l,{axis:Number(m)})},885208:(l,m)=>{u.kb("GatherElements",l,{axis:Number(m)})},885287:(l,m)=>{u.kb("GatherND",l,{batch_dims:Number(m)})},885366:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt)=>{u.kb("Resize",l,{antialias:m,axes:E?Array.from(i().subarray(Number(E)>>>0,Number(I)>>>0)):[],coordinateTransformMode:zs(G),cubicCoeffA:we,excludeOutside:Ke,extrapolationValue:tt,keepAspectRatioPolicy:zs(bt),mode:zs(kt),nearestMode:zs(Vt)})},885728:(l,m,E,I,G,we,Ke)=>{u.kb("Slice",l,{starts:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[],axes:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[]})},885992:l=>{u.kb("Tile",l,void 0)},886044:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886158:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886272:l=>{u.kb("Range",l,void 0)},886325:(l,m)=>{u.kb("Einsum",l,{equation:zs(m)})},886406:(l,m,E,I,G)=>{u.kb("Pad",l,{mode:m,value:E,pads:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},886549:(l,m,E,I,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!I,format:we?"NHWC":"NCHW"})},886718:(l,m,E,I,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!I,format:we?"NHWC":"NCHW"})},886887:(l,m,E)=>{u.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},886984:(l,m,E)=>{u.kb("DequantizeLinear",l,{axis:m,blockSize:E})},887074:(l,m,E,I,G)=>{u.kb("GridSample",l,{align_corners:m,mode:zs(E),padding_mode:zs(I),format:G?"NHWC":"NCHW"})},887244:(l,m,E,I,G)=>{u.kb("GridSample",l,{align_corners:m,mode:zs(E),padding_mode:zs(I),format:G?"NHWC":"NCHW"})},887414:(l,m)=>{u.kb("ScatterND",l,{reduction:zs(m)})},887499:(l,m,E,I,G,we,Ke,tt,bt)=>{u.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:I,scale:G,doRotary:we,qkvHiddenSizes:Ke?Array.from(i().subarray(Number(tt)>>>0,Number(tt)+Ke>>>0)):[],pastPresentShareBuffer:!!bt})},887771:l=>{u.kb("BiasAdd",l,void 0)},887826:l=>{u.kb("BiasSplitGelu",l,void 0)},887887:l=>{u.kb("FastGelu",l,void 0)},887943:(l,m,E,I,G,we,Ke,tt,bt,kt,Vt,ps,Ms,We,as,Bs)=>{u.kb("Conv",l,{format:ps?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(i().subarray(Number(E)>>>0,Number(I)>>>0)):[],group:G,kernel_shape:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],pads:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Vt)>>>0)):[],w_is_const:()=>!!s()[Number(Ms)>>>0],activation:zs(We),activation_params:as?Array.from(p().subarray(Number(as)>>>0,Number(Bs)>>>0)):[]})},888527:l=>{u.kb("Gelu",l,void 0)},888579:(l,m,E,I,G,we,Ke,tt,bt)=>{u.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:I,softcap:G,doRotary:we,rotaryInterleaved:Ke,smoothSoftmax:tt,localWindowSize:bt})},888796:(l,m,E,I)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!I})},888907:(l,m,E,I)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!I})},889018:(l,m,E,I,G,we)=>{u.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:I,bits:G,blockSize:we})},889145:(l,m,E,I,G,we)=>{u.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:I,scale:G,doRotary:we})},889304:(l,m)=>{u.kb("QuickGelu",l,{alpha:m})},889368:(l,m,E,I,G)=>{u.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:I,scale:G})},889507:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889609:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889711:(l,m,E,I)=>{u.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:I})},889832:l=>{u.$b(l)},889866:(l,m)=>u.cc(Number(l),Number(m),u.Gb.hc,u.Gb.errors)};function p_(l,m,E){return gm(async()=>{await u.Yb(Number(l),Number(m),Number(E))})}function h_(){return typeof wasmOffsetConverter<"u"}function Yp(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var Jp=l=>{l.terminate(),l.onmessage=()=>{}},Bh=l=>{Hn.length==0&&(Vh(),Wh(Hn[0]));var m=Hn.pop();if(!m)return 6;Bo.push(m),pn[l.Bb]=m,m.Bb=l.Bb;var E={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(E,l.nc),0},zo=0,Os=(l,m,...E)=>{for(var I=2*E.length,G=fh(),we=_h(8*I),Ke=we>>>3,tt=0;tt>>0]=bt)}return l=jm(l,0,I,we,m),$p(G),l};function Zp(l){if(Z)return Os(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw Rh(l),"unwind";Zp(l)},Hn=[],Bo=[],Nh=[],pn={},jh=l=>{var m=l.Bb;delete pn[m],Hn.push(l),Bo.splice(Bo.indexOf(l),1),l.Bb=0,mh(m)};function Uh(){Nh.forEach(l=>l())}var Wh=l=>new Promise(m=>{l.onmessage=G=>{var we=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Ma()){var Ke=pn[G.targetThread];Ke?Ke.postMessage(G,G.transferList):Ct(`Internal error! Worker sent a message "${we}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else we==="checkMailbox"?yp():we==="spawnThread"?Bh(G):we==="cleanupThread"?jh(pn[G.thread]):we==="killThread"?(G=G.thread,we=pn[G],delete pn[G],Jp(we),mh(G),Bo.splice(Bo.indexOf(we),1),we.Bb=0):we==="cancelThread"?pn[G.thread].postMessage({cmd:"cancel"}):we==="loaded"?(l.loaded=!0,m(l)):we==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):we==="callHandler"?u[G.handler](...G.args):we&&Ct(`worker sent an unknown command ${we}`)},l.onerror=G=>{throw Ct(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var E,I=[];for(E of[])u.hasOwnProperty(E)&&I.push(E);l.postMessage({cmd:"load",handlers:I,wasmMemory:jt,wasmModule:vs})});function Vh(){var l=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Hn.push(l)}var wp=l=>{for(;0{var l=Ma(),m=d()[l+52>>>2>>>0];l=d()[l+56>>>2>>>0],Wm(m,m-l),$p(m)},__=(l,m)=>{zo=0,l=Vm(l,m),0>>=0);throw m>>>=0,E>>>=0,d()[I.Kb+16>>>2>>>0]=0,d()[I.Kb+4>>>2>>>0]=m,d()[I.Kb+8>>>2>>>0]=E,l}function Gh(l,m,E,I){return Z?Os(2,1,l,m,E,I):Kh(l,m,E,I)}function Kh(l,m,E,I){if(l>>>=0,m>>>=0,E>>>=0,I>>>=0,te===void 0)return Ct("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?Gh(l,m,E,I):(l={ic:E,Bb:l,Rb:I,nc:G},Z?(l.Nb="spawnThread",postMessage(l,G),0):Bh(l))}var Hh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,qh=(l,m,E)=>{var I=(m>>>=0)+E;for(E=m;l[E]&&!(E>=I);)++E;if(16(G=(240&G)==224?(15&G)<<12|we<<6|Ke:(7&G)<<18|we<<12|Ke<<6|63&l[m++])?I+=String.fromCharCode(G):(G-=65536,I+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else I+=String.fromCharCode(G)}return I},zs=(l,m)=>(l>>>=0)?qh(n(),l,m):"";function Xh(l,m,E){return Z?Os(3,1,l,m,E):0}function Qh(l,m){if(Z)return Os(4,1,l,m)}var th=l=>{for(var m=0,E=0;E=I?m++:2047>=I?m+=2:55296<=I&&57343>=I?(m+=4,++E):m+=3}return m},Yh=(l,m,E,I)=>{if(!(0>>=0;I=E+I-1;for(var we=0;we=Ke&&(Ke=65536+((1023&Ke)<<10)|1023&l.charCodeAt(++we)),127>=Ke){if(E>=I)break;m[E++>>>0]=Ke}else{if(2047>=Ke){if(E+1>=I)break;m[E++>>>0]=192|Ke>>6}else{if(65535>=Ke){if(E+2>=I)break;m[E++>>>0]=224|Ke>>12}else{if(E+3>=I)break;m[E++>>>0]=240|Ke>>18,m[E++>>>0]=128|Ke>>12&63}m[E++>>>0]=128|Ke>>6&63}m[E++>>>0]=128|63&Ke}}return m[E>>>0]=0,E-G},wa=(l,m,E)=>Yh(l,n(),m,E);function Jh(l,m){if(Z)return Os(5,1,l,m)}function Zh(l,m,E){if(Z)return Os(6,1,l,m,E)}function em(l,m,E){return Z?Os(7,1,l,m,E):0}function tm(l,m){if(Z)return Os(8,1,l,m)}function sm(l,m,E){if(Z)return Os(9,1,l,m,E)}function rm(l,m,E,I){if(Z)return Os(10,1,l,m,E,I)}function nm(l,m,E,I){if(Z)return Os(11,1,l,m,E,I)}function om(l,m,E,I){if(Z)return Os(12,1,l,m,E,I)}function im(l){if(Z)return Os(13,1,l)}function am(l,m){if(Z)return Os(14,1,l,m)}function lm(l,m,E){if(Z)return Os(15,1,l,m,E)}var um,qn,w_=()=>{Kn("")},hn=l=>{for(var m="";n()[l>>>0];)m+=um[n()[l++>>>0]];return m},sh={},rh={};function Pn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(I,G,we={}){var Ke=G.name;if(!I)throw new qn(`type "${Ke}" must have a positive integer typeid pointer`);if(rh.hasOwnProperty(I)){if(we.Tb)return;throw new qn(`Cannot register type '${Ke}' twice`)}rh[I]=G,sh.hasOwnProperty(I)&&(G=sh[I],delete sh[I],G.forEach(tt=>tt()))}(l,m,E)}var dm=(l,m,E)=>{switch(m){case 1:return E?I=>s()[I>>>0]:I=>n()[I>>>0];case 2:return E?I=>o()[I>>>1>>>0]:I=>a()[I>>>1>>>0];case 4:return E?I=>i()[I>>>2>>>0]:I=>d()[I>>>2>>>0];case 8:return E?I=>Hs[I>>>3]:I=>cn[I>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function y_(l,m,E){E>>>=0,Pn(l>>>=0,{name:m=hn(m>>>0),fromWireType:I=>I,toWireType:function(I,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(I=typeof G)=="object"||I==="array"||I==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:Xn,readValueFromPointer:dm(m,E,m.indexOf("u")==-1),Eb:null})}var Xn=8;function M_(l,m,E,I){Pn(l>>>=0,{name:m=hn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,we){return we?E:I},argPackAdvance:Xn,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var nh=[],Cn=[];function oh(l){9<(l>>>=0)&&--Cn[l+1]==0&&(Cn[l]=void 0,nh.push(l))}var kr=l=>{if(!l)throw new qn("Cannot use deleted val. handle = "+l);return Cn[l]},zr=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=nh.pop()||Cn.length;return Cn[m]=l,Cn[m+1]=1,m}};function ih(l){return this.fromWireType(d()[l>>>2>>>0])}var b_={name:"emscripten::val",fromWireType:l=>{var m=kr(l);return oh(l),m},toWireType:(l,m)=>zr(m),argPackAdvance:Xn,readValueFromPointer:ih,Eb:null};function v_(l){return Pn(l>>>0,b_)}var T_=(l,m)=>{switch(m){case 4:return function(E){return this.fromWireType(p()[E>>>2>>>0])};case 8:return function(E){return this.fromWireType(h()[E>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function x_(l,m,E){E>>>=0,Pn(l>>>=0,{name:m=hn(m>>>0),fromWireType:I=>I,toWireType:(I,G)=>G,argPackAdvance:Xn,readValueFromPointer:T_(m,E),Eb:null})}function E_(l,m,E,I,G){if(l>>>=0,E>>>=0,m=hn(m>>>0),G===-1&&(G=4294967295),G=tt=>tt,I===0){var we=32-8*E;G=tt=>tt<>>we}var Ke=m.includes("unsigned")?function(tt,bt){return bt>>>0}:function(tt,bt){return bt};Pn(l,{name:m,fromWireType:G,toWireType:Ke,argPackAdvance:Xn,readValueFromPointer:dm(m,E,I!==0),Eb:null})}function P_(l,m,E){function I(we){var Ke=d()[we>>>2>>>0];return we=d()[we+4>>>2>>>0],new G(s().buffer,we,Ke)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Pn(l>>>=0,{name:E=hn(E>>>0),fromWireType:I,argPackAdvance:Xn,readValueFromPointer:I},{Tb:!0})}function C_(l,m){l>>>=0;var E=(m=hn(m>>>0))==="std::string";Pn(l,{name:m,fromWireType:function(I){var G=d()[I>>>2>>>0],we=I+4;if(E)for(var Ke=we,tt=0;tt<=G;++tt){var bt=we+tt;if(tt==G||n()[bt>>>0]==0){if(Ke=zs(Ke,bt-Ke),kt===void 0)var kt=Ke;else kt+="\0",kt+=Ke;Ke=bt+1}}else{for(kt=Array(G),tt=0;tt>>0]);kt=kt.join("")}return _n(I),kt},toWireType:function(I,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var we=typeof G=="string";if(!(we||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new qn("Cannot pass non-string to std::string");var Ke=E&&we?th(G):G.length,tt=kp(4+Ke+1),bt=tt+4;if(d()[tt>>>2>>>0]=Ke,E&&we)wa(G,bt,Ke+1);else if(we)for(we=0;we>>0]=kt}else for(we=0;we>>0]=G[we];return I!==null&&I.push(_n,tt),tt},argPackAdvance:Xn,readValueFromPointer:ih,Eb(I){_n(I)}})}var cm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,k_=(l,m)=>{for(var E=l>>1,I=E+m/2;!(E>=I)&&a()[E>>>0];)++E;if(32<(E<<=1)-l&&cm)return cm.decode(n().slice(l,E));for(E="",I=0;!(I>=m/2);++I){var G=o()[l+2*I>>>1>>>0];if(G==0)break;E+=String.fromCharCode(G)}return E},S_=(l,m,E)=>{if(E??(E=2147483647),2>E)return 0;var I=m;E=(E-=2)<2*l.length?E/2:l.length;for(var G=0;G>>1>>>0]=we,m+=2}return o()[m>>>1>>>0]=0,m-I},$_=l=>2*l.length,A_=(l,m)=>{for(var E=0,I="";!(E>=m/4);){var G=i()[l+4*E>>>2>>>0];if(G==0)break;++E,65536<=G?(G-=65536,I+=String.fromCharCode(55296|G>>10,56320|1023&G)):I+=String.fromCharCode(G)}return I},I_=(l,m,E)=>{if(m>>>=0,E??(E=2147483647),4>E)return 0;var I=m;E=I+E-4;for(var G=0;G=we&&(we=65536+((1023&we)<<10)|1023&l.charCodeAt(++G)),i()[m>>>2>>>0]=we,(m+=4)+4>E)break}return i()[m>>>2>>>0]=0,m-I},O_=l=>{for(var m=0,E=0;E=I&&++E,m+=4}return m};function F_(l,m,E){if(l>>>=0,m>>>=0,E=hn(E>>>=0),m===2)var I=k_,G=S_,we=$_,Ke=tt=>a()[tt>>>1>>>0];else m===4&&(I=A_,G=I_,we=O_,Ke=tt=>d()[tt>>>2>>>0]);Pn(l,{name:E,fromWireType:tt=>{for(var bt,kt=d()[tt>>>2>>>0],Vt=tt+4,ps=0;ps<=kt;++ps){var Ms=tt+4+ps*m;ps!=kt&&Ke(Ms)!=0||(Vt=I(Vt,Ms-Vt),bt===void 0?bt=Vt:(bt+="\0",bt+=Vt),Vt=Ms+m)}return _n(tt),bt},toWireType:(tt,bt)=>{if(typeof bt!="string")throw new qn(`Cannot pass non-string to C++ string type ${E}`);var kt=we(bt),Vt=kp(4+kt+m);return d()[Vt>>>2>>>0]=kt/m,G(bt,Vt+4,kt+m),tt!==null&&tt.push(_n,Vt),Vt},argPackAdvance:Xn,readValueFromPointer:ih,Eb(tt){_n(tt)}})}function D_(l,m){Pn(l>>>=0,{Ub:!0,name:m=hn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var L_=()=>1;function z_(l){hh(l>>>0,!j,1,!R,131072,!1),Uh()}var pm=l=>{if(!Is)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(i(),l>>>2,l).value.then(yp),l+=128,Atomics.store(i(),l>>>2,1))}var yp=()=>{var l=Ma();l&&(ah(l),pm(Um))};function B_(l,m){(l>>>=0)==m>>>0?setTimeout(yp):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=pn[l])&&l.postMessage({cmd:"checkMailbox"})}var lh=[];function R_(l,m,E,I,G){for(m>>>=0,I/=2,lh.length=I,E=G>>>0>>>3,G=0;G>>0];return(m?Qp[m]:$f[l])(...lh)}function N_(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):jh(pn[l])}function j_(l){}var Mp=(l,m)=>{var E=rh[l];if(E===void 0)throw l=Bm(l),E=hn(l),_n(l),new qn(`${m} has unknown type ${E}`);return E},hm=(l,m,E)=>{var I=[];return l=l.toWireType(I,E),I.length&&(d()[m>>>2>>>0]=zr(I)),l};function U_(l,m,E){return m>>>=0,E>>>=0,l=kr(l>>>0),m=Mp(m,"emval::as"),hm(m,E,l)}function W_(l,m){return m>>>=0,l=kr(l>>>0),(m=Mp(m,"emval::as")).toWireType(null,l)}var bp=l=>{try{l()}catch(m){Kn(m)}},Qn=0,mn=null,mm=0,vp=[],_m={},fm={},V_=0,uh=null,G_=[];function gm(l){return function(m){if(!Is){if(Qn===0){var E=!1,I=!1;m((G=0)=>{if(!Is&&(mm=G,E=!0,I)){Qn=2,bp(()=>Hm(mn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var we=function(){var bt=i()[mn+8>>>2>>>0];return bt=Rt[fm[bt]],--zo,bt()}()}catch(bt){we=bt,G=!0}var Ke=!1;if(!mn){var tt=uh;tt&&(uh=null,(G?tt.reject:tt.resolve)(we),Ke=!0)}if(G&&!Ke)throw we}}),I=!0,E||(Qn=1,mn=function(){var G=kp(65548),we=G+12;d()[G>>>2>>>0]=we,d()[G+4>>>2>>>0]=we+65536,we=vp[0];var Ke=_m[we];return Ke===void 0&&(Ke=V_++,_m[we]=Ke,fm[Ke]=we),we=Ke,i()[G+8>>>2>>>0]=we,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),bp(()=>Gm(mn)))}else Qn===2?(Qn=0,bp(qm),_n(mn),mn=null,G_.forEach(pm)):Kn(`invalid state: ${Qn}`);return mm}}(m=>{l().then(m)})}function K_(l){return l>>>=0,gm(()=>(l=kr(l)).then(zr))}var Tp=[];function H_(l,m,E,I){return E>>>=0,I>>>=0,(l=Tp[l>>>0])(null,m=kr(m>>>0),E,I)}var q_={},xp=l=>{var m=q_[l];return m===void 0?hn(l):m};function X_(l,m,E,I,G){return E>>>=0,I>>>=0,G>>>=0,(l=Tp[l>>>0])(m=kr(m>>>0),m[E=xp(E)],I,G)}var wm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Q_(l){return(l>>>=0)==0?zr(wm()):(l=xp(l),zr(wm()[l]))}var Y_=l=>{var m=Tp.length;return Tp.push(l),m},J_=(l,m)=>{for(var E=Array(l),I=0;I>>2>>>0],"parameter "+I);return E},ym=(l,m)=>Object.defineProperty(m,"name",{value:l});function Z_(l,m,E){var I=(m=J_(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { `,we=0,Ke=[];E===0&&Ke.push("obj");for(var tt=["retType"],bt=[I],kt=0;ktVt.name).join(", ")}) => ${I.name}>`,Y_(ym(E,l))}function ef(l){return l=xp(l>>>0),zr(u[l])}function tf(l,m){return m>>>=0,l=kr(l>>>0),m=kr(m),zr(l[m])}function sf(l){9<(l>>>=0)&&(Cn[l+1]+=1)}function rf(){return zr([])}function nf(l){l=kr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function af(){return zr({})}function lf(l){for(var m=kr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}oh(l)}function uf(l,m,E){m>>>=0,E>>>=0,l=kr(l>>>0),m=kr(m),E=kr(E),l[m]=E}function df(l,m){return m>>>=0,l=(l=Mp(l>>>0,"_emval_take_value")).readValueFromPointer(m),zr(l)}function cf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getUTCSeconds(),i()[m+4>>>2>>>0]=l.getUTCMinutes(),i()[m+8>>>2>>>0]=l.getUTCHours(),i()[m+12>>>2>>>0]=l.getUTCDate(),i()[m+16>>>2>>>0]=l.getUTCMonth(),i()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,i()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[m+28>>>2>>>0]=l}var ya=l=>l%4==0&&(l%100!=0||l%400==0),Mm=[0,31,60,91,121,152,182,213,244,274,305,335],bm=[0,31,59,90,120,151,181,212,243,273,304,334];function pf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getSeconds(),i()[m+4>>>2>>>0]=l.getMinutes(),i()[m+8>>>2>>>0]=l.getHours(),i()[m+12>>>2>>>0]=l.getDate(),i()[m+16>>>2>>>0]=l.getMonth(),i()[m+20>>>2>>>0]=l.getFullYear()-1900,i()[m+24>>>2>>>0]=l.getDay();var E=(ya(l.getFullYear())?Mm:bm)[l.getMonth()]+l.getDate()-1|0;i()[m+28>>>2>>>0]=E,i()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var I=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=I&&l.getTimezoneOffset()==Math.min(I,E)),i()[m+32>>>2>>>0]=l}function hf(l){l>>>=0;var m=new Date(i()[l+20>>>2>>>0]+1900,i()[l+16>>>2>>>0],i()[l+12>>>2>>>0],i()[l+8>>>2>>>0],i()[l+4>>>2>>>0],i()[l>>>2>>>0],0),E=i()[l+32>>>2>>>0],I=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),we=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ke=Math.min(we,G);return 0>E?i()[l+32>>>2>>>0]=+(G!=we&&Ke==I):0>>2>>>0]=m.getDay(),E=(ya(m.getFullYear())?Mm:bm)[m.getMonth()]+m.getDate()-1|0,i()[l+28>>>2>>>0]=E,i()[l>>>2>>>0]=m.getSeconds(),i()[l+4>>>2>>>0]=m.getMinutes(),i()[l+8>>>2>>>0]=m.getHours(),i()[l+12>>>2>>>0]=m.getDate(),i()[l+16>>>2>>>0]=m.getMonth(),i()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function vm(l,m,E,I,G,we,Ke){return Z?Os(16,1,l,m,E,I,G,we,Ke):-52}function Tm(l,m,E,I,G,we){if(Z)return Os(17,1,l,m,E,I,G,we)}function mf(l,m,E,I){l>>>=0,m>>>=0,E>>>=0,I>>>=0;var G=new Date().getFullYear(),we=new Date(G,0,1),Ke=new Date(G,6,1);G=we.getTimezoneOffset();var tt=Ke.getTimezoneOffset(),bt=Math.max(G,tt);d()[l>>>2>>>0]=60*bt,i()[m>>>2>>>0]=+(G!=tt),we=(l=kt=>kt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(we),Ke=l(Ke),tt{dh.length=0;for(var E;E=n()[l++>>>0];){var I=E!=105;m+=(I&=E!=112)&&m%8?4:0,dh.push(E==112?d()[m>>>2>>>0]:E==106?Hs[m>>>3]:E==105?i()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=I?8:4}return dh};function _f(l,m,E){return l>>>=0,m=xm(m>>>0,E>>>0),Qp[l](...m)}function ff(l,m,E){return l>>>=0,m=xm(m>>>0,E>>>0),Qp[l](...m)}var gf=()=>{},wf=()=>Date.now();function yf(l,m){return Ct(zs(l>>>0,m>>>0))}var Em,Mf=()=>{throw zo+=1,"unwind"};function bf(){return 4294901760}Em=()=>performance.timeOrigin+performance.now();var vf=()=>navigator.hardwareConcurrency;function Tf(){return Kn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function xf(l){l>>>=0;var m=n().length;if(l<=m||4294901760=E;E*=2){var I=m*(1+.2/E);I=Math.min(I,l+100663296);var G=Math;I=Math.max(l,I);e:{G=(G.min.call(G,4294901760,I+(65536-I%65536)%65536)-jt.buffer.byteLength+65535)/65536;try{jt.grow(G),Es();var we=1;break e}catch{}we=void 0}if(we)return!0}return!1}var Ep=()=>(Kn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Pc={},Pm=l=>{l.forEach(m=>{Ep()})};function Ef(){var l=Error().stack.toString().split(` `);return l[0]=="Error"&&l.shift(),Pm(l),Pc.Qb=Ep(),Pc.fc=l,Pc.Qb}function Pf(l,m,E){if(l>>>=0,m>>>=0,Pc.Qb==l)var I=Pc.fc;else(I=Error().stack.toString().split(` `))[0]=="Error"&&I.shift(),Pm(I);for(var G=3;I[G]&&Ep()!=l;)++G;for(l=0;l>>2>>>0]=Ep();return l}var ch,ph={},Cm=()=>{if(!ch){var l,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:$e};for(l in ph)ph[l]===void 0?delete m[l]:m[l]=ph[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);ch=E}return ch};function km(l,m){if(Z)return Os(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Cm().forEach((I,G)=>{var we=m+E;for(G=d()[l+4*G>>>2>>>0]=we,we=0;we>>0]=I.charCodeAt(we);s()[G>>>0]=0,E+=I.length+1}),0}function Sm(l,m){if(Z)return Os(19,1,l,m);l>>>=0,m>>>=0;var E=Cm();d()[l>>>2>>>0]=E.length;var I=0;return E.forEach(G=>I+=G.length+1),d()[m>>>2>>>0]=I,0}function $m(l){return Z?Os(20,1,l):52}function Am(l,m,E,I){return Z?Os(21,1,l,m,E,I):52}function Im(l,m,E,I){return Z?Os(22,1,l,m,E,I):70}var Cf=[null,[],[]];function Om(l,m,E,I){if(Z)return Os(23,1,l,m,E,I);m>>>=0,E>>>=0,I>>>=0;for(var G=0,we=0;we>>2>>>0],tt=d()[m+4>>>2>>>0];m+=8;for(var bt=0;bt>>0],Vt=Cf[l];kt===0||kt===10?((l===1?Yt:Ct)(qh(Vt,0)),Vt.length=0):Vt.push(kt)}G+=tt}return d()[I>>>2>>>0]=G,0}var Fm=[31,29,31,30,31,30,31,31,30,31,30,31],Dm=[31,28,31,30,31,30,31,31,30,31,30,31],kf=(l,m)=>{s().set(l,m>>>0)};function Lm(l,m,E,I){function G(We,as,Bs){for(We=typeof We=="number"?We.toString():We||"";We.lengthQm?-1:0Ro-We.getDate())){We.setDate(We.getDate()+as);break}as-=Ro-We.getDate()+1,We.setDate(1),11>Bs?We.setMonth(Bs+1):(We.setMonth(0),We.setFullYear(We.getFullYear()+1))}return Bs=new Date(We.getFullYear()+1,0,4),as=tt(new Date(We.getFullYear(),0,4)),Bs=tt(Bs),0>=Ke(as,We)?0>=Ke(Bs,We)?We.getFullYear()+1:We.getFullYear():We.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,I>>>=0;var kt=d()[I+40>>>2>>>0];for(var Vt in I={lc:i()[I>>>2>>>0],kc:i()[I+4>>>2>>>0],Ib:i()[I+8>>>2>>>0],Mb:i()[I+12>>>2>>>0],Jb:i()[I+16>>>2>>>0],Db:i()[I+20>>>2>>>0],vb:i()[I+24>>>2>>>0],Cb:i()[I+28>>>2>>>0],sc:i()[I+32>>>2>>>0],jc:i()[I+36>>>2>>>0],mc:kt?zs(kt):""},E=zs(E),kt={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})E=E.replace(new RegExp(Vt,"g"),kt[Vt]);var ps="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ms="January February March April May June July August September October November December".split(" ");for(Vt in kt={"%a":We=>ps[We.vb].substring(0,3),"%A":We=>ps[We.vb],"%b":We=>Ms[We.Jb].substring(0,3),"%B":We=>Ms[We.Jb],"%C":We=>we((We.Db+1900)/100|0,2),"%d":We=>we(We.Mb,2),"%e":We=>G(We.Mb,2," "),"%g":We=>bt(We).toString().substring(2),"%G":bt,"%H":We=>we(We.Ib,2),"%I":We=>((We=We.Ib)==0?We=12:12{for(var as=0,Bs=0;Bs<=We.Jb-1;as+=(ya(We.Db+1900)?Fm:Dm)[Bs++]);return we(We.Mb+as,3)},"%m":We=>we(We.Jb+1,2),"%M":We=>we(We.kc,2),"%n":()=>` `,"%p":We=>0<=We.Ib&&12>We.Ib?"AM":"PM","%S":We=>we(We.lc,2),"%t":()=>" ","%u":We=>We.vb||7,"%U":We=>we(Math.floor((We.Cb+7-We.vb)/7),2),"%V":We=>{var as=Math.floor((We.Cb+7-(We.vb+6)%7)/7);if(2>=(We.vb+371-We.Cb-2)%7&&as++,as)as==53&&((Bs=(We.vb+371-We.Cb)%7)==4||Bs==3&&ya(We.Db)||(as=1));else{as=52;var Bs=(We.vb+7-We.Cb-1)%7;(Bs==4||Bs==5&&ya(We.Db%400-1))&&as++}return we(as,2)},"%w":We=>We.vb,"%W":We=>we(Math.floor((We.Cb+7-(We.vb+6)%7)/7),2),"%y":We=>(We.Db+1900).toString().substring(2),"%Y":We=>We.Db+1900,"%z":We=>{var as=0<=(We=We.jc);return We=Math.abs(We)/60,(as?"+":"-")+("0000"+(We/60*100+We%60)).slice(-4)},"%Z":We=>We.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),kt)E.includes(Vt)&&(E=E.replace(new RegExp(Vt,"g"),kt[Vt](I)));return Vt=function(We){var as=Array(th(We)+1);return Yh(We,as,0,as.length),as}(E=E.replace(/\0\0/g,"%")),Vt.length>m?0:(kf(Vt,l),Vt.length-1)}function Sf(l,m,E,I){return Lm(l>>>0,m>>>0,E>>>0,I>>>0)}Z||function(){for(var l=u.numThreads-1;l--;)Vh();Gn.unshift(()=>{xc++,function(m){Z?m():Promise.all(Hn.map(Wh)).then(m)}(()=>Ih())})}();for(var zm=Array(256),Pp=0;256>Pp;++Pp)zm[Pp]=String.fromCharCode(Pp);um=zm,qn=u.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},u.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},Cn.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>Cn.length/2-5-nh.length;var $f=[Zp,Rh,Gh,Xh,Qh,Jh,Zh,em,tm,sm,rm,nm,om,im,am,lm,vm,Tm,km,Sm,$m,Am,Im,Om],Rt=function(){function l(E,I){return Rt=E.exports,Rt=function(){var G=Rt,we={};for(let[Ke,tt]of Object.entries(G))we[Ke]=typeof tt=="function"?(...bt)=>{vp.push(Ke);try{return tt(...bt)}finally{Is||(vp.pop(),mn&&Qn===1&&vp.length===0&&(Qn=0,zo+=1,bp(Km),typeof Fibers<"u"&&Fibers.tc()))}}:tt;return we}(),Rt=function(){var G=Rt,we=tt=>bt=>tt(bt)>>>0,Ke=tt=>()=>tt()>>>0;return(G=Object.assign({},G)).Da=we(G.Da),G.gb=Ke(G.gb),G.ib=we(G.ib),G.emscripten_main_runtime_thread_id=Ke(G.emscripten_main_runtime_thread_id),G.tb=we(G.tb),G.ub=Ke(G.ub),G}(),Nh.push(Rt.jb),Tc.unshift(Rt.Ca),vs=I,Ih(),Rt}var m=zh();if(xc++,u.instantiateWasm)try{return u.instantiateWasm(m,l)}catch(E){Ct(`Module.instantiateWasm callback failed with error: ${E}`),S(E)}return Xp||(Xp=u.locateFile?Oh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ge):Ge+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(E,I){var G=Xp;return lt||typeof WebAssembly.instantiateStreaming!="function"||Oh(G)||Fh(G)||typeof fetch!="function"?Lh(G,E,I):fetch(G,{credentials:"same-origin"}).then(we=>WebAssembly.instantiateStreaming(we,E).then(I,function(Ke){return Ct(`wasm streaming compile failed: ${Ke}`),Ct("falling back to ArrayBuffer instantiation"),Lh(G,E,I)}))}(m,function(E){l(E.instance,E.module)}).catch(S),{}}(),Bm=l=>(Bm=Rt.Da)(l),Rm=()=>(Rm=Rt.Ea)();u._OrtInit=(l,m)=>(u._OrtInit=Rt.Fa)(l,m),u._OrtGetLastError=(l,m)=>(u._OrtGetLastError=Rt.Ga)(l,m),u._OrtCreateSessionOptions=(l,m,E,I,G,we,Ke,tt,bt,kt)=>(u._OrtCreateSessionOptions=Rt.Ha)(l,m,E,I,G,we,Ke,tt,bt,kt),u._OrtAppendExecutionProvider=(l,m)=>(u._OrtAppendExecutionProvider=Rt.Ia)(l,m),u._OrtAddFreeDimensionOverride=(l,m,E)=>(u._OrtAddFreeDimensionOverride=Rt.Ja)(l,m,E),u._OrtAddSessionConfigEntry=(l,m,E)=>(u._OrtAddSessionConfigEntry=Rt.Ka)(l,m,E),u._OrtReleaseSessionOptions=l=>(u._OrtReleaseSessionOptions=Rt.La)(l),u._OrtCreateSession=(l,m,E)=>(u._OrtCreateSession=Rt.Ma)(l,m,E),u._OrtReleaseSession=l=>(u._OrtReleaseSession=Rt.Na)(l),u._OrtGetInputOutputCount=(l,m,E)=>(u._OrtGetInputOutputCount=Rt.Oa)(l,m,E),u._OrtGetInputName=(l,m)=>(u._OrtGetInputName=Rt.Pa)(l,m),u._OrtGetOutputName=(l,m)=>(u._OrtGetOutputName=Rt.Qa)(l,m),u._OrtFree=l=>(u._OrtFree=Rt.Ra)(l),u._OrtCreateTensor=(l,m,E,I,G,we)=>(u._OrtCreateTensor=Rt.Sa)(l,m,E,I,G,we),u._OrtGetTensorData=(l,m,E,I,G)=>(u._OrtGetTensorData=Rt.Ta)(l,m,E,I,G),u._OrtReleaseTensor=l=>(u._OrtReleaseTensor=Rt.Ua)(l),u._OrtCreateRunOptions=(l,m,E,I)=>(u._OrtCreateRunOptions=Rt.Va)(l,m,E,I),u._OrtAddRunConfigEntry=(l,m,E)=>(u._OrtAddRunConfigEntry=Rt.Wa)(l,m,E),u._OrtReleaseRunOptions=l=>(u._OrtReleaseRunOptions=Rt.Xa)(l),u._OrtCreateBinding=l=>(u._OrtCreateBinding=Rt.Ya)(l),u._OrtBindInput=(l,m,E)=>(u._OrtBindInput=Rt.Za)(l,m,E),u._OrtBindOutput=(l,m,E,I)=>(u._OrtBindOutput=Rt._a)(l,m,E,I),u._OrtClearBoundOutputs=l=>(u._OrtClearBoundOutputs=Rt.$a)(l),u._OrtReleaseBinding=l=>(u._OrtReleaseBinding=Rt.ab)(l),u._OrtRunWithBinding=(l,m,E,I,G)=>(u._OrtRunWithBinding=Rt.bb)(l,m,E,I,G),u._OrtRun=(l,m,E,I,G,we,Ke,tt)=>(u._OrtRun=Rt.cb)(l,m,E,I,G,we,Ke,tt),u._OrtEndProfiling=l=>(u._OrtEndProfiling=Rt.db)(l),u._JsepOutput=(l,m,E)=>(u._JsepOutput=Rt.eb)(l,m,E),u._JsepGetNodeName=l=>(u._JsepGetNodeName=Rt.fb)(l);var Cp,Ma=()=>(Ma=Rt.gb)(),_n=u._free=l=>(_n=u._free=Rt.hb)(l),kp=u._malloc=l=>(kp=u._malloc=Rt.ib)(l),hh=(l,m,E,I,G,we)=>(hh=Rt.lb)(l,m,E,I,G,we),Nm=()=>(Nm=Rt.mb)(),jm=(l,m,E,I,G)=>(jm=Rt.nb)(l,m,E,I,G),mh=l=>(mh=Rt.ob)(l),Sp=l=>(Sp=Rt.pb)(l),Um=()=>(Um=Rt.qb)(),Wm=(l,m)=>(Wm=Rt.rb)(l,m),$p=l=>($p=Rt.sb)(l),_h=l=>(_h=Rt.tb)(l),fh=()=>(fh=Rt.ub)(),Vm=u.dynCall_ii=(l,m)=>(Vm=u.dynCall_ii=Rt.wb)(l,m),Gm=l=>(Gm=Rt.xb)(l),Km=()=>(Km=Rt.yb)(),Hm=l=>(Hm=Rt.zb)(l),qm=()=>(qm=Rt.Ab)();function Xm(){0fh(),u.stackRestore=l=>$p(l),u.stackAlloc=l=>_h(l),u.setValue=function(l,m,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":s()[l>>>0]=m;break;case"i16":o()[l>>>1>>>0]=m;break;case"i32":i()[l>>>2>>>0]=m;break;case"i64":Hs[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":d()[l>>>2>>>0]=m;break;default:Kn(`invalid type for setValue: ${E}`)}},u.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return s()[l>>>0];case"i16":return o()[l>>>1>>>0];case"i32":return i()[l>>>2>>>0];case"i64":return Hs[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return d()[l>>>2>>>0];default:Kn(`invalid type for getValue: ${m}`)}},u.UTF8ToString=zs,u.stringToUTF8=wa,u.lengthBytesUTF8=th,Ec=function l(){Cp||Xm(),Cp||(Ec=l)},Xm(),u.PTR_SIZE=4,B}),As=ks,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ks()}),ir,Yr,Br,br,Nt,Jr,Sr,Rr,$r=w(()=>{var e,t;rt(),ir=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Yr=typeof location>"u"?void 0:location.origin,Br=(s,n)=>{try{let o=n??ir;return(o?new URL(s,o):new URL(s)).origin===Yr}catch{return!1}},br=async s=>{let n=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Nt=(At(),M(pt)).default,Jr=async()=>{if(!ir)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Br(ir))return[void 0,Nt()];let s=await br(ir);return[s,Nt(s)]},Sr=(Qs(),M(ns)).default,Rr=async(s,n,o)=>[void 0,Sr]}),ar,Ar,pr,Ir,Zr,lr,nt,_t,Ot=w(()=>{$r(),Ar=!1,pr=!1,Ir=!1,Zr=()=>{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}},lr=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},nt=async e=>{if(Ar)return Promise.resolve();if(pr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ir)throw new Error("previous call to 'initializeWebAssembly()' failed.");pr=!0;let t=e.initTimeout,s=e.numThreads;if(!lr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Zr();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let o=e.wasmPaths,a=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,d=(i==null?void 0:i.href)??i,p=o==null?void 0:o.wasm,h=(p==null?void 0:p.href)??p,k=e.wasmBinary,[S,u]=await Rr(d,a,s>1),B=!1,R=[];if(t>0&&R.push(new Promise(j=>{setTimeout(()=>{B=!0,j()},t)})),R.push(new Promise((j,Z)=>{let te={numThreads:s};k?te.wasmBinary=k:(h||a)&&(te.locateFile=(X,_e)=>h??(a??_e)+X),u(te).then(X=>{pr=!1,Ar=!0,ar=X,j(),S&&URL.revokeObjectURL(S)},X=>{pr=!1,Ir=!0,Z(X)})})),await Promise.race(R),B)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},_t=()=>{if(Ar&&ar)return ar;throw new Error("WebAssembly is not initialized yet.")}}),ls,vr,ts,tr=w(()=>{Ot(),ls=(e,t)=>{let s=_t(),n=s.lengthBytesUTF8(e)+1,o=s._malloc(n);return s.stringToUTF8(e,o,n),t.push(o),o},vr=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,a])=>{let i=t?t+o:o;if(typeof a=="object")vr(a,i+".",s,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},ts=e=>{let t=_t(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let a=Number(t.getValue(o,n===4?"i32":"i64")),i=t.getValue(o+n,"*"),d=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),Nr,en=w(()=>{Ot(),tr(),Nr=e=>{let t=_t(),s=0,n=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.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)o.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&&(o.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=ls(e.tag,n)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,a),s===0&&ts("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&vr(e.extra,"",new WeakSet,(i,d)=>{let p=ls(i,n),h=ls(d,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ts(`Can't set a run config entry: ${i} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(i=>t._free(i)),a}}}),jr,Tr,kn,Ur,Sn,Jn=w(()=>{Ot(),tr(),jr=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Tr=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},kn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},Ur=(e,t,s)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let d=ls("deviceType",s),p=ls(i,s);_t()._OrtAddSessionConfigEntry(e,d,p)!==0&&ts(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(o="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let d=ls("preferredLayout",s),p=ls(i.preferredLayout,s);_t()._OrtAddSessionConfigEntry(e,d,p)!==0&&ts(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=ls(o,s);_t()._OrtAppendExecutionProvider(e,a)!==0&&ts(`Can't append execution provider: ${o}.`)}},Sn=e=>{let t=_t(),s=0,n=[],o=e||{};kn(o);try{let a=jr(o.graphOptimizationLevel??"all"),i=Tr(o.executionMode??"sequential"),d=typeof o.logId=="string"?ls(o.logId,n):0,p=o.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=o.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof o.optimizedModelFilePath=="string"?ls(o.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,d,p,h,k),s===0&&ts("Can't create session options."),o.executionProviders&&Ur(s,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let S=ls("enableGraphCapture",n),u=ls(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,S,u)!==0&&ts(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[S,u]of Object.entries(o.freeDimensionOverrides)){if(typeof S!="string")throw new Error(`free dimension override name must be a string: ${S}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let B=ls(S,n);t._OrtAddFreeDimensionOverride(s,B,u)!==0&&ts(`Can't set a free dimension override: ${S} - ${u}.`)}return o.extra!==void 0&&vr(o.extra,"",new WeakSet,(S,u)=>{let B=ls(S,n),R=ls(u,n);t._OrtAddSessionConfigEntry(s,B,R)!==0&&ts(`Can't set a session config entry: ${S} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ts("Can't release session options."),n.forEach(i=>t._free(i)),a}}}),Wr,xr,ur,fn,tn,gn,sn,Er,zt=w(()=>{Wr=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},xr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},ur=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,a)=>o*a,1);return s>0?Math.ceil(n*s):void 0},fn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},tn=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},gn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",sn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Er=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),wn,$n=w(()=>{rt(),wn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw d}let i=0;for(;;){let{done:d,value:p}=await o.read();if(d)break;let h=p.byteLength;new Uint8Array(a,i,h).set(p),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),An,In,Vr,On,yn,Fn,is,Ys=w(()=>{zt(),An=["V","I","W","E","F"],In=(e,t)=>{console.log(`[${An[e]},${new Date().toISOString()}]${t}`)},yn=(e,t)=>{Vr=e,On=t},Fn=(e,t)=>{let s=tn(e),n=tn(Vr);s>=n&&In(s,typeof t=="function"?t():t)},is=(...e)=>{On&&Fn(...e)}}),Mn,Dn=w(()=>{zt(),Mn=(e,t)=>new(fn(t))(e)}),bn=w(()=>{}),vn,xe,P,q,ae,Me,Pe,He,ct,yt=w(()=>{Ys(),bn(),vn=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),xe=[],P=e=>Math.ceil(Number(e)/16)*16,q=e=>{for(let t=0;tae++,Pe=async(e,t,s,n)=>{let o=P(s),a=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,o),e.flush(),await a.mapAsync(GPUMapMode.READ);let d=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(d,0,s)),p}else return new Uint8Array(d.slice(0,s))}finally{a.destroy()}},He=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of vn)xe.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,o=t.byteLength,a=P(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,o)),d.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(d,0,i.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),d.destroy(),is("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=P(s.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return is("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else n=Me();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),is("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),is("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=q(e),n,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||a){let d=(o?this.freeBuffers:this.freeUniformBuffers).get(s);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let i={id:Me(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),is("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return is("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await Pe(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=vn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(is("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ct=(...e)=>new He(...e)}),ht,it,Pt=w(()=>{ht=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},it=e=>new ht(e)}),hs,ss,Se,ws,Rs,Js,Zs,Bt=w(()=>{hs=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ss=class{static calcShape(e,t,s=!1){let n=e.length,o=t.length;if(n===0)return t;if(o===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(s){if(n<2||o<2)return;let d=hs.calcMatMulShape([e[n-2],e[n-1]],[t[o-2],t[o-1]]);if(d===void 0)return;[i[a-2],i[a-1]]=d}for(let d=s?3:1;d<=a;d++){let p=n-d<0?1:e[n-d],h=o-d<0?1:t[o-d];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)i[a-d]=Math.max(p,h);else{if(k>1)return;i[a-d]=0}}return i}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[n-o])return!1;return!0}},Se=class Ap{static size(t){return Ap.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let o=new Array(n),a=n-1;for(;a>=0;){if(t[a]%s===0){o[a]=t[a]/s;break}if(s%t[a]!==0)throw new Error("cannot convert shape");o[a]=1,s/=t[a],a--}for(a--;a>=0;a--)o[a]=t[a];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Ap.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Ap.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let o=1;for(let a=s;a=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((o,a)=>o+s[a]+s[a+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,o)=>n===s[o])}},ws=class Cc{static adjustPoolAttributes(t,s,n,o,a,i){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d=n.length?n.push(s[d+2]):n[d]=s[d+2];for(let d=0;d=n[d]||i[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,o,a,i,d){if(d){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{zt(),Bt(),Ns=64,hr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},es=(e,t=1)=>{let s=hr(e,t);return typeof s=="string"?s:s[0]},_s=(e,t=1)=>{let s=hr(e,t);return typeof s=="string"?s:s[1]},vt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:Se.computeStrides(s)})}),t},ys=e=>e%4===0?4:e%2===0?2:1,Pr=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,Fs=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,qs=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Mt=(e,t,s,n)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,bs=(e,t,s,n,o)=>{let a=typeof s=="number",i=a?s:s.length,d=[...new Array(i).keys()],p=i<2?"u32":i<=4?`vec${i}`:`array`,h=hr(t,o),k=typeof h=="string"?h:h[1],S=typeof h=="string"?h:h[0],u={indices:p,value:k,storage:S,tensor:t},B=ot=>typeof ot=="string"?ot:`${ot}u`,R={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},j=a?"uniforms.":"",Z=`${j}${e}_shape`,te=`${j}${e}_strides`,X="";for(let ot=0;ot ${u.indices} { var indices: ${u.indices}; var current = offset; ${X} return indices; }`,me=ot=>(R.offsetToIndices=!0,i<2?ot:`o2i_${e}(${ot})`),ye=[];if(i>=2)for(let ot=i-1;ot>=0;ot--)ye.push(`${Mt(te,ot,i)} * (indices[${ot}])`);let $e=i<2?"":` fn i2o_${e}(indices: ${u.indices}) -> u32 { return ${ye.join("+")}; }`,Ae=ot=>(R.indicesToOffset=!0,i<2?ot:`i2o_${e}(${ot})`),Ge=(...ot)=>i===0?"0u":`${u.indices}(${ot.map(B).join(",")})`,lt=(ot,Et)=>i<2?`${ot}`:`${Mt(ot,Et,i)}`,xt=(ot,Et,cs)=>i<2?`${ot}=${cs};`:`${Mt(ot,Et,i)}=${cs};`,Kt={},Yt=(ot,Et)=>{R.broadcastedIndicesToOffset=!0;let cs=`${Et.name}broadcastedIndicesTo${e}Offset`;if(cs in Kt)return`${cs}(${ot})`;let Ls=[];for(let Mr=i-1;Mr>=0;Mr--){let Hs=Et.indicesGet("outputIndices",Mr+Et.rank-i);Ls.push(`${lt(te,Mr)} * (${Hs} % ${lt(Z,Mr)})`)}return Kt[cs]=`fn ${cs}(outputIndices: ${Et.type.indices}) -> u32 { return ${Ls.length>0?Ls.join("+"):"0u"}; }`,`${cs}(${ot})`},Ct=(ot,Et)=>(()=>{if(u.storage===u.value)return`${e}[${ot}]=${Et};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${ot}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${ot}]=vec2(u32(${Et}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Jt=ot=>(()=>{if(u.storage===u.value)return`${e}[${ot}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${ot}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${ot}].x)`;if(u.storage==="u32"&&u.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 ${u.storage} and value type ${u.value} yet`)})(),$t=i<2?"":` fn get_${e}ByIndices(indices: ${u.indices}) -> ${k} { return ${Jt(`i2o_${e}(indices)`)}; }`,jt=i<2?"":(()=>{let ot=d.map(cs=>`d${cs}: u32`).join(", "),Et=d.map(cs=>`d${cs}`).join(", ");return` fn get_${e}(${ot}) -> ${k} { return get_${e}ByIndices(${Ge(Et)}); }`})(),vs=(...ot)=>{if(ot.length!==i)throw new Error(`indices length must be ${i}`);let Et=ot.map(B).join(",");return i===0?Jt("0u"):i===1?Jt(Et[0]):(R.get=!0,R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}(${Et})`)},Ht=ot=>i<2?Jt(ot):(R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}ByIndices(${ot})`),Gt=i<2?"":` fn set_${e}ByIndices(indices: ${u.indices}, value: ${k}) { ${Ct(`i2o_${e}(indices)`,"value")} }`,Cs=i<2?"":(()=>{let ot=d.map(cs=>`d${cs}: u32`).join(", "),Et=d.map(cs=>`d${cs}`).join(", ");return` fn set_${e}(${ot}, value: ${k}) { set_${e}ByIndices(${Ge(Et)}, value); }`})();return{impl:()=>{let ot=[],Et=!1;return R.offsetToIndices&&(ot.push(_e),Et=!0),R.indicesToOffset&&(ot.push($e),Et=!0),R.broadcastedIndicesToOffset&&(Object.values(Kt).forEach(cs=>ot.push(cs)),Et=!0),R.set&&(ot.push(Cs),Et=!0),R.setByIndices&&(ot.push(Gt),Et=!0),R.get&&(ot.push(jt),Et=!0),R.getByIndices&&(ot.push($t),Et=!0),!a&&Et&&ot.unshift(`const ${Z} = ${u.indices}(${s.join(",")});`,`const ${te} = ${u.indices}(${Se.computeStrides(s).join(",")});`),ot.join(` `)},type:u,offsetToIndices:me,indicesToOffset:Ae,broadcastedIndicesToOffset:Yt,indices:Ge,indicesGet:lt,indicesSet:xt,set:(...ot)=>{if(ot.length!==i+1)throw new Error(`indices length must be ${i}`);let Et=ot[i];if(typeof Et!="string")throw new Error("value must be string");let cs=ot.slice(0,i).map(B).join(",");return i===0?Ct("0u",Et):i===1?Ct(cs[0],Et):(R.set=!0,R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}(${cs}, ${Et})`)},setByOffset:Ct,setByIndices:(ot,Et)=>i<2?Ct(ot,Et):(R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}ByIndices(${ot}, ${Et});`),get:vs,getByOffset:Jt,getByIndices:Ht,usage:n,name:e,strides:te,shape:Z,rank:i}},ze=(e,t,s,n=1)=>bs(e,t,s,"input",n),wt=(e,t,s,n=1)=>bs(e,t,s,"output",n),sr=(e,t,s)=>bs(e,t,s,"atomicOutput",1),rn=(e,t,s,n=1)=>bs(e,t,s,"internal",n),Zn=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Ns){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=o?`@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`,i=o?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) fn main(${a}) { ${i} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let o=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${o}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Tn=(e,t)=>new Zn(e,t)}),ba,No,va,Ta,jo,xa,rr,Uo,Ea,Gr=w(()=>{zt(),Bt(),Pt(),Qt(),ba=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},No=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,va=(e,t)=>Se.sortBasedOnPerm(e,No(e.length,t)),Ta=(e,t,s,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`;for(let a=0;a{let s=[],n=[];for(let o=0;o{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,o=No(n,t),a=va(e.dims,o),i=e.dims,d=a,p=n<2||xa(o,e.dims),h;if(p)return h=R=>{let j=ze("input",s,i,4),Z=wt("output",s,d,4);return` ${R.registerUniform("output_size","u32").declareVariables(j,Z)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let R=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(R/4)}]}},getShaderSource:h};let{newShape:k,newPerm:S}=jo(e.dims,o),u=Se.areEqual(S,[2,3,1]),B=Se.areEqual(S,[3,1,2]);if(k.length===2||u||B){i=u?[k[0],k[1]*k[2]]:B?[k[0]*k[1],k[2]]:k,d=[i[1],i[0]];let R=16;return h=j=>{let Z=ze("a",s,i.length),te=wt("output",s,d.length);return` ${j.registerUniform("output_size","u32").declareVariables(Z,te)} var tile : array, ${R}>; ${j.mainStart([R,R,1])} let stride = (uniforms.output_shape[1] - 1) / ${R} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${R}u + local_id.x; let input_row = workgroup_id_x * ${R}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${Z.getByIndices(`${Z.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${R}u + local_id.x; let output_row = workgroup_id_y * ${R}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${te.setByIndices(`${te.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let j=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d[1]/R),y:Math.ceil(d[0]/R)},programUniforms:[{type:12,data:j},...vt(i,d)]}},getShaderSource:h}}return h=R=>{let j=ze("a",s,i.length),Z=wt("output",s,d.length);return` ${R.registerUniform("output_size","u32").declareVariables(j,Z)} ${Ta(o,n,j,Z)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${Z.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${Z.setByOffset("global_idx",j.getByIndices("aIndices"))} }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let R=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...vt(i,d)]}},getShaderSource:h}},Uo=(e,t)=>{ba(e.inputs),e.compute(rr(e.inputs[0],t.perm))},Ea=e=>it({perm:e.perm})}),Wo,Sc,Pa,Vo,Ca,eo,ka,Sa,$a,Aa,mr,Ia,Oa,Go,Fa,Ko,nn,Da,$c,La,Ac,Ic=w(()=>{zt(),Bt(),Qt(),ei(),Gr(),Wo={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"},Sc={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"},Pa={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Vo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ca=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,o]},ka=(e,t)=>{let s=e.length+t.length,n=[],o=0;for(let a=0;a{for(let s=0;s{let s=[];if(!Sa(e,t)){for(let n=0;ns.push(n))}return s},Aa=(e,t,s,n,o,a,i)=>{let d=s[0].dims,p=Se.size(a),h=Se.size(i),k=ze("_A",s[0].dataType,d),S=wt("output",o,a),u=64;p===1&&(u=256);let B=` var aBestValues : array; `,R=j=>` ${j.registerUniform("reduceSize","u32").declareVariables(k,S)} ${B} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${j.mainStart(u)} let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Pa[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${k.getByOffset("offset + k")}); bestValue = ${Wo[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${u}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Sc[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${S.setByOffset("outputIndex",`${n==="mean"?`${S.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${S.type.storage}(${Vo[n]})`}`)}; } }`;return{name:e,shaderCache:{hint:`${t};${u}`,inputDependencies:["type"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},mr=(e,t,s,n)=>{let o=e.inputs.length===1?s:Ho(e.inputs,s),a=o.axes;a.length===0&&!o.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((B,R)=>R));let i=Se.normalizeAxes(a,e.inputs[0].dims.length),d=i,p=e.inputs[0],h=$a(d,e.inputs[0].dims.length);h.length>0&&(p=e.compute(rr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=Ca(d.length,p.dims.length));let[k,S]=eo(p.dims,d),u=k;o.keepDims&&(u=ka(k,i)),e.compute(Aa(t,o.cacheKey,[p],n,e.inputs[0].dataType,u,S),{inputs:[p]})},Ia=(e,t)=>{mr(e,"ReduceMeanShared",t,"mean")},Oa=(e,t)=>{mr(e,"ReduceL1Shared",t,"l1")},Go=(e,t)=>{mr(e,"ReduceL2Shared",t,"l2")},Fa=(e,t)=>{mr(e,"ReduceLogSumExpShared",t,"logSumExp")},Ko=(e,t)=>{mr(e,"ReduceMaxShared",t,"max")},nn=(e,t)=>{mr(e,"ReduceMinShared",t,"min")},Da=(e,t)=>{mr(e,"ReduceProdShared",t,"prod")},$c=(e,t)=>{mr(e,"ReduceSumShared",t,"sum")},La=(e,t)=>{mr(e,"ReduceSumSquareShared",t,"sumSquare")},Ac=(e,t)=>{mr(e,"ReduceLogSumShared",t,"logSum")}}),dr,za,to,Ho,_r,Ba,so,Ra,Na,ja,qo,Ua,Wa,Xo,Va,fr,Qo,Ga,Ka,Yo,Ha,qa,Jo,Xa,Qa,Zo,ei=w(()=>{zt(),Bt(),Pt(),Qt(),Ic(),dr=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.")},za=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],to=(e,t,s,n,o,a,i=!1,d=!1)=>{let p=[],h=s[0].dims,k=h.length,S=Se.normalizeAxes(o,k),u=!d&&S.length===0;h.forEach((j,Z)=>{u||S.indexOf(Z)>=0?i&&p.push(1):p.push(j)});let B=p.length,R=Se.size(p);return{name:e,shaderCache:t,getShaderSource:j=>{let Z=[],te=ze("_A",s[0].dataType,k),X=wt("output",a,B),_e=n(te,X,S),me=_e[2];for(let ye=0,$e=0;ye=0?(i&&$e++,me=`for(var j${ye}: u32 = 0; j${ye} < ${h[ye]}; j${ye}++) { ${_e[2].includes("last_index")?`let last_index = j${ye};`:""} ${te.indicesSet("input_indices",ye,`j${ye}`)} ${me} }`):(Z.push(`${te.indicesSet("input_indices",ye,X.indicesGet("output_indices",$e))};`),$e++);return` ${j.registerUniform("output_size","u32").declareVariables(te,X)} ${j.mainStart()} ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${te.type.indices}; let output_indices = ${X.offsetToIndices("global_idx")}; ${Z.join(` `)} ${_e[0]} // init ops for reduce max/min ${_e[1]} ${me} ${_e[3]} ${_e.length===4?X.setByOffset("global_idx","value"):_e.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...vt(h,p)]})}},Ho=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),it({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},_r=(e,t,s,n)=>{let o=e.inputs,a=o.length===1?s:Ho(o,s);e.compute(to(t,{hint:a.cacheKey,inputDependencies:["rank"]},[o[0]],a.noopWithEmptyAxes&&a.axes.length===0?za:n,a.axes,o[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Ba=(e,t)=>{dr(e.inputs),_r(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},so=(e,t)=>{dr(e.inputs),_r(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Ra=(e,t)=>{dr(e.inputs),_r(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Na=(e,t)=>{dr(e.inputs),_r(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ja=(e,t)=>{dr(e.inputs),_r(e,"ReduceMax",t,(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(s.indicesSet("input_indices",i,0));return[`${a.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},qo=(e,t)=>{dr(e.inputs),_r(e,"ReduceMean",t,(s,n,o)=>{let a=1;for(let i=0;i=0||o.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Ua=(e,t)=>{dr(e.inputs),_r(e,"ReduceMin",t,(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` `)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Wa=(e,t)=>{dr(e.inputs),_r(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Xo=(e,t)=>{dr(e.inputs),_r(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Va=(e,t)=>{dr(e.inputs),_r(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},fr=(e,t,s)=>{if(t.length===0)return s;let n=1,o=1;for(let a=0;a1024},Qo=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):Ia(e,t)},Ga=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?so(e,t):Oa(e,t)},Ka=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ra(e,t):Go(e,t)},Yo=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Na(e,t):Fa(e,t)},Ha=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ja(e,t):Ko(e,t)},qa=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ua(e,t):nn(e,t)},Jo=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wa(e,t):Da(e,t)},Xa=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xo(e,t):$c(e,t)},Qa=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Va(e,t):La(e,t)},Zo=(e,t)=>{fr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ba(e,t):Ac(e,t)}}),ti,si,Ya,ri,Ja=w(()=>{zt(),Pt(),ei(),ti=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.")},si=(e,t)=>{ti(e.inputs);let s=(n,o,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",o.setByOffset("global_idx","best_index")]};e.compute(to("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Ya=(e,t)=>{ti(e.inputs);let s=(n,o,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",o.setByOffset("global_idx","best_index")]};e.compute(to("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},ri=e=>it(e)}),Za,ro,ni,el,tl,xn,sl,rl,no=w(()=>{zt(),Bt(),bn(),Qt(),Za=(e,t)=>{let s=e[0],n=e[1],o=e[2],a=e[3],i=e[4],d=e[5];if(i&&d)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],k=s.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let S=o.dims[0]/3,u=S,B=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let _e of t.qkvHiddenSizes)if(_e%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");S=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],B=t.qkvHiddenSizes[2]}let R=h;if(S!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==S+u+B)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let j=0;if(i){if(u!==B)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(j=i.dims[3])}let Z=R+j,te=-1,X=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(d.dims[0]!==p||d.dims[1]!==t.numHeads||d.dims[2]!==h||d.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:j,kvSequenceLength:R,totalSequenceLength:Z,maxSequenceLength:te,inputHiddenSize:k,hiddenSize:S,vHiddenSize:B,headSize:Math.floor(S/t.numHeads),vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ro=(e,t,s)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } `:` ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; `,ni=(e,t,s,n,o,a,i,d)=>{let p=ys(i?1:a),h=64,k=a/p;k{let X=wt("x",e.dataType,e.dims,p),_e=[X],me=i?ze("seq_lens",i.dataType,i.dims):void 0;me&&_e.push(me);let ye=d?ze("total_sequence_length_input",d.dataType,d.dims):void 0;ye&&_e.push(ye);let $e=_s(e.dataType),Ae=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${te.registerUniforms(Ae).declareVariables(..._e)} ${te.mainStart([h,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${ro(me,ye,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${R}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${R}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(p){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${p}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${h}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${R}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${R}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${h}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${X.type.value}(${$e}(1.0) / ${$e}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${R}(x[offset + i]); x[offset + i] = ${X.type.value}(exp(f32input - max_value) / sum); } } ${i?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${X.type.value}(${$e}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${B};${p}`,inputDependencies:j},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:o,z:t*s},programUniforms:u})}},el=(e,t,s,n,o,a,i,d,p)=>{let h=i+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],S=e>1&&n,u=a.kvNumHeads?a.kvNumHeads:a.numHeads,B=S?[a.batchSize,u,h,a.headSize]:void 0,R=a.nReps?a.nReps:1,j=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=ys(a.headSize),te=a.headSize/Z,X=12,_e={x:Math.ceil(h/X),y:Math.ceil(a.sequenceLength/X),z:a.batchSize*a.numHeads},me=[{type:12,data:a.sequenceLength},{type:12,data:te},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:j},{type:12,data:i},{type:12,data:a.kvSequenceLength},{type:12,data:R}],ye=S&&n&&Se.size(n.dims)>0,$e=["type","type"];ye&&$e.push("type"),o&&$e.push("type"),d&&$e.push("type"),p&&$e.push("type");let Ae=[{dims:k,dataType:t.dataType,gpuDataType:0}];S&&Ae.push({dims:B,dataType:t.dataType,gpuDataType:0});let Ge=lt=>{let xt=ze("q",t.dataType,t.dims,Z),Kt=ze("key",s.dataType,s.dims,Z),Yt=[xt,Kt];if(ye){let Gt=ze("past_key",n.dataType,n.dims,Z);Yt.push(Gt)}o&&Yt.push(ze("attention_bias",o.dataType,o.dims));let Ct=d?ze("seq_lens",d.dataType,d.dims):void 0;Ct&&Yt.push(Ct);let Jt=p?ze("total_sequence_length_input",p.dataType,p.dims):void 0;Jt&&Yt.push(Jt);let $t=wt("output",t.dataType,k),jt=[$t];S&&jt.push(wt("present_key",t.dataType,B,Z));let vs=_s(1,Z),Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${X}u; var tileQ: array<${xt.type.storage}, ${X*X}>; var tileK: array<${xt.type.storage}, ${X*X}>; ${lt.registerUniforms(Ht).declareVariables(...Yt,...jt)} ${lt.mainStart([X,X,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${R===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${R===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${ro(Ct,Jt,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${ye&&S?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${S?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${vs}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${ye&&S?` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }`:` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${S?`if (n + local_id.y < present_sequence_length) { present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${vs}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(Z){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${Z}`)}})()}; output[outputIdx] = ${$t.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${o!==void 0};${n!==void 0};${e}`,inputDependencies:$e},getRunData:()=>({outputs:Ae,dispatchGroup:_e,programUniforms:me}),getShaderSource:Ge}},tl=(e,t,s,n,o,a,i=void 0,d=void 0)=>{let p=a+o.kvSequenceLength,h=o.nReps?o.nReps:1,k=o.vHiddenSize*h,S=e>1&&n,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,B=S?[o.batchSize,u,p,o.headSize]:void 0,R=[o.batchSize,o.sequenceLength,k],j=12,Z={x:Math.ceil(o.vHeadSize/j),y:Math.ceil(o.sequenceLength/j),z:o.batchSize*o.numHeads},te=[{type:12,data:o.sequenceLength},{type:12,data:p},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:k},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:h}],X=S&&n&&Se.size(n.dims)>0,_e=["type","type"];X&&_e.push("type"),i&&_e.push("type"),d&&_e.push("type");let me=[{dims:R,dataType:t.dataType,gpuDataType:0}];S&&me.push({dims:B,dataType:t.dataType,gpuDataType:0});let ye=$e=>{let Ae=ze("probs",t.dataType,t.dims),Ge=ze("v",s.dataType,s.dims),lt=[Ae,Ge];X&<.push(ze("past_value",n.dataType,n.dims));let xt=i?ze("seq_lens",i.dataType,i.dims):void 0;i&<.push(xt);let Kt=d?ze("total_sequence_length_input",d.dataType,d.dims):void 0;d&<.push(Kt);let Yt=[wt("output",t.dataType,R)];S&&Yt.push(wt("present_value",t.dataType,B));let Ct=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${j}u; var tileQ: array<${Ae.type.value}, ${j*j}>; var tileV: array<${Ae.type.value}, ${j*j}>; ${$e.registerUniforms(Ct).declareVariables(...lt,...Yt)} ${$e.mainStart([j,j,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${ro(xt,Kt,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${X&&S?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${S?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${Ae.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${X&&S?` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } `:` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${S?` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }`:""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:_e},getRunData:()=>({outputs:me,dispatchGroup:Z,programUniforms:te}),getShaderSource:ye}},xn=(e,t,s,n,o,a,i,d,p,h,k=void 0,S=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(d?1:0)),B=u>1?h.pastSequenceLength:0,R=B+h.kvSequenceLength,j=p&&Se.size(p.dims)>0?p:void 0,Z=[t,s];u>1&&i&&Se.size(i.dims)>0&&Z.push(i),j&&Z.push(j),k&&Z.push(k),S&&Z.push(S);let te=e.compute(el(u,t,s,i,j,h,B,k,S),{inputs:Z,outputs:u>1?[-1,1]:[-1]})[0];e.compute(ni(te,h.batchSize,h.numHeads,B,h.sequenceLength,R,k,S),{inputs:k&&S?[te,k,S]:[te],outputs:[]});let X=[te,n];u>1&&d&&Se.size(d.dims)>0&&X.push(d),k&&X.push(k),S&&X.push(S),e.compute(tl(u,te,n,d,h,B,k,S),{inputs:X,outputs:u>1?[0,2]:[0]})},sl=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,a=t.headSize,i=12,d={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:o},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],k=S=>{let u=wt("output_q",p[0].dataType,s),B=wt("output_k",p[0].dataType,s),R=wt("output_v",p[0].dataType,s),j=ze("input",p[0].dataType,p[0].dims),Z=ze("weight",p[1].dataType,p[1].dims),te=ze("bias",p[2].dataType,p[2].dims),X=j.type.storage,_e=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${i}u; var tileInput: array<${X}, ${i*i}>; var tileWeightQ: array<${X}, ${i*i}>; var tileWeightK: array<${X}, ${i*i}>; var tileWeightV: array<${X}, ${i*i}>; ${S.registerUniforms(_e).declareVariables(j,Z,te,u,B,R)} ${S.mainStart([i,i,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${X}(0); var valueK = ${X}(0); var valueV = ${X}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},rl=(e,t)=>{let s=Za(e.inputs,t),[n,o,a]=sl(e,s);return xn(e,n,o,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),nl,ol,oi,il,Oc=w(()=>{Qe(),zt(),Bt(),Pt(),Qt(),nl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,o,a)=>{let i=o.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);o.forEach((d,p)=>{if(d!==n[p])throw new Error(`${a}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},ol=(e,t)=>{let{epsilon:s,spatial:n,format:o}=t,a=e[0].dims,i=n?ys(a[a.length-1]):1,d=o==="NHWC"&&a.length>1?i:1,p=Se.size(a)/i,h=n,k=h?a.length:a,S=ze("x",e[0].dataType,e[0].dims,i),u=ze("scale",e[1].dataType,e[1].dims,d),B=ze("bias",e[2].dataType,e[2].dims,d),R=ze("inputMean",e[3].dataType,e[3].dims,d),j=ze("inputVar",e[4].dataType,e[4].dims,d),Z=wt("y",e[0].dataType,k,i),te=()=>{let _e="";if(n)_e=`let cOffset = ${a.length===1?"0u":o==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")_e=` ${Z.indicesSet("outputIndices","0","0")} let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{_e=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let me=1;me` const epsilon = ${s}; ${_e.registerUniform("outputSize","u32").declareVariables(S,u,B,R,j,Z)} ${_e.mainStart()} ${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${Z.offsetToIndices(`global_idx * ${i}`)}; ${te()} let scale = ${u.getByOffset("cOffset")}; let bias = ${B.getByOffset("cOffset")}; let inputMean = ${R.getByOffset("cOffset")}; let inputVar = ${j.getByOffset("cOffset")}; let x = ${S.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${Z.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:X,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...vt(a)]:[{type:12,data:p}]})}},oi=e=>it(e),il=(e,t)=>{let{inputs:s,outputCount:n}=e,o=oi({...t,outputCount:n});if(T.webgpu.validateInputContent&&nl(s,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ol(s,o))}}),ii,al,ll,ul=w(()=>{Bt(),Qt(),ii=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")},al=e=>{let t=e[0].dims,s=e[0].dims[2],n=Se.size(t)/4,o=e[0].dataType,a=ze("input",o,t,4),i=ze("bias",o,[s],4),d=ze("residual",o,t,4),p=wt("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` const channels = ${s}u / 4; ${h.declareVariables(a,i,d,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${a.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${p.setByOffset("global_idx","value")} }`}},ll=e=>{ii(e.inputs),e.compute(al(e.inputs))}}),dl,us,ai,cl,pl,li,hl,ml,ui,_l,fl,di,gl,wl,ci,yl,Ln,Ml,oo,pi,bl,vl,hi,Tl,xl,mi,El,Pl,_i,Cl,kl,fi,Sl,$l,gi,wi,Al,io,yi,Il,Ol,Fl,Mi,Dl,Ll,bi=w(()=>{zt(),Bt(),Pt(),Qt(),dl=(e,t,s,n,o,a,i)=>{let d=Math.ceil(t/4),p="";typeof o=="string"?p=`${o}(a)`:p=o("a");let h=ze("inputData",s,[d],4),k=wt("outputData",n,[d],4),S=[{name:"vec_size",type:"u32"}];return i&&S.push(...i),` ${e.registerUniforms(S).declareVariables(h,k)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${k.setByOffset("global_idx",p)} }`},us=(e,t,s,n,o,a=e.dataType,i,d)=>{let p=[{type:12,data:Math.ceil(Se.size(e.dims)/4)}];return i&&p.push(...i),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:h=>dl(h,Se.size(e.dims),e.dataType,a,s,n,d),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Se.size(h[0].dims)/64/4)},programUniforms:p})}},ai=e=>{e.compute(us(e.inputs[0],"Abs","abs"))},cl=e=>{e.compute(us(e.inputs[0],"Acos","acos"))},pl=e=>{e.compute(us(e.inputs[0],"Acosh","acosh"))},li=e=>{e.compute(us(e.inputs[0],"Asin","asin"))},hl=e=>{e.compute(us(e.inputs[0],"Asinh","asinh"))},ml=e=>{e.compute(us(e.inputs[0],"Atan","atan"))},ui=e=>{e.compute(us(e.inputs[0],"Atanh","atanh"))},_l=e=>it(e),fl=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(us(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},di=e=>{let t,s,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return it({min:t,max:s})},gl=(e,t)=>{let s=t||di(e.inputs),n=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},wl=e=>{e.compute(us(e.inputs[0],"Ceil","ceil"))},ci=e=>{e.compute(us(e.inputs[0],"Cos","cos"))},yl=e=>{e.compute(us(e.inputs[0],"Cosh","cosh"))},Ln=e=>it(e),Ml=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${s}(${t.alpha}); fn elu_f32(a: ${s}) -> ${s} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},oo=(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)); }`,pi=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,oo(t)))},bl=e=>{e.compute(us(e.inputs[0],"Exp","exp"))},vl=e=>{e.compute(us(e.inputs[0],"Floor","floor"))},hi=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,oo(t)))},Tl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},xl=e=>{e.compute(us(e.inputs[0],"Not",t=>`!${t}`))},mi=e=>{e.compute(us(e.inputs[0],"Neg",t=>`-${t}`))},El=e=>{e.compute(us(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Pl=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},_i=e=>{e.compute(us(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Cl=e=>it(e),kl=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},fi=e=>{e.compute(us(e.inputs[0],"Sin","sin"))},Sl=e=>{e.compute(us(e.inputs[0],"Sinh","sinh"))},$l=e=>{e.compute(us(e.inputs[0],"Sqrt","sqrt"))},gi=e=>{e.compute(us(e.inputs[0],"Tan","tan"))},wi=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Al=e=>{e.compute(us(e.inputs[0],"Tanh",wi))},io=(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 ${wi("v")}; } `,yi=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Il=e=>{let t=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"FastGelu",yi,io(t),void 0,e.inputs[0].dataType))},Ol=(e,t)=>{let s=_s(e.inputs[0].dataType);return e.compute(us(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},Fl=e=>{e.compute(us(e.inputs[0],"Log","log"))},Mi=(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; } `,Dl=e=>`quick_gelu_impl(${e})`,Ll=(e,t)=>{let s=_s(e.inputs[0].dataType);e.compute(us(e.inputs[0],"QuickGelu",Dl,Mi(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),zl,vi,Bl,Fc=w(()=>{Bt(),Qt(),bi(),zl=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")},vi=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=ze("input",e[0].dataType,e[0].dims,4),n=ze("bias",e[0].dataType,[e[0].dims[2]],4),o=wt("output",e[0].dataType,t,4),a=Se.size(t)/4,i=es(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${d.declareVariables(s,n,o)} ${oo(i)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${o.setByOffset("global_idx","valueLeft * geluRight")} }`}},Bl=e=>{zl(e.inputs),e.compute(vi(e.inputs))}}),Rl,Nl,cr,jl,Ul,Wl,Vl,Ti,Gl,Kl,xi,Hl,ql,Xl=w(()=>{zt(),Bt(),Qt(),Rl=(e,t,s,n,o,a,i,d,p,h,k,S)=>{let u,B;typeof d=="string"?u=B=(X,_e)=>`${d}((${X}),(${_e}))`:typeof d=="function"?u=B=d:(u=d.scalar,B=d.vector);let R=wt("outputData",k,n.length,4),j=ze("aData",p,t.length,4),Z=ze("bData",h,s.length,4),te;if(o)if(a){let X=Se.size(t)===1,_e=Se.size(s)===1,me=t.length>0&&t[t.length-1]%4===0,ye=s.length>0&&s[s.length-1]%4===0;X||_e?te=R.setByOffset("global_idx",B(X?`${j.type.value}(${j.getByOffset("0")}.x)`:j.getByOffset("global_idx"),_e?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):te=` let outputIndices = ${R.offsetToIndices("global_idx * 4u")}; let offsetA = ${j.broadcastedIndicesToOffset("outputIndices",R)}; let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",R)}; ${R.setByOffset("global_idx",B(i||me?j.getByOffset("offsetA / 4u"):`${j.type.value}(${j.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||ye?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else te=R.setByOffset("global_idx",B(j.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let X=(_e,me,ye="")=>{let $e=`aData[indexA${me}][componentA${me}]`,Ae=`bData[indexB${me}][componentB${me}]`;return` let outputIndices${me} = ${R.offsetToIndices(`global_idx * 4u + ${me}u`)}; let offsetA${me} = ${j.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; let offsetB${me} = ${Z.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; let indexA${me} = offsetA${me} / 4u; let indexB${me} = offsetB${me} / 4u; let componentA${me} = offsetA${me} % 4u; let componentB${me} = offsetB${me} % 4u; ${_e}[${me}] = ${ye}(${u($e,Ae)}); `};k===9?te=` var data = vec4(0); ${X("data",0,"u32")} ${X("data",1,"u32")} ${X("data",2,"u32")} ${X("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:te=` ${X("outputData[global_idx]",0)} ${X("outputData[global_idx]",1)} ${X("outputData[global_idx]",2)} ${X("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(j,Z,R)} ${S??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${te} }`},Nl=(e,t,s,n,o,a,i=s.dataType)=>{let d=s.dims.map(j=>Number(j)??1),p=n.dims.map(j=>Number(j)??1),h=!Se.areEqual(d,p),k=d,S=Se.size(d),u=!1,B=!1,R=[h];if(h){let j=ss.calcShape(d,p,!1);if(!j)throw new Error("Can't perform binary op on the given tensors");k=j.slice(),S=Se.size(k);let Z=Se.size(d)===1,te=Se.size(p)===1,X=d.length>0&&d[d.length-1]%4===0,_e=p.length>0&&p[p.length-1]%4===0;R.push(Z),R.push(te),R.push(X),R.push(_e);let me=1;for(let ye=1;yej.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:j=>Rl(j,d,p,k,u,h,B,o,s.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:k,dataType:i}],dispatchGroup:{x:Math.ceil(S/64/4)},programUniforms:[{type:12,data:Math.ceil(Se.size(k)/4)},...vt(d,p,k)]})}},cr=(e,t,s,n,o,a)=>{e.compute(Nl(t,o??"",e.inputs[0],e.inputs[1],s,n,a))},jl=e=>{cr(e,"Add",(t,s)=>`${t}+${s}`)},Ul=e=>{cr(e,"Div",(t,s)=>`${t}/${s}`)},Wl=e=>{cr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},Vl=e=>{cr(e,"Mul",(t,s)=>`${t}*${s}`)},Ti=e=>{let t=ze("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;cr(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${n})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Gl=e=>{cr(e,"Sub",(t,s)=>`${t}-${s}`)},Kl=e=>{cr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},xi=e=>{cr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},Hl=e=>{cr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},ql=e=>{cr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),Ql,Yl,Ei,Jl,Zl,Pi,Dc=w(()=>{zt(),Bt(),Pt(),Qt(),Ql=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],o=n.dataType,a=n.dims.length;e.forEach((i,d)=>{if(d!==s){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},Yl=(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; }`,Ei=(e,t)=>{let s=e.length,n=[];for(let o=0;o{let o=Se.size(s),a=new Array(e.length),i=new Array(e.length),d=0,p=[],h=[],k=[{type:12,data:o}];for(let j=0;j`uniforms.sizeInConcatAxis${j}`).join(","),R=j=>` ${(()=>{j.registerUniform("outputSize","u32");for(let Z=0;Z(${B}); ${u} -= sizeInConcatAxis[inputIndex - 1u]; } ${Ei(i,S)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:k}),getShaderSource:R}},Zl=(e,t)=>{let s=e.inputs,n=s[0].dims,o=Se.normalizeAxis(t.axis,n.length);Ql(s,o);let a=n.slice();a[o]=s.reduce((d,p)=>d+(p.dims.length>o?p.dims[o]:0),0);let i=s.filter(d=>Se.size(d.dims)>0);e.compute(Jl(i,o,a,s[0].dataType),{inputs:i})},Pi=e=>it({axis:e.axis})}),on,Or,an,Ci,Kr=w(()=>{zt(),Bt(),on=(e,t,s="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Or=(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})},an=(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"})},Ci=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[s,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=(e==null?void 0:e.activation_params)||[Js,Zs];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Ws,eu,ao=w(()=>{Ws=(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.`)}},eu=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),tu,Lc=w(()=>{tu=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)); } `}),zn,lo,ki=w(()=>{zt(),Bt(),Qt(),Kr(),zn=(e,t,s,n,o)=>{let a=n-s;return` ${Array.from({length:s}).map((i,d)=>` if (${Mt(t.shape,d,t.rank)} != 1) { ${t.indicesSet(e,d,Mt(o,d+a,n))} } else { ${t.indicesSet(e,d,0)} }`).join("")} `},lo=(e,t,s,n,o=!1,a)=>{let i=e[0].dims,d=e[1].dims,p=i[i.length-2],h=d[d.length-1],k=i[i.length-1],S=ys(h),u=ys(k),B=ys(p),R=Se.size(s)/S/B,j=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),te=[Se.size(Z),p,h],X=[{type:12,data:R},{type:12,data:p},{type:12,data:h},{type:12,data:k}];Or(t,X),X.push(...vt(Z,i,d)),j&&X.push(...vt(e[2].dims)),X.push(...vt(te));let _e=me=>{let ye=rn("batch_dims",e[0].dataType,Z.length),$e=ze("a",e[0].dataType,i.length,u),Ae=ze("b",e[1].dataType,d.length,S),Ge=wt("output",e[0].dataType,te.length,S),lt=es(Ge.type.tensor),xt=on(t,Ge.type.value,lt),Kt=[$e,Ae],Yt="";if(j){let $t=o?S:1;Kt.push(ze("bias",e[2].dataType,e[2].dims.length,$t)),Yt=`${o?`value += bias[col / ${$t}];`:`value += ${Ge.type.value}(bias[row + i]);`}`}let Ct=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];an(t,Ct);let Jt=()=>{let $t=`var a_data: ${$e.type.value};`;for(let jt=0;jt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { ${Jt()} } for (var i = 0u; i < ${B}u; i++) { var value = values[i]; ${Yt} ${xt} let cur_indices = ${Ge.type.indices}(batch, row + i, col); let offset = ${Ge.indicesToOffset("cur_indices")}; ${Ge.setByOffset(`offset / ${S}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${S};${u};${B};${o}`,inputDependencies:j?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:X}),getShaderSource:_e}}}),su,ru,uo,Si,nu,co,ou,po,ho=w(()=>{zt(),Bt(),Qt(),Kr(),ki(),ao(),su=(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":""}); `,ru=(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];"} }`,uo=(e,t,s="f32",n,o=!1,a=32,i=!1,d=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=o?p:a,S=o?a:p,u=k/t[0],B=a/t[1];if(!((o&&u===4&&e[1]===4||!o&&(u===3||u===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${u} must be 3 or 4. tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${k/u}>, ${S}>; var mm_Bsub: array, ${h/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${u}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${p}; let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${B}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${su(o,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${ru(o,u)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Si=(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":""}); `,nu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",co=(e,t,s="f32",n,o=!1,a=32,i=!1,d=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],S=o?h:a,u=o?a:h;if(!(u%t[1]===0&&S%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${S} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let B=u/t[1],R=S/t[0],j=a/t[1],Z=p?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${k}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${S}; inputCol = inputCol + ${t[0]}) { ${Si(o,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${s}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${h}; let tileRowA = i32(localId.y) * ${B}; let tileColA = i32(localId.x) * ${R}; let tileRowB = i32(localId.y) * ${j}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Si(o,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${j}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${s}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${nu(o)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${u}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${i?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; var acc : array, rowPerThread>; ${Z} } `},ou=(e,t,s,n,o=!1)=>{let[a,i,d,p]=n,h=es(n[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ws(e,h)} { var value = ${Ws(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${i.type.indices}; ${zn("aIndices",i,i.rank-2,a.rank,"batchIndices")} ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} value = ${i.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ws(e,h)} { var value = ${Ws(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${d.type.indices}; ${zn("bIndices",d,d.rank-2,a.rank,"batchIndices")} ${d.indicesSet("bIndices",d.rank-2,"u32(row)")} ${d.indicesSet("bIndices",d.rank-1,"u32(colIn)")} value = ${d.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ws(e,h)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${o?"bias[colIn]":`${Ws(e,h)}(bias[row])`};`:""} ${s} ${p.setByIndices("vec3(coords)","value")} } } `},po=(e,t,s,n,o=!1,a)=>{let i=e[0].dims,d=e[1].dims,p=i.slice(0,-2),h=d.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),S=Se.size(k),u=i[i.length-2],B=i[i.length-1],R=d[d.length-1],j=B%4===0&&R%4===0,Z=u<=8?[4,1,1]:[4,4,1],te=[8,8,1],X=[Math.ceil(R/te[0]/Z[0]),Math.ceil(u/te[1]/Z[1]),Math.ceil(S/te[2]/Z[2])],_e=j?4:1,me=[...p,u,B/_e],ye=me.length,$e=[...h,B,R/_e],Ae=$e.length,Ge=[S,u,R/_e],lt=[{type:6,data:u},{type:6,data:R},{type:6,data:B}];Or(t,lt),lt.push(...vt(k,me,$e));let xt=["rank","rank"],Kt=e.length>2;Kt&&(lt.push(...vt(e[2].dims)),xt.push("rank")),lt.push(...vt(Ge));let Yt=Ct=>{let Jt=k.length,$t=rn("batchDims",e[0].dataType,Jt,1),jt=es(e[0].dataType),vs=ze("a",e[0].dataType,ye,_e),Ht=ze("b",e[1].dataType,Ae,_e),Gt=wt("result",e[0].dataType,Ge.length,_e),Cs=[vs,Ht];if(Kt){let Mr=o?_e:1;Cs.push(ze("bias",e[2].dataType,e[2].dims.length,Mr))}let ot=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];an(t,ot);let Et=es(Gt.type.tensor),cs=on(t,Gt.type.value,Et),Ls=ou(_e,Kt,cs,[$t,vs,Ht,Gt],o);return` ${Ct.registerUniforms(ot).registerInternalVariables($t).declareVariables(...Cs,Gt)} ${Ls} ${j?uo(Z,te,jt,$t):co(Z,te,jt,$t)} `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${j};${o}`,inputDependencies:xt},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:X[0],y:X[1],z:X[2]},programUniforms:lt}),getShaderSource:Yt}}}),iu,au,lu=w(()=>{zt(),Ys(),Qt(),Kr(),ao(),Lc(),ho(),iu=(e,t,s,n,o=!1,a,i=4,d=4,p=4,h="f32")=>{let k=lt=>{switch(lt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${lt} is not supported.`)}},S=lt=>{switch(lt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${lt} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,B=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,R=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",j=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",te=e?"col":"row",X=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${Z} / outWidth; let outCol = ${Z} % outWidth; let WRow = ${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 = ${Ws(i,h)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${R} && xCol >= 0 && xCol < ${j}) { ${u} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${k(i)} } return resData;`,_e=e?t&&n?` let col = colIn * ${i}; ${X}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${X} } return ${Ws(i,h)}(0.0);`:n&&s?` let col = colIn * ${i}; ${X}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${X} } return ${Ws(i,h)}(0.0);`,me=`${S(d)}`,ye=Ws(p,h),$e=Ws(e?i:d,h),Ae=Ws(e?d:i,h),Ge=on(a,ye,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${$e} { ${e?_e:me} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ae} { ${e?me:_e} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ye}) { let col = colIn * ${p}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${B} ${eu(o)} ${Ge} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},au=(e,t,s,n,o,a,i,d,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],S=s[0],u=h?s[2]:s[3],B=h?s[1]:s[2],R=h?s[3]:s[1],j=h&&(k%4===0||k%3===0)&&R%4===0,Z=h?R:u*B,te=h?u*B:R,X=[8,8,1],_e=n<=8?[4,1,1]:[4,4,1],me=[Math.ceil(Z/X[0]/_e[0]),Math.ceil(te/X[1]/_e[1]),Math.ceil(S/X[2]/_e[2])];is("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${me}`);let ye=j?h&&k%4!==0?3:4:1,$e=X[1]*_e[1],Ae=X[0]*_e[0],Ge=Math.max(X[0]*ye,X[1]),lt=n%$e===0,xt=o%Ae===0,Kt=a%Ge===0,Yt=j?[ye,4,4]:[1,1,1],Ct=[{type:6,data:n},{type:6,data:o},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Or(t,Ct),Ct.push(...vt(e[0].dims,e[1].dims));let Jt=["rank","rank"];i&&(Ct.push(...vt(e[2].dims)),Jt.push("rank")),Ct.push(...vt(s));let $t=jt=>{let vs=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];an(t,vs);let Ht=j?4:1,Gt=es(e[0].dataType),Cs=` fn setOutputAtIndex(flatIndex : i32, value : ${j?`vec4<${Gt}>`:Gt}) { result[flatIndex] = ${j?`vec4<${Gt}>`:Gt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${j?`vec4<${Gt}>`:Gt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${j?"/ 4":""}, value); }`,ot=ze("x",e[0].dataType,e[0].dims.length,ye===3?1:ye),Et=ze("w",e[1].dataType,e[1].dims.length,Ht),cs=[ot,Et],Ls=wt("result",e[0].dataType,s.length,Ht);if(i){let Mr=ze("bias",e[2].dataType,e[2].dims.length,Ht);cs.push(Mr),Cs+=` fn getBiasByOutputCoords(coords : vec4) -> ${j?`vec4<${Gt}>`:Gt} { return bias[coords.${h?"w":"y"}${j?"/ 4":""}]; }`}return` ${tu("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${jt.registerUniforms(vs).declareVariables(...cs,Ls)} ${Cs} ${iu(h,lt,xt,Kt,i,t,Yt[0],Yt[1],Yt[2],Gt)} ${j?uo(_e,X,Gt,void 0,!h,Ge):co(_e,X,Gt,void 0,!h,Ge,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ye};${j};${lt};${xt};${Kt};${$e};${Ae};${Ge}`,inputDependencies:Jt},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:me[0],y:me[1],z:me[2]},programUniforms:Ct}),getShaderSource:$t}}}),uu,$i,En,du,Ai,Ii,cu,pu,zc=w(()=>{zt(),Ys(),Bt(),Qt(),Kr(),ao(),uu=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,En=(e,t)=>t<=1?e:e+(e-1)*(t-1),du=(e,t,s,n=1)=>{let o=En(t,n);return Math.floor((e[0]*(s-1)-s+o)/2)},Ai=(e,t,s,n,o)=>{o==null&&(o=du(e,t[0],n[0]));let a=[0,0,0,s];for(let i=0;i<3;i++)e[i]+2*o>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*o)/n[i]+1));return a},Ii=(e,t,s,n,o,a,i,d,p,h)=>{let k,S,u,B;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let R=Ai([t,s,n,1],[d,p,h],1,[o,a,i],e);S=R[0],u=R[1],B=R[2]}else if(Array.isArray(e)){if(!e.every((j,Z,te)=>j===te[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let R=Ai([t,s,n,1],[d,p,h],1,[o,a,i],e[0]);S=R[0],u=R[1],B=R[2]}else if(e==="SAME_UPPER"){S=Math.ceil(t/o),u=Math.ceil(s/a),B=Math.ceil(n/i);let R=(S-1)*o+d-t,j=(u-1)*a+p-s,Z=(B-1)*i+h-n,te=Math.floor(R/2),X=R-te,_e=Math.floor(j/2),me=j-_e,ye=Math.floor(Z/2),$e=Z-ye;k={top:_e,bottom:me,left:ye,right:$e,front:te,back:X}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:S,outHeight:u,outWidth:B}},cu=(e,t,s,n,o,a=!1,i="channelsLast")=>{let d,p,h,k,S;if(i==="channelsLast")[d,p,h,k,S]=e;else if(i==="channelsFirst")[d,S,p,h,k]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,B,R,j]=t,[Z,te,X]=$i(s),[_e,me,ye]=$i(n),$e=En(B,_e),Ae=En(R,me),Ge=En(j,ye),{padInfo:lt,outDepth:xt,outHeight:Kt,outWidth:Yt}=Ii(o,p,h,k,Z,te,X,$e,Ae,Ge),Ct=a?u*S:u,Jt=[0,0,0,0,0];return i==="channelsFirst"?Jt=[d,Ct,xt,Kt,Yt]:i==="channelsLast"&&(Jt=[d,xt,Kt,Yt,Ct]),{batchSize:d,dataFormat:i,inDepth:p,inHeight:h,inWidth:k,inChannels:S,outDepth:xt,outHeight:Kt,outWidth:Yt,outChannels:Ct,padInfo:lt,strideDepth:Z,strideHeight:te,strideWidth:X,filterDepth:B,filterHeight:R,filterWidth:j,effectiveFilterDepth:$e,effectiveFilterHeight:Ae,effectiveFilterWidth:Ge,dilationDepth:_e,dilationHeight:me,dilationWidth:ye,inShape:e,outShape:Jt,filterShape:t}},pu=(e,t,s,n,o,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],p={x:s.map((Z,te)=>te)},h=[Math.ceil(uu(p.x.map(Z=>s[Z]))/d[0]),1,1];is("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,S=Se.size(s),u=[{type:12,data:S},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Or(t,u),u.push(...vt(e[0].dims,e[1].dims));let B=["rank","rank"],R=e.length===3;R&&(u.push(...vt(e[2].dims)),B.push("rank")),u.push(...vt(s));let j=Z=>{let te=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];an(t,te);let X=1,_e=es(e[0].dataType),me=ze("x",e[0].dataType,e[0].dims.length,k),ye=ze("W",e[1].dataType,e[1].dims.length,X),$e=[me,ye],Ae=wt("result",e[0].dataType,s.length,X),Ge="";if(R){let Kt=ze("bias",e[2].dataType,e[2].dims.length,X);$e.push(Kt),Ge+=` fn getBiasByOutputCoords(coords : array) -> ${_e} { return bias[${i?Mt("coords",4,5):Mt("coords",1,5)}]; }`}let lt=Ws(k,_e),xt=on(t,lt,_e);return` ${Ge} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${me.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ye.getByIndices("aIndices")}; } ${Z.registerUniforms(te).declareVariables(...$e,Ae)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ae.offsetToIndices("global_idx")}; let batch = ${Mt("coords",0,me.rank)}; let d2 = ${i?Mt("coords",me.rank-1,me.rank):Mt("coords",1,me.rank)}; let xFRCCorner = vec3(${i?Mt("coords",1,me.rank):Mt("coords",2,me.rank)}, ${i?Mt("coords",2,me.rank):Mt("coords",3,me.rank)}, ${i?Mt("coords",3,me.rank):Mt("coords",4,me.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${i?Mt("uniforms.x_shape",1,me.rank):Mt("uniforms.x_shape",2,me.rank)}; let xShapeZ = ${i?Mt("uniforms.x_shape",2,me.rank):Mt("uniforms.x_shape",3,me.rank)}; let xShapeW = ${i?Mt("uniforms.x_shape",3,me.rank):Mt("uniforms.x_shape",4,me.rank)}; let xShapeU = ${i?Mt("uniforms.x_shape",4,me.rank):Mt("uniforms.x_shape",1,me.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${i?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${i?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${i?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${R?"value = value + getBiasByOutputCoords(coords)":""}; ${xt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${k};${R}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:u}),getShaderSource:j}}}),hu,mo,Bc=w(()=>{zt(),Bt(),Qt(),Kr(),hu=(e,t,s,n)=>{let o=e.length>2,a=o?"value += b[output_channel];":"",i=e[0].dims,d=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,S=p&&k>=4?ys(h):1,u=Se.size(s)/S,B=[{type:12,data:u},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:k}];Or(t,B),B.push(...vt(i,[d[0],d[1],d[2],d[3]/S]));let R=o?["rank","rank","rank"]:["rank","rank"];B.push(...vt([s[0],s[1],s[2],s[3]/S]));let j=Z=>{let te=wt("output",e[0].dataType,s.length,S),X=es(te.type.tensor),_e=on(t,te.type.value,X),me=ze("x",e[0].dataType,i.length),ye=ze("w",e[1].dataType,d.length,S),$e=[me,ye];o&&$e.push(ze("b",e[2].dataType,e[2].dims,S));let Ae=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];an(t,Ae);let Ge=p?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${me.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${ye.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${me.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${ye.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${Z.registerUniforms(Ae).declareVariables(...$e,te)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${te.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${p?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${S} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; var value: ${te.type.value} = ${te.type.value}(0); ${Ge} ${a} ${_e} ${te.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${S}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:j}},mo=(e,t,s,n)=>{let o=e.length>2,a=ys(s[3]),i=ys(s[2]),d=Se.size(s)/a/i,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],k=[s[0],s[1],s[2],s[3]/a],S=[{type:12,data:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Or(t,S),S.push(...vt(p,h,k));let u=(i-1)*t.strides[1]+h[1],B=R=>{let j=wt("output",e[0].dataType,k.length,a),Z=es(j.type.tensor),te=on(t,j.type.value,Z),X=ze("x",e[0].dataType,p.length,a),_e=ze("w",e[1].dataType,h.length,a),me=[X,_e];o&&me.push(ze("b",e[2].dataType,e[2].dims,a));let ye=o?"value += b[output_channel];":"",$e=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return an(t,$e),` ${R.registerUniforms($e).declareVariables(...me,j)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${i}u; let col = (index1 % width1) * ${i}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${X.type.value}, ${u}>; var values: array<${j.type.value}, ${i}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${u}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${X.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${X.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${_e.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${i}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${i}u; i++) { var value = values[i]; ${ye} ${te} ${j.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${u};${h[0]};${h[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:S}),getShaderSource:B}}}),mu,_o,_u,fo,go,Oi,fu,Fi,Di,Rc=w(()=>{Bt(),lu(),zc(),ho(),Bc(),Kr(),ki(),Gr(),mu=(e,t,s,n,o,a)=>{let i=e[0],d=e.slice(a?1:2,a?3:4),p=d.length,h=t[0],k=t.slice(2).map((u,B)=>u+(u-1)*(s[B]-1)),S=d.map((u,B)=>u+n[B]+n[B+p]).map((u,B)=>Math.floor((u-k[B]+o[B])/o[B]));return S.splice(0,0,i),S.splice(a?3:1,0,h),S},_o=[2,3,1,0],_u=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},fo=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=Ci(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,a=e.group,i=e.kernel_shape,d=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:o,group:a,kernelShape:i,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Oi=(e,t,s,n)=>{let o=s.format==="NHWC",a=mu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,o);if(s.group!==1){let $e=[t[0]];if(o){let Ae=e.kernelCustomData.wT??e.compute(rr(t[1],_o),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ae),$e.push(Ae)}else $e.push(t[1]);t.length===3&&$e.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(mo($e,s,a,n),{inputs:$e}):e.compute(hu($e,s,a,n),{inputs:$e});return}let i=t.length===3,d=t[0].dims[o?1:2],p=t[0].dims[o?2:3],h=t[0].dims[o?3:1],k=t[1].dims[2],S=t[1].dims[3],u=a[o?1:2],B=a[o?2:3],R=a[o?3:1],j=o&&k===d&&S===p&&s.pads[0]===0&&s.pads[1]===0;if(j||k===1&&S===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let $e=a[0],Ae,Ge,lt,xt=[];if(o){let Ct=e.kernelCustomData.wT??e.compute(rr(t[1],_o),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ct),j){let Jt=d*p*h;Ae=t[0].reshape([1,$e,Jt]),Ge=Ct.reshape([1,Jt,R]),lt=[1,$e,R]}else Ae=t[0].reshape([$e,d*p,h]),Ge=Ct.reshape([1,h,R]),lt=[$e,u*B,R];xt.push(Ae),xt.push(Ge)}else Ae=t[0].reshape([$e,h,d*p]),Ge=t[1].reshape([1,R,h]),lt=[$e,R,u*B],xt.push(Ge),xt.push(Ae);i&&xt.push(t[2]);let Kt=lt[2],Yt=xt[0].dims[xt[0].dims.length-1];Kt<8&&Yt<8?e.compute(lo(xt,s,a,lt,o,n),{inputs:xt}):e.compute(po(xt,s,a,lt,o,n),{inputs:xt});return}let Z=!0,te=e.kernelCustomData.wT??e.compute(rr(t[1],_o),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let X=[t[0],te];i&&X.push(t[2]);let _e=o?u*B:R,me=o?R:u*B,ye=k*S*h;e.compute(au(X,s,a,_e,me,ye,i,Z,n),{inputs:X})},fu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),d=[1].concat(t.kernelShape),p=fo({...t,pads:o,strides:a,dilations:i,kernelShape:d},n);Oi(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Fi=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",o=fo(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,i=cu(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(pu(t,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},Di=(e,t)=>{if(_u(e.inputs,t),e.inputs[0].dims.length===3)fu(e,t);else if(e.inputs[0].dims.length===5)Fi(e,e.inputs,t);else{let s=fo(t,e.inputs);Oi(e,e.inputs,s)}}}),gu,Nc=w(()=>{zt(),Ys(),Bt(),Qt(),gu=(e,t,s)=>{let n=e.length>2,o=t.outputShape,a=t.format==="NHWC",i=t.group,d=e[1].dims,p=d[2]/i,h=d[3],k=a?ys(h):1,S=Se.size(o)/k,u=[Math.ceil(S/64),1,1];is("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let B=["rank","rank"],R=[t.strides[0],t.strides[1]],j=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],Z=[t.dilations[0],t.dilations[1]],te=[j[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),j[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],X=[te[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),te[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],_e=[{type:12,data:S},{type:12,data:R},{type:12,data:j},{type:12,data:Z},{type:12,data:te},{type:6,data:X},{type:12,data:p},{type:12,data:h},...vt(e[0].dims,e[1].dims)];n&&(_e.push(...vt(e[2].dims)),B.push("rank")),_e.push(...vt(o));let me=ye=>{let $e=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:R.length},{name:"filter_dims",type:"u32",length:j.length},{name:"dilations",type:"u32",length:j.length},{name:"effective_filter_dims",type:"u32",length:te.length},{name:"pads",type:"i32",length:X.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ae=es(e[0].dataType),Ge=a?1:2,lt=a?2:3,xt=a?3:1,Kt=ze("W",e[1].dataType,e[1].dims.length,k),Yt=ze("Dy",e[0].dataType,e[0].dims.length),Ct=[Yt,Kt];n&&Ct.push(ze("bias",e[2].dataType,[o[xt]].length,k));let Jt=wt("result",e[0].dataType,o.length,k),$t=` let outputIndices = ${Jt.offsetToIndices(`global_idx * ${k}`)}; let batch = ${Jt.indicesGet("outputIndices",0)}; let d1 = ${Jt.indicesGet("outputIndices",xt)}; let r = ${Jt.indicesGet("outputIndices",Ge)}; let c = ${Jt.indicesGet("outputIndices",lt)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${Jt.type.value}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${Ae}(dyRCorner) + ${Ae}(wR)) / ${Ae}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${Ae}(uniforms.Dy_shape[${Ge}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${Ae}(dyCCorner) + ${Ae}(wC)) / ${Ae}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${Ae}(uniforms.Dy_shape[${lt}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${a?Yt.get("batch","idyR","idyC","inputChannel"):Yt.get("batch","inputChannel","idyR","idyC")}; let w_offset = ${Kt.indicesToOffset(`${Kt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${Kt.getByOffset(`w_offset / ${k}`)}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd${n?` + bias[d1 / ${k}]`:""}; ${Jt.setByOffset("global_idx","value")}; `;return` ${ye.registerUniforms($e).declareVariables(...Ct,Jt)} ${ye.mainStart()} ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${$t}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}`,inputDependencies:B},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:s?s(o):o,dataType:e[0].dataType}],programUniforms:_e}),getShaderSource:me}}}),Li,wu,yu,wo,Mu,bu,yo,vu,Tu,xu=w(()=>{Nc(),Kr(),Gr(),Li=(e,t,s,n,o,a)=>(e-1)*t+s+(n-1)*o+1-a,wu=(e,t,s,n,o)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=a,s[o]=e-a):t==="SAME_LOWER"&&(s[n]=e-a,s[o]=a)},yu=(e,t,s,n,o,a,i,d,p,h)=>{let k=e.length-2,S=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((S,u)=>S*u,1)===0){s.length=0;for(let S=2;SS+u,0)===0){let S=t[0].dims.length-2;p=new Array(S).fill(1)}let h=e.strides.slice();if(h.reduce((S,u)=>S+u,0)===0){let S=t[0].dims.length-2;h=new Array(S).fill(1)}yu(d,s,p,e.autoPad,e.group,o,h,n,i,a);let k=Object.assign({},e);return Object.assign(k,{kernelShape:s,pads:o,outputPadding:i,outputShape:a,dilations:p,strides:h}),k},Mu=e=>{let t=Ci(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,a=e.group,i=e.kernelShape,d=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,S=e.outputShape;return{autoPad:n,format:s,dilations:o,group:a,kernelShape:i,outputPadding:k,outputShape:S,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},bu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,d)=>i+d,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,d)=>i+d,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,d)=>i+d,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,d)=>i+d,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},yo=(e,t,s,n)=>{let o=e.kernelCustomData.wT??e.compute(rr(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let a=[t[0],o];t.length===3&&a.push(t[2]),e.compute(gu(a,s,n),{inputs:a})},vu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],i=[1].concat(i),a=[1].concat(a),o=[1].concat(o);let p=wo({...t,pads:d,strides:i,dilations:a,kernelShape:o},n);yo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Tu=(e,t)=>{if(bu(e.inputs,t),e.inputs[0].dims.length===3)vu(e,t);else{let s=wo(t,e.inputs);yo(e,e.inputs,s)}}}),Eu,Pu,Cu,jc=w(()=>{zt(),Bt(),Pt(),Qt(),Eu=(e,t,s,n)=>{let o=Se.size(t),a=t.length,i=ze("input",e,a),d=wt("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=Se.normalizeAxis(p,a),k=S=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,B=Mt("uniforms.input_shape","uniforms.axis",a),R=n.reverse?u+(n.exclusive?" + 1":""):"0",j=n.reverse?B:u+(n.exclusive?"":" + 1");return` ${S.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,d)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${d.offsetToIndices("global_idx")}; var sum = ${d.type.value}(0); let first : i32 = ${R}; let last : i32 = ${j}; for (var i : i32 = first; i < last; i++) { ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${i.getByIndices("inputIndices")}; } ${d.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:h},...vt(t,t)]}),getShaderSource:k}},Pu=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(Eu(n,s,o,t),{inputs:[0]})},Cu=e=>{let t=e.exclusive===1,s=e.reverse===1;return it({exclusive:t,reverse:s})}}),ku,Su,zi,$u,Au,Iu=w(()=>{zt(),Bt(),Pt(),Qt(),ku=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Su=(e,t,s,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`);for(let a=0;a{let s,n,o,a,i,d,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([s,n,o,a]=e.dims,i=k?[s,n,o,h,h,a/h**2]:[s,n,o,a/h**2,h,h],d=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,o,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=k?[s,h,h,a/h**2,n,o]:[s,a/h**2,h,h,n,o],d=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let S=e.reshape(i),u=S.dims.length,B=e.dataType,R=ze("a",B,u),j=wt("output",B,u),Z=te=>` ${te.registerUniform("output_size","u32").declareVariables(R,j)} ${Su(d,u,R,j)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${j.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${j.setByOffset("global_idx",R.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:te=>{let X=p?[s,n*h,o*h,a/h**2]:[s,a/h**2,n*h,o*h],_e=Se.size(X),me=S.dims,ye=Se.sortBasedOnPerm(me,d);return{outputs:[{dims:X,dataType:te[0].dataType}],dispatchGroup:{x:Math.ceil(_e/64)},programUniforms:[{type:12,data:_e},...vt(me,ye)]}},getShaderSource:Z}},$u=(e,t)=>{ku(e.inputs),e.compute(zi(e.inputs[0],t))},Au=e=>it({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Mo,Bn,Fr,Ou,Fu,Du,Lu,bo,zu,Bu,Ru,Uc=w(()=>{zt(),Bt(),Pt(),Qt(),Mo="[a-zA-Z]|\\.\\.\\.",Bn="("+Mo+")+",Fr="^"+Bn+"$",Ou="("+Bn+",)*"+Bn,Fu="^"+Ou+"$",Du=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},Lu=class{constructor(e,t){var o;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(Fu)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,i)=>{let d=e[i].dims.slice();if(!a.match(RegExp(Fr)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,d,i);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Bn)))throw new Error("Invalid RHS");(o=n.match(RegExp(Mo,"g")))==null||o.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let o=s.length,a=!1,i=[],d=0;if(!e.match(RegExp(Fr))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(Mo,"g")),h=new Du(n);return p==null||p.forEach((k,S)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let u=o-p.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=s.slice(d,d+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let B=0;Be+"_max",zu=(e,t,s,n)=>{let o=e.map(h=>h.length).map((h,k)=>ze(`input${k}`,t,h)),a=Se.size(n),i=wt("output",t,n.length),d=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],S="var prod = 1.0;",u="var sum = 0.0;",B="sum += prod;",R=[],j=[],Z=[],te=[],X=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((me,ye)=>{var $e;if(s.rhs.symbolToIndices.has(ye)){let Ae=($e=s.rhs.symbolToIndices.get(ye))==null?void 0:$e[0];Ae!==void 0&&s.lhs.forEach((Ge,lt)=>{if(me.inputIndices.includes(lt)){let xt=Ge.symbolToIndices.get(ye);if(xt===void 0)throw new Error("Invalid symbol error");xt.forEach(Kt=>{k.push(`${o[lt].indicesSet(`input${lt}Indices`,Kt,i.indicesGet("outputIndices",Ae))}`)})}})}else s.lhs.forEach((Ae,Ge)=>{if(me.inputIndices.includes(Ge)){let lt=Ae.symbolToIndices.get(ye);if(lt===void 0)throw new Error("Invalid symbol error");lt.forEach(xt=>{R.push(`${o[Ge].indicesSet(`input${Ge}Indices`,xt,`${ye}`)}`)}),te.push(`prod *= ${o[Ge].getByIndices(`input${Ge}Indices`)};`)}}),j.push(`for(var ${ye}: u32 = 0; ${ye} < uniforms.${bo(ye)}; ${ye}++) {`),Z.push("}")});let _e=X?[...k,`let sum = ${o.map((me,ye)=>me.getByIndices(`input${ye}Indices`)).join(" * ")};`]:[...k,u,...j,...R,S,...te,B,...Z];return` ${h.registerUniforms(d.map(me=>({name:`${bo(me)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${o.map((me,ye)=>`var input${ye}Indices: ${o[ye].type.indices};`).join(` `)} ${_e.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=d.filter(S=>s.symbolToInfo.has(S)).map(S=>{var u;return{type:12,data:((u=s.symbolToInfo.get(S))==null?void 0:u.dimValue)||0}});h.push({type:12,data:a});let k=e.map((S,u)=>[...vt(S)]).reduce((S,u)=>S.concat(u),h);return k.push(...vt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},Bu=(e,t)=>{let s=new Lu(e.inputs,t.equation),n=s.outputDims,o=e.inputs.map((a,i)=>a.dims);e.compute(zu(o,e.inputs[0].dataType,s,n))},Ru=e=>{let t=e.equation.replace(/\s+/g,"");return it({equation:t})}}),vo,Bi,Nu,ju,Rn,Wc=w(()=>{zt(),Bt(),Qt(),vo=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let o=0;oe.length>t.length?Bi(e,t):Bi(t,e),ju=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Nu(t,s),o=e[0].dataType,a=o===9||Se.size(t)===1,i=o===9||t.length>0&&t[t.length-1]%4===0?4:1,d=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(Se.size(n)/d),h=S=>{let u=ze("input",o,t.length,i),B=wt("output",o,n.length,d),R;if(o===9){let j=(Z,te,X="")=>` let outputIndices${te} = ${B.offsetToIndices(`outputOffset + ${te}u`)}; let offset${te} = ${u.broadcastedIndicesToOffset(`outputIndices${te}`,B)}; let index${te} = offset${te} / 4u; let component${te} = offset${te} % 4u; ${Z}[${te}] = ${X}(${u.getByOffset(`index${te}`)}[component${te}]); `;R=` let outputOffset = global_idx * ${d}; var data = vec4(0); ${j("data",0,"u32")} ${j("data",1,"u32")} ${j("data",2,"u32")} ${j("data",3,"u32")} ${B.setByOffset("global_idx","data")} }`}else R=` let outputIndices = ${B.offsetToIndices(`global_idx * ${d}`)}; let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",B)}; let data = ${B.type.value}(${u.getByOffset(`inputOffset / ${i}`)}); ${B.setByOffset("global_idx","data")} }`;return` ${S.registerUniform("vec_size","u32").declareVariables(u,B)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${R}`},k=[{type:12,data:p},...vt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${i}${d}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},Rn=e=>{vo(e.inputs),e.compute(ju(e.inputs),{inputs:[0]})}}),Uu,Wu,Vc=w(()=>{zt(),Bt(),Qt(),bi(),Uu=e=>{let t=e[0].dataType,s=Se.size(e[0].dims),n=Se.size(e[1].dims),o=n%4===0,a=i=>{let d=ze("x",t,[1],4),p=ze("bias",t,[1],4),h=wt("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],S=B=>` let bias${B}_offset: u32 = (global_idx * 4 + ${B}) % uniforms.bias_size; let bias${B} = ${p.getByOffset(`bias${B}_offset / 4`)}[bias${B}_offset % 4];`,u=o?` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${S(0)}${S(1)}${S(2)}${S(3)} let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(k).declareVariables(d,p,h)} ${io(_s(t))} ${i.mainStart(Ns)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${u} let x_in = x + bias; ${h.setByOffset("global_idx",yi("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/Ns/4)}})}},Wu=e=>{e.inputs.length<2||Se.size(e.inputs[1].dims)===0?Il(e):e.compute(Uu(e.inputs))}}),To,Vu,Gu,Ku,Fp=w(()=>{zt(),Bt(),Pt(),Qt(),To=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Vu=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,a=Se.normalizeAxis(t.axis,o),i=s.slice(0);i.splice(a,1,...n);let d=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(Se.size(i)/p),k=[{type:12,data:h},{type:6,data:d},{type:12,data:a},...vt(e[0].dims,e[1].dims,i)],S=u=>{let B=ze("data",e[0].dataType,e[0].dims.length,p),R=ze("inputIndices",e[1].dataType,e[1].dims.length),j=wt("output",e[0].dataType,i.length,p),Z=X=>{let _e=n.length,me=`var indicesIndices${X} = ${R.type.indices}(0);`;for(let ye=0;ye<_e;ye++)me+=`${_e>1?`indicesIndices${X}[${ye}]`:`indicesIndices${X}`} = ${i.length>1?`outputIndices${X}[uniforms.axis + ${ye}]`:`outputIndices${X}`};`;me+=` var idx${X} = ${R.getByIndices(`indicesIndices${X}`)}; if (idx${X} < 0) { idx${X} = idx${X} + uniforms.axisDimLimit; } var dataIndices${X} : ${B.type.indices}; `;for(let ye=0,$e=0;ye1?`dataIndices${X}[${ye}]`:`dataIndices${X}`} = u32(idx${X});`,$e+=_e):(me+=`${o>1?`dataIndices${X}[${ye}]`:`dataIndices${X}`} = ${i.length>1?`outputIndices${X}[${$e}]`:`outputIndices${X}`};`,$e++);return me},te;if(e[0].dataType===9){let X=(_e,me,ye="")=>` let outputIndices${me} = ${j.offsetToIndices(`outputOffset + ${me}u`)}; ${Z(me)}; let offset${me} = ${B.indicesToOffset(`dataIndices${me}`)}; let index${me} = offset${me} / 4u; let component${me} = offset${me} % 4u; ${_e}[${me}] = ${ye}(${B.getByOffset(`index${me}`)}[component${me}]); `;te=` let outputOffset = global_idx * ${p}; var value = vec4(0); ${X("value",0,"u32")} ${X("value",1,"u32")} ${X("value",2,"u32")} ${X("value",3,"u32")} ${j.setByOffset("global_idx","value")} `}else te=` let outputIndices = ${j.offsetToIndices("global_idx")}; ${Z("")}; let value = ${B.getByIndices("dataIndices")}; ${j.setByOffset("global_idx","value")}; `;return` ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(B,R,j)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${te} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:S}},Gu=e=>it({axis:e.axis}),Ku=(e,t)=>{let s=e.inputs;To(s),e.compute(Vu(e.inputs,t))}}),Hu,qu,Xu,Nn=w(()=>{zt(),Bt(),Qt(),Hu=(e,t,s,n,o,a,i,d,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:o},{type:12,data:s},{type:12,data:i},{type:12,data:d},{type:12,data:p}],k=[a];h.push(...vt(t.dims,k));let S=u=>{let B=ze("indices_data",t.dataType,t.dims.length),R=wt("input_slice_offsets_data",12,1,1),j=[B,R],Z=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${u.registerUniforms(Z).declareVariables(...j)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} } ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:S},{inputs:[t],outputs:[-1]})[0]},qu=(e,t)=>{let s=e.inputs,n=s[0].dims,o=s[0].dataType,a=s[1].dims,i=a[a.length-1],d=Se.sizeToDimension(a,a.length-1),p=Se.sizeFromDimension(n,t.batchDims+i),h=Se.sizeToDimension(n,t.batchDims),k=Se.sizeFromDimension(n,t.batchDims),S=d/h,u=new Array(i),B=p;for(let me=0;men.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(j)),te=Se.size(Z),X=[{type:12,data:te},{type:12,data:p},...vt(s[0].dims,R.dims,Z)],_e=me=>{let ye=ze("data",s[0].dataType,s[0].dims.length),$e=ze("slice_offsets",12,R.dims.length),Ae=wt("output",s[0].dataType,Z.length);return` ${me.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(ye,$e,Ae)} ${me.mainStart()} ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:o}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:X}),getShaderSource:_e},{inputs:[s[0],R]})},Xu=e=>({batchDims:e.batch_dims,cacheKey:""})}),Qu,Yu,Ju,Zu,Gc=w(()=>{zt(),Bt(),Pt(),Qt(),Qu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=Se.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==o.dims.length||!o.dims.map((d,p)=>p===s?Math.ceil(d/n)===a.dims[p]:d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((d,p)=>d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Yu=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,a=Se.normalizeAxis(t.gatherAxis,o),i=Se.normalizeAxis(t.quantizeAxis,o),d=s.slice(0);d.splice(a,1,...n);let p=Se.size(d),h=e[2].dataType,k=e[0].dataType===22,S=[{type:12,data:p},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...vt(...e.map((B,R)=>B.dims),d)],u=B=>{let R=ze("data",e[0].dataType,e[0].dims.length),j=ze("inputIndices",e[1].dataType,e[1].dims.length),Z=ze("scales",e[2].dataType,e[2].dims.length),te=e.length>3?ze("zeroPoint",e[3].dataType,e[3].dims.length):void 0,X=wt("output",h,d.length),_e=[R,j,Z];te&&_e.push(te);let me=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${B.registerUniforms(me).declareVariables(..._e,X)} ${B.mainStart()} let output_indices = ${X.offsetToIndices("global_idx")}; var indices_indices = ${j.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${X.indicesGet("output_indices","uniforms.gather_axis + i")}; ${j.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${X.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${R.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${X.indicesGet("output_indices","i")}; ${R.indicesSet("data_indices","i","index")}; } var index_from_indices = ${j.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${s[a]}; } ${R.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${d.length}; i++) { let index = ${X.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${R.indicesSet("data_indices","i","index")}; } let data_offset = ${R.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${Z.getByIndices("scale_indices")}; ${te?` let zero_point_indices = scale_indices; let zero_point_offset = ${te.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${te.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${_s(h)}(quantized_data - zero_point) * scale; ${X.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((B,R)=>R!==1).map(B=>B.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(B,R)=>"rank")},getRunData:()=>({outputs:[{dims:d,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:S}),getShaderSource:u}},Ju=(e,t)=>{let s=e.inputs;Qu(s,t),e.compute(Yu(e.inputs,t))},Zu=e=>it({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),xo,Kc,ed,td,Hc=w(()=>{zt(),Bt(),Pt(),Qt(),xo=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.`)},Kc=(e,t)=>{let s=e[0].dims,n=e[0].dataType,o=s.length,a=e[1].dims,i=e[1].dataType,d=Se.normalizeAxis(t.axis,o),p=s[d],h=a.slice(0),k=Se.size(h),S=ze("input",n,o),u=ze("indicesInput",i,a.length),B=wt("output",n,h.length),R=[{type:12,data:k},{type:6,data:p},{type:12,data:d}];return R.push(...vt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:R}),getShaderSource:j=>` ${j.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(S,u,B)} ${j.mainStart()} ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${B.offsetToIndices("global_idx")}; var idx = ${u.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${S.type.indices}(outputIndices); ${S.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${S.getByIndices("inputIndices")}; ${B.setByOffset("global_idx","value")}; }`}},ed=e=>it({axis:e.axis}),td=(e,t)=>{let s=e.inputs;xo(s),e.compute(Kc(e.inputs,t))}}),sd,rd,Ri,nd,qc=w(()=>{zt(),Bt(),Qt(),sd=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")},rd=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[o,a,i]=Rs.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),d=[o,a];if(!d)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(o/p),S=!0,u=Se.size(d),B=[{type:12,data:S?h:u},{type:12,data:o},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],R=["type","type"];e.length===3&&(B.push(...vt(e[2].dims)),R.push("rank")),B.push(...vt(d));let j=te=>{let X="";t.transA&&t.transB?X="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?X="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?X="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(X="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let _e=t.alpha===1?"":"value *= uniforms.alpha;",me=ze("a",e[0].dataType,e[0].dims),ye=ze("b",e[1].dataType,e[1].dims),$e=me.type.value,Ae=null,Ge=[me,ye];e.length===3&&(Ae=ze("c",e[2].dataType,e[2].dims.length),Ge.push(Ae));let lt=wt("output",e[0].dataType,d.length);Ge.push(lt);let xt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${te.registerUniforms(xt).declareVariables(...Ge)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${$e}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${X} } ${_e} ${Ae!=null?`let cOffset = ${Ae.broadcastedIndicesToOffset("vec2(m, n)",lt)}; value += ${$e}(uniforms.beta) * ${Ae.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},Z=te=>{let X=ze("a",e[0].dataType,e[0].dims),_e=ze("b",e[1].dataType,e[1].dims),me=null,ye=[X,_e];e.length===3&&(me=ze("c",e[2].dataType,e[2].dims.length),ye.push(me));let $e=wt("output",e[0].dataType,d.length);ye.push($e);let Ae=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],Ge="",lt="";t.transA&&t.transB?(lt=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${X.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); } `,Ge="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(lt=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${X.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); } `,Ge="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(lt=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${X.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); } `,Ge="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(lt=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${X.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); } `,Ge="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let xt=t.alpha===1?"":"value *= uniforms.alpha;";return` ${te.registerUniforms(Ae).declareVariables(...ye)} var tile_a: array, ${p}>; var tile_b: array, ${p}>; ${te.mainStart([p,p,1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; let num_tiles = (uniforms.K - 1) / ${p} + 1; var k_start = 0u; var value = ${$e.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${lt} k_start = k_start + ${p}; workgroupBarrier(); for (var k: u32 = 0u; k < ${p}; k++) { ${Ge} } workgroupBarrier(); } ${xt} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${me!=null?`let cOffset = ${me.broadcastedIndicesToOffset("vec2(m, n)",$e)}; value += ${$e.type.value}(uniforms.beta) * ${me.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return S?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:B}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:j}},Ri=e=>{let t=e.transA,s=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:s,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},nd=(e,t)=>{sd(e.inputs),e.compute(rd(e.inputs,t))}}),gr,Dr,ln,Hr,od,id,Eo,ad,ld,ud,dd,Ni,Po,Xc,Qc=w(()=>{zt(),Bt(),Pt(),Qt(),[gr,Dr,ln,Hr]=[0,1,2,3],od=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},id=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); var coeffs: vec4; coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } `,Eo=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; } `,ad=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)); `} } `,ld=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); }`:""} `,ud=(e,t,s)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { var pixel = ${t}(0); var indices = vec4(0); indices[${gr}] = batch; indices[${Dr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${ln}] = u32(r); indices[${Hr}] = u32(c); } `;case"border":return` indices[${ln}] = u32(clamp(r, 0, H - 1)); indices[${Hr}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${ln}] = gs_reflect(r, border[1], border[3]); indices[${Hr}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,dd=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${gr}], indices[${Dr}], border); `;case"bilinear":return` let x1 = i32(floor(x)); let y1 = i32(floor(y)); let x2 = x1 + 1; let y2 = y1 + 1; let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${gr}], indices[${Dr}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${gr}], indices[${Dr}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${gr}], indices[${Dr}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${gr}], indices[${Dr}], border); let dx2 = ${t}(f32(x2) - x); let dx1 = ${t}(x - f32(x1)); let dy2 = ${t}(f32(y2) - y); let dy1 = ${t}(y - f32(y1)); let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); `;case"bicubic":return` let x0 = i32(floor(x)) - 1; let y0 = i32(floor(y)) - 1; var p: mat4x4<${t}>; for (var h = 0; h < 4; h++) { for (var w = 0; w < 4; w++) { p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${gr}], indices[${Dr}], border); } } let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); `;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Ni=(e,t)=>{let s=ze("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=ze("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[gr,Dr,ln,Hr]=[0,3,1,2]);let i=wt("output",e[0].dataType,a.length),d=s.type.value,p=Se.size(a),h=[{type:12,data:p},...vt(e[0].dims,n,a)],k=S=>` ${S.registerUniform("output_size","u32").declareVariables(s,o,i)} ${id} ${Eo(d)} ${ad(t)} ${ld(t)} ${ud(s,d,t)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${ln}]); let W_in = i32(uniforms.x_shape[${Hr}]); ${t.alignCorners===0?` let x_min = -0.5; let x_max = f32(W_in) - 0.5; let y_min = -0.5; let y_max = f32(H_in) - 0.5; `:` let x_min = 0.0; let x_max = f32(W_in) - 1.0; let y_min = 0.0; let y_max = f32(H_in) - 1.0; `}; let border = vec4(x_min, y_min, x_max, y_max); let indices = ${i.offsetToIndices("global_idx")}; var grid_indices = vec3(indices[${gr}], indices[${ln}], indices[${Hr}]); let nxy = ${o.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${dd(i,d,t)} }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:S=>{let u=Se.size(a);return{outputs:[{dims:a,dataType:S[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}},getShaderSource:k}},Po=(e,t)=>{od(e.inputs),e.compute(Ni(e.inputs,t))},Xc=e=>it({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),er,ji,cd,Ui,Wi,jn,pd,Vi=w(()=>{zt(),Bt(),Pt(),bn(),no(),Qt(),Gr(),er=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,ji=(e,t)=>{let s=e[0],n=er(e,1),o=er(e,2),a=er(e,3),i=er(e,4),d=er(e,5),p=er(e,6),h=er(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=s.dims[0],S=s.dims[1],u=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],B=S,R=0,j=0,Z=Math.floor(u/t.numHeads);if(p&&h&&Se.size(p.dims)&&Se.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');R=p.dims[2],j=p.dims[2]}else if(p&&Se.size(p.dims)||h&&Se.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te;if(n&&Se.size(n.dims)>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');te=2,B=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');te=5,B=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');te=0,B=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}if(a&&Se.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let X=R+B,_e=0;if(i&&Se.size(i.dims)>0){_e=8;let Ae=i.dims;throw Ae.length===1?Ae[0]===k?_e=1:Ae[0]===3*k+2&&(_e=3):Ae.length===2&&Ae[0]===k&&Ae[1]===X&&(_e=5),_e===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let me=!1,ye=u;if(o&&Se.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(B!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ye=o.dims[2]}else{if(B!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ye=o.dims[1]*o.dims[3],me=!0}}let $e=!1;if(i&&Se.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(d&&Se.size(d.dims)>0){if(d.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(d.dims[0]!==k||d.dims[1]!==t.numHeads||d.dims[2]!==S||d.dims[3]!==X)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:S,pastSequenceLength:R,kvSequenceLength:B,totalSequenceLength:X,maxSequenceLength:j,inputHiddenSize:0,hiddenSize:u,vHiddenSize:ye,headSize:Z,vHeadSize:Math.floor(ye/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:_e,scale:t.scale,broadcastResPosBias:$e,passPastInKv:me,qkvFormat:te}},cd=e=>it({...e}),Ui=it({perm:[0,2,1,3]}),Wi=(e,t,s,n,o,a,i)=>{let d=[n,o,a],p=Se.size(d),h=[{type:12,data:p},{type:12,data:i},{type:12,data:a}],k=S=>{let u=wt("qkv_with_bias",t.dataType,d),B=ze("qkv",t.dataType,d),R=ze("bias",s.dataType,d),j=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${S.registerUniforms(j).declareVariables(B,R,u)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},jn=(e,t,s,n,o,a,i,d)=>{let p=a;if(i&&Se.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=Wi(e,a,i,t,n,s*o,d),p=p.reshape([t,n,s,o]),s===1||n===1?p:e.compute(rr(p,Ui.perm),{inputs:[p],outputs:[-1]})[0]}else return a.dims.length===3&&(p=a.reshape([t,n,s,o])),s===1||n===1?p:e.compute(rr(p,Ui.perm),{inputs:[p],outputs:[-1]})[0]},pd=(e,t)=>{let s=ji(e.inputs,t),n=e.inputs[0],o=er(e.inputs,1),a=er(e.inputs,2),i=er(e.inputs,3),d=er(e.inputs,4),p=er(e.inputs,5),h=er(e.inputs,6),k=er(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let S=o&&a&&o.dims.length===4&&a.dims.length===4,u=jn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,i,0);if(S)return xn(e,u,o,a,d,void 0,h,k,p,s);if(!o||!a)throw new Error("key and value must be provided");let B=jn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,o,i,s.hiddenSize),R=jn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,i,2*s.hiddenSize);xn(e,u,B,R,d,void 0,h,k,p,s)}}),Yc,Jc,Gi,Ki,Hi,hd,qi,md=w(()=>{zt(),Bt(),Pt(),Qt(),Yc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Jc=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>s.push(Number(o))),n=s.length),it({numOutputs:n,axis:t.axis,splitSizes:s})},Gi=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Mt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Ki=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=Se.size(s),o=e[0].dataType,a=Se.normalizeAxis(t.axis,s.length),i=new Array(t.numOutputs),d=ze("input",o,s.length),p=new Array(t.numOutputs),h=[],k=[],S=0,u=[{type:12,data:n}];for(let R=0;R` ${R.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(d,...i)} ${Gi(p.length)} ${Ki(i)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${d.offsetToIndices("global_idx")}; var index = ${d.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Mt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; ${d.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},hd=(e,t)=>{Yc(e.inputs);let s=e.inputs.length===1?t:Jc(e.inputs,t);e.compute(Hi(e.inputs,s),{inputs:[0]})},qi=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return it({axis:t,numOutputs:n,splitSizes:s})}}),_d,Xi,Qi,fd,gd=w(()=>{Pt(),no(),Vi(),md(),Gr(),_d=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],o=e[2],a=e[3],i=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?d?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],S=h,u=0,B=!n||n.dims.length===0,R=Math.floor(B?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);B&&(k=R*t.numHeads);let j=a&&a.dims.length!==0,Z=i&&i.dims.length!==0;if(j&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===R)throw new Error("BSNH pastKey/pastValue is not supported");if(j&&Z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=a.dims[2]}else if(j||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te=1;if(n&&n.dims.length>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');S=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');S=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');S=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}let X=0,_e=!1,me=t.kvNumHeads?R*t.kvNumHeads:k;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(S!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=o.dims[2]}else{if(S!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=o.dims[1]*o.dims[3],_e=!0}}let ye=e.length>4?e[5]:void 0;if(ye&&ye.dims.length!==1&&ye.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:u,kvSequenceLength:S,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:me,headSize:R,vHeadSize:Math.floor(me/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_e,qkvFormat:te}},Xi=it({perm:[0,2,1,3]}),Qi=(e,t,s)=>{let n=t,o=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize]),n=e.compute(rr(n,Xi.perm),{inputs:[n],outputs:[-1]})[0]),n},fd=(e,t)=>{var Z;let s=_d(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=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,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,d=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=s.kvNumHeads?s.kvNumHeads:s.numHeads,S=it({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[u,B,R]=!o&&!a?e.compute(Hi([n],S),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,a],j=jn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,void 0,0);xn(e,j,Qi(e,B,s),Qi(e,R,s),void 0,void 0,i,d,void 0,s,p,h)}}),Yi,wd,yd,Md,Zc=w(()=>{zt(),Bt(),Gr(),Qt(),Yi=(e,t,s,n,o,a,i,d)=>{let p=ys(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,S=o*i,u=64;S===1&&(u=256);let B=[o,i,a/p],R=[o,i,2],j=["rank","type","type"],Z=[];Z.push(...vt(B,R));let te=X=>{let _e=ze("x",t.dataType,3,p),me=ze("scale",s.dataType,s.dims),ye=ze("bias",n.dataType,n.dims),$e=wt("output",1,3,2),Ae=[_e,me,ye,$e];return` var workgroup_shared : array<${k}, ${u}>; const workgroup_size = ${u}u; ${X.declareVariables(...Ae)} ${X.mainStart(u)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${h}(0); var squared_sum = ${h}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${h}(${_e.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${k}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${qs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); let squared_sum_final = ${qs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${d})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${d};${u}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:R,dataType:1}],dispatchGroup:{x:S},programUniforms:Z}),getShaderSource:te},{inputs:[t,s,n],outputs:[-1]})[0]},wd=(e,t,s)=>{let n=t[0].dims,o=n,a=2,i=n[0],d=n[1],p=Se.sizeFromDimension(n,a),h=ys(p),k=Se.size(o)/h,S=Yi(e,t[0],t[1],t[2],i,p,d,s.epsilon),u=[i,d,p/h],B=[i,d],R=["type","none"],j=Z=>{let te=ze("x",t[0].dataType,u.length,h),X=ze("scale_shift",1,B.length,2),_e=wt("output",t[0].dataType,u.length,h),me=[te,X,_e];return` ${Z.registerUniform("output_size","u32").declareVariables(...me)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${_e.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${X.getByIndices("vec2(batch, channel)")}; let value = ${te.getByOffset("global_idx")} * ${_e.type.value}(scale_shift.x) + ${_e.type.value}(scale_shift.y); ${_e.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...vt(u,B,u)]}),getShaderSource:j},{inputs:[t[0],S]})},yd=(e,t,s)=>{let n=t[0].dims,o=n,a=n[0],i=n[n.length-1],d=Se.sizeFromDimension(n,1)/i,p=ys(i),h=Se.size(o)/p,k=[{type:12,data:d},{type:12,data:Math.floor(i/p)}],S=["type","type"],u=!1,B=[0,n.length-1];for(let te=0;ten[B[X]])),j=Yi(e,R,t[1],t[2],a,d,i,s.epsilon),Z=te=>{let X=es(t[0].dataType),_e=p===1?"vec2f":`mat${p}x2f`,me=Ae=>{let Ge=Ae===0?"x":"y",lt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${X}(${lt}(scale.${Ge}))`;case 2:return`vec2<${X}>(${lt}(scale[0].${Ge}, scale[1].${Ge}))`;case 4:return`vec4<${X}>(${lt}(scale[0].${Ge}, scale[1].${Ge}, scale[2].${Ge}, scale[3].${Ge}))`;default:throw new Error(`Not supported compoents ${p}`)}},ye=ze("input",t[0].dataType,t[0].dims,p),$e=wt("output",t[0].dataType,o,p);return` @group(0) @binding(0) var input : array<${ye.type.storage}>; @group(0) @binding(1) var scale_input : array<${_e}>; @group(0) @binding(2) var output : array<${$e.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${te.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${me(0)}, ${me(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],j]})},Md=(e,t)=>{t.format==="NHWC"?yd(e,e.inputs,t):wd(e,e.inputs,t)}}),bd,vd,Td,ep=w(()=>{zt(),Bt(),Qt(),bd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},vd=(e,t,s)=>{let n=t.simplified,o=e[0].dims,a=e[1],i=!n&&e[2],d=o,p=Se.normalizeAxis(t.axis,o.length),h=Se.sizeToDimension(o,p),k=Se.sizeFromDimension(o,p),S=Se.size(a.dims),u=i?Se.size(i.dims):0;if(S!==k||i&&u!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. Size of scale and bias (if provided) must match this. Got scale size of ${S} and bias size of ${u}`);let B=[];for(let ye=0;ye1,X=s>2,_e=ye=>{let $e=es(e[0].dataType),Ae=[ze("x",e[0].dataType,e[0].dims,R),ze("scale",a.dataType,a.dims,R)];i&&Ae.push(ze("bias",i.dataType,i.dims,R)),Ae.push(wt("output",e[0].dataType,d,R)),te&&Ae.push(wt("mean_data_output",1,B)),X&&Ae.push(wt("inv_std_output",1,B));let Ge=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${ye.registerUniforms(Ge).declareVariables(...Ae)} ${ye.mainStart()} ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Pr("f32",R)}; var mean_square_vector = ${Pr("f32",R)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Fs($e,R,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${qs("mean_vector",R)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${qs("mean_square_vector",R)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Fs($e,R,"x[j + offset]")}; let f32scale = ${Fs($e,R,"scale[j]")}; output[j + offset] = ${Ae[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${Fs($e,R,"bias[j]")}`:""} ); } ${te?"mean_data_output[global_idx] = mean":""}; ${X?"inv_std_output[global_idx] = inv_std_dev":""}; }`},me=[{dims:d,dataType:e[0].dataType}];return te&&me.push({dims:B,dataType:1}),X&&me.push({dims:B,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${R};${s};${n}`,inputDependencies:j},getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:_e}},Td=(e,t)=>{bd(e.inputs),e.compute(vd(e.inputs,t,e.outputCount))}}),Ji,xd,tp=w(()=>{Bt(),ki(),ho(),Ji=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.")},xd=e=>{Ji(e.inputs);let t=ss.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(lo(e.inputs,{activation:""},t));else{let o=t[t.length-2],a=Se.size(e.inputs[0].dims.slice(0,-2)),i=Se.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&o===1&&i===1){let d=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],k=[d,p];e.compute(po(k,{activation:""},t,h),{inputs:k})}else e.compute(po(e.inputs,{activation:""},t))}}}),Zi,Ed,Pd,fs,sp,Dp=w(()=>{zt(),Bt(),Pt(),Qt(),Zi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!Se.areEqual(i.dims,[t.n,o,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(Se.size(d)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(Se.size(p)!==h)throw new Error("zeroPoints input size error.")}},Ed=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],a=t.k,i=t.n,d=s.slice(0,n-2),p=Se.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=ys(t.k),u=ys(h),B=ys(i),R=d.concat([o,i]),j=o>1&&i/B%2===0?2:1,Z=Se.size(R)/B/j,te=64,X=[],_e=[p,o,a/S],me=Se.convertShape(e[1].dims).slice();me.splice(-1,1,h/u),X.push(...vt(_e)),X.push(...vt(me)),X.push(...vt(e[2].dims)),e.length===4&&X.push(...vt(Se.convertShape(e[3].dims)));let ye=[p,o,i/B];X.push(...vt(ye));let $e=Ae=>{let Ge=_e.length,lt=ze("a",e[0].dataType,Ge,S),xt=ze("b",12,me.length,u),Kt=ze("scales",e[2].dataType,e[2].dims.length),Yt=[lt,xt,Kt],Ct=e.length===4?ze("zero_points",12,e[3].dims.length):void 0;Ct&&Yt.push(Ct);let Jt=ye.length,$t=wt("output",e[0].dataType,Jt,B),jt=es(e[0].dataType),vs=(()=>{switch(S){case 1:return`array<${jt}, 8>`;case 2:return`mat4x2<${jt}>`;case 4:return`mat2x4<${jt}>`;default:throw new Error(`${S}-component is not supported.`)}})(),Ht=()=>{let ot=` // reuse a data var input_offset = ${lt.indicesToOffset(`${lt.type.indices}(batch, row, word_offset)`)}; var a_data: ${vs}; for (var j: u32 = 0; j < ${8/S}; j++) { a_data[j] = ${lt.getByOffset("input_offset")}; input_offset++; } `;for(let Et=0;Et> 4) & b_mask); b_quantized_values = ${vs}(${Array.from({length:4},(cs,Ls)=>`${jt}(b_value_lower[${Ls}]), ${jt}(b_value_upper[${Ls}])`).join(", ")}); b_dequantized_values = ${S===1?`${vs}(${Array.from({length:8},(cs,Ls)=>`(b_quantized_values[${Ls}] - ${Ct?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${vs}(${Array(8).fill(`${Ct?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; workgroup_shared[local_id.x * ${j} + ${Math.floor(Et/B)}]${B>1?`[${Et%B}]`:""} += ${Array.from({length:8/S},(cs,Ls)=>`${S===1?`a_data[${Ls}] * b_dequantized_values[${Ls}]`:`dot(a_data[${Ls}], b_dequantized_values[${Ls}])`}`).join(" + ")}; `;return ot},Gt=()=>{let ot=` var col_index = col * ${B}; ${Ct?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${jt}(8);`} `;for(let Et=0;Et> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${Ct.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${Et} = ${jt}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return ot},Cs=()=>{let ot=`col_index = col * ${B};`;for(let Et=0;Et; var b_value_upper: vec4; var b_quantized_values: ${vs}; var b_dequantized_values: ${vs};`,ot};return` var workgroup_shared: array<${$t.type.value}, ${j*te}>; ${Ae.declareVariables(...Yt,$t)} ${Ae.mainStart([te,1,1])} let output_indices = ${$t.offsetToIndices(`(global_idx / ${te}) * ${j}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${te}) { //process one block var word_offset: u32 = block * ${t.blockSize/S}; ${Gt()} for (var word: u32 = 0; word < ${h}; word += ${u}) { ${Cs()} for (var i: u32 = 0; i < ${u}; i++) { ${Ht()} word_offset += ${8/S}; } } } workgroupBarrier(); if (local_id.x < ${j}) { var output_value: ${$t.type.value} = ${$t.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${te}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${j}; } ${$t.setByIndices(`${$t.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${S};${u};${B};${j};${te}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:R,dataType:k}],dispatchGroup:{x:Z},programUniforms:X}),getShaderSource:$e}},Pd=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],a=t.k,i=t.n,d=s.slice(0,n-2),p=Se.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=ys(t.k),u=ys(h),B=d.concat([o,i]),R=128,j=i%8===0?8:i%4===0?4:1,Z=R/j,te=Z*u*8,X=te/S,_e=te/t.blockSize,me=Se.size(B)/j,ye=[],$e=[p,o,a/S],Ae=Se.convertShape(e[1].dims).slice();Ae.splice(-1,1,h/u),ye.push(...vt($e)),ye.push(...vt(Ae)),ye.push(...vt(e[2].dims)),e.length===4&&ye.push(...vt(Se.convertShape(e[3].dims)));let Ge=[p,o,i];ye.push(...vt(Ge));let lt=xt=>{let Kt=$e.length,Yt=ze("a",e[0].dataType,Kt,S),Ct=ze("b",12,Ae.length,u),Jt=ze("scales",e[2].dataType,e[2].dims.length),$t=[Yt,Ct,Jt],jt=e.length===4?ze("zero_points",12,e[3].dims.length):void 0;jt&&$t.push(jt);let vs=Ge.length,Ht=wt("output",e[0].dataType,vs),Gt=es(e[0].dataType),Cs=()=>{switch(S){case 1:return` let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Gt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Gt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${S}-component is not supported.`)}};return` var sub_a: array<${Yt.type.value}, ${X}>; var inter_results: array, ${j}>; ${xt.declareVariables(...$t,Ht)} ${xt.mainStart([Z,j,1])} let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${j}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${_e} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${X}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${X}; a_offset += ${R}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${Yt.getByIndices(`${Yt.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${Yt.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${_e} + local_id.x; ${jt?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${jt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Gt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Gt}(8);`} let scale = ${Jt.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${Ct.getByIndices(`${Ct.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/S}; for (var i: u32 = 0; i < ${u}; i++) { ${Cs()} let b_value = ${u===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Gt}>(${Array.from({length:4},(ot,Et)=>`${Gt}(b_value_lower[${Et}]), ${Gt}(b_value_upper[${Et}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Gt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ot,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; word_offset += ${8/S}; } workgroupBarrier(); } if (local_idx < ${j}) { var output_value: ${Ht.type.value} = ${Ht.type.value}(0); for (var b = 0u; b < ${Z}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Ht.setByIndices(`${Ht.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${S};${u};${Z};${j}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:me},programUniforms:ye}),getShaderSource:lt}},fs=(e,t)=>{Zi(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Pd(e.inputs,t)):e.compute(Ed(e.inputs,t))},sp=e=>it(e)}),rp,ea,Cd,kd,Sd,$d,ta,sa,np,op=w(()=>{zt(),Bt(),Qt(),rp=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].")}},ea=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; if (k < 0) { break; } if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { break; } offset += k * i32(${Mt("uniforms.x_strides",o,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]; } `},Cd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Mt("uniforms.x_shape",o,t)}) - 1); k = k % _2n_1; if(k >= i32(${Mt("uniforms.x_shape",o,t)})) { k = _2n_1 - k; } } offset += k * i32(${Mt("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},kd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; if (k < 0) { k = 0; } if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { k = i32(${Mt("uniforms.x_shape",o,t)}) - 1; } offset += k * i32(${Mt("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},Sd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; if (k < 0) { k += i32(${Mt("uniforms.x_shape",o,t)}]); } if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { k -= i32(${Mt("uniforms.x_shape",o,t)}); } offset += k * i32(${Mt("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},$d=(e,t,s)=>{switch(s.mode){case 0:return ea(e,t,s.pads.length);case 1:return Cd(e,t,s.pads.length);case 2:return kd(e,t,s.pads.length);case 3:return Sd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},ta=(e,t)=>{let s=Se.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=Se.size(s),a=[{type:12,data:o},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...vt(e[0].dims,s));let d=["rank"],p=h=>{let k=wt("output",e[0].dataType,s.length),S=ze("x",e[0].dataType,n.length),u=S.type.value,B=$d(k,n.length,t),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&R.push({name:"constant_value",type:i?u:"f32"}),` ${h.registerUniforms(R).declareVariables(S,k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${k.offsetToIndices("global_idx")}; var value = ${u}(0); ${B} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(s)/64)},programUniforms:a}),getShaderSource:p}},sa=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,a=new Int32Array(2*o).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(d));let i=[];return a.forEach(d=>i.push(d)),{mode:t.mode,value:n,pads:i}}else return t},np=(e,t)=>{rp(e.inputs);let s=sa(e.inputs,t);e.compute(ta(e.inputs,s),{inputs:[0]})}}),Un,Co,Ad,Id,ra,Od,Fd,na,oa,Dd,Ld,ia,zd,Bd,aa,Rd,ip,Nd,jd,ap=w(()=>{Qe(),zt(),Bt(),Qt(),Un=e=>{if(T.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Co=(e,t,s)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),d=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();ws.adjustPoolAttributes(s,o,i,d,p,h);let k=ws.computePoolOutputShape(s,o,d,p,i,h,t.autoPad),S=Object.assign({},t);a?Object.assign(S,{kernelShape:i,strides:d,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(S,{kernelShape:i,strides:d,pads:h,cacheKey:t.cacheKey});let u=k.slice();return u.push(u.splice(1,1)[0]),[S,n?u:k]},Ad=(e,t)=>{let s=t.format==="NHWC",n=Se.size(e),o=Se.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],S=!!(h+k);a.push({type:12,data:d},{type:12,data:p},{type:12,data:h},{type:12,data:k}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(t.kernelShape.length===2){let B=t.kernelShape[t.kernelShape.length-2],R=t.strides[t.strides.length-2],j=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];u=!!(j+Z),a.push({type:12,data:B},{type:12,data:R},{type:12,data:j},{type:12,data:Z}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,S,u]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=Se.computeStrides(t.kernelShape);a.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[a,i,!!p,!1,!1]}},Id=(e,t,s,n,o,a,i,d,p,h,k,S)=>{let u=o.format==="NHWC",B=t.type.value,R=wt("output",t.type.tensor,n);if(o.kernelShape.length<=2){let j="",Z="",te="",X=s-(u?2:1);if(k?j=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${X}] < 0 || xIndices[${X}] >= uniforms.x_shape[${X}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:j=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,o.kernelShape.length===2){let _e=s-(u?3:2);S?Z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${_e}] < 0 || xIndices[${_e}] >= uniforms.x_shape[${_e}]) { pad += i32(uniforms.kw); continue; } `:Z=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; `,te=` } `}return` ${e.registerUniforms(p).declareVariables(t,R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var value = ${B}(${d}); var pad = 0; ${Z} ${j} ${te} ${i} output[global_idx] = value; }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let j=o.kernelShape.length,Z=o.pads.length,te="";return h?te=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:te=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(p).declareVariables(t,R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var offsets: array; var value = ${B}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${j-1}u; j++) { offsets[j] = offset / ${Mt("uniforms.kernelStrides","j",j)}; offset -= offsets[j] * ${Mt("uniforms.kernelStrides","j",j)}; } offsets[${j-1}] = offset; isPad = false; for (var j = ${s-j}u; j < ${s}u; j++) { xIndices[j] = indices[j] * ${Mt("uniforms.strides",`j - ${s-j}u`,j)} + offsets[j - ${s-j}u] - ${Mt("uniforms.pads","j - 2u",Z)}; ${te} } ${i} output[global_idx] = value; }`}},ra=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Od=e=>`${ra(e)};${e.countIncludePad}`,Fd=e=>`${ra(e)};${e.storageOrder};${e.dilations}`,na=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),oa=(e,t,s,n)=>{let[o,a]=Co(t,n,s),i=ze("x",t.dataType,t.dims.length),d=i.type.value,p="value += x_val;",h="";o.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[k,S,u,B,R]=Ad(a,o);k.push(...vt(t.dims,a));let j=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:k}),getShaderSource:Z=>Id(Z,i,t.dims.length,a.length,o,p,h,0,S,u,B,R)}},Dd=e=>{let t=e.count_include_pad!==0,s=na(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:Od(n)}},Ld=(e,t)=>{Un(e.inputs),e.compute(oa("AveragePool",e.inputs[0],!1,t))},ia={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},zd=e=>{let t=e.format;return{format:t,...ia,cacheKey:t}},Bd=(e,t)=>{Un(e.inputs),e.compute(oa("GlobalAveragePool",e.inputs[0],!0,t))},aa=(e,t,s,n)=>{let[o,a]=Co(t,n,s),i=` value = max(x_val, value); `,d="",p=ze("x",t.dataType,t.dims.length),h=["rank"],[k,S,u,B,R]=Ad(a,o);return k.push(...vt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:k}),getShaderSource:j=>Id(j,p,t.dims.length,a.length,o,i,d,t.dataType===10?-65504:-1e5,S,u,B,R)}},Rd=(e,t)=>{Un(e.inputs),e.compute(aa("MaxPool",e.inputs[0],!1,t))},ip=e=>{let t=e.storage_order,s=e.dilations,n=na(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 o={storageOrder:t,dilations:s,...n,cacheKey:""};return{...o,cacheKey:Fd(o)}},Nd=e=>{let t=e.format;return{format:t,...ia,cacheKey:t}},jd=(e,t)=>{Un(e.inputs),e.compute(aa("GlobalMaxPool",e.inputs[0],!0,t))}}),Ud,Wd,Vd,lp,Gd=w(()=>{zt(),Bt(),Pt(),Qt(),Ud=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,a)=>a===t.axis||o===e[0].dims[a]).reduce((o,a)=>o&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Wd=(e,t)=>{let s=Se.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,a=e[0].dims,i=e[1].dataType,d=Se.size(a),p=n===3||n===2,h=p?[Math.ceil(Se.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,S=e.length>2?e[2]:void 0,u=S?p?[Math.ceil(Se.size(S.dims)/4)]:S.dims:void 0,B=k.length===0||k.length===1&&k[0]===1,R=B===!1&&k.length===1,j=ys(d),Z=B&&(!p||j===4),te=Z?j:1,X=Z&&!p?j:1,_e=ze("input",p?12:n,h.length,X),me=ze("scale",i,k.length),ye=S?ze("zero_point",p?12:n,u.length):void 0,$e=wt("output",i,a.length,te),Ae=[_e,me];ye&&Ae.push(ye);let Ge=[h,k];S&&Ge.push(u);let lt=[{type:12,data:d/te},{type:12,data:s},{type:12,data:t.blockSize},...vt(...Ge,a)],xt=Kt=>{let Yt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Kt.registerUniforms(Yt).declareVariables(...Ae,$e)} ${Kt.mainStart()} ${Kt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${$e.offsetToIndices("global_idx")}; // Set input x ${p?` let input = ${_e.getByOffset("global_idx / 4")}; let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${te===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${_e.getByOffset("global_idx")};`}; // Set scale input ${B?`let scale_value= ${me.getByOffset("0")}`:R?` let scale_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${me.getByOffset("scale_index")};`:` var scale_indices: ${me.type.indices} = output_indices; let index = ${me.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${me.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${me.getByIndices("scale_indices")};`}; // Set zero-point input ${ye?B?p?` let zero_point_input = ${ye.getByOffset("0")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ye.getByOffset("0")}`:R?p?` let zero_point_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${ye.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${$e.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${ye.getByOffset("zero_point_index")};`:p?` let zero_point_offset = ${me.indicesToOffset("scale_indices")}; let zero_point_input = ${ye.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ye.getByIndices("scale_indices")};`:`let zero_point_value = ${p?o?"i32":"u32":_e.type.value}(0);`}; // Compute and write output ${$e.setByOffset("global_idx",`${$e.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:ye?["rank","rank","rank"]:["rank","rank"]},getShaderSource:xt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(d/te/64),y:1,z:1},programUniforms:lt})}},Vd=(e,t)=>{Ud(e.inputs,t),e.compute(Wd(e.inputs,t))},lp=e=>it({axis:e.axis,blockSize:e.blockSize})}),Kd,Hd,qd,up=w(()=>{Qe(),zt(),Qt(),Kd=(e,t,s)=>{let n=e===t,o=et&&s>0;if(n||o||a)throw new Error("Range these inputs' contents are invalid.")},Hd=(e,t,s,n)=>{let o=Math.abs(Math.ceil((t-e)/s)),a=[o],i=o,d=[{type:12,data:i},{type:n,data:e},{type:n,data:s},...vt(a)],p=h=>{let k=wt("output",n,a.length),S=k.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:S},{name:"delta",type:S}];return` ${h.registerUniforms(u).declareVariables(k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${S}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},qd=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),T.webgpu.validateInputContent&&Kd(t,s,n),e.compute(Hd(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Xd,Qd,Yd,Jd,dp=w(()=>{zt(),Bt(),Pt(),Qt(),Xd=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ var oldValue = 0; loop { let newValueF32 =`,a=`; let newValue = bitcast(newValueF32); let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); if res.exchanged { break; } oldValue = res.old_value; } }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` ${o}bitcast<${n}>(oldValue) + (${s})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` ${o}max(bitcast(oldValue), (${s}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${o}min(bitcast<${n}>(oldValue), (${s}))${a}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${s}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Qd=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s,a=1,i=Math.ceil(Se.size(n)/a),d=n[n.length-1],p=Se.sizeFromDimension(s,d),h=[{type:12,data:i},{type:12,data:d},{type:12,data:p},...vt(e[1].dims,e[2].dims,o)],k=S=>{let u=ze("indices",e[1].dataType,e[1].dims.length),B=ze("updates",e[2].dataType,e[2].dims.length,a),R=t.reduction!=="none"&&t.reduction!==""?sr("output",e[0].dataType,o.length):wt("output",e[0].dataType,o.length,a);return` ${S.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(u,B,R)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var data_offset = 0u; let indices_start = uniforms.last_index_dimension * global_idx; let indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${e[0].dims.length===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[i - indices_start]; let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim)); } for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; ${Xd(t.reduction,"output[data_offset + i]","value",R.type.value)} } }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h}),getShaderSource:k}},Yd=e=>it({reduction:e.reduction}),Jd=(e,t)=>{e.compute(Qd(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Zd,ec,tc,sc,rc,nc,oc,ic,ac,lc,uc,la,dc,cc,pc,hc,mc,_c,fc,Lp=w(()=>{zt(),Bt(),Pt(),Qt(),Zd=(e,t)=>{if(e.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},ec=(e,t,s)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((o,a)=>n[o]=e[a]),n},tc=(e,t,s,n,o,a)=>{let[i,d,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(k=>a.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0){if(e[d].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&s>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Zd(n,t),t.axes.length>0&&ec(n,t.axes,h).forEach((k,S)=>n[S]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>o.push(Number(k))),o.length!==0&&o.length!==h&&s>=18&&o.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(o.length!==0&&o.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 o<"u"&&n.length>0&&o.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},sc=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",rc=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",nc=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=o[i],n[i+s]=o[t.length+i]}),n):o},oc=(e,t,s,n)=>{let o=[];if(s.length>0)if(n.length>0){if(e.forEach(a=>o.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>o[a]=s[i])}else s.forEach(a=>o.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((a,i)=>Math.round(a*t[i]))}return o},ic=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return s.axes.length>0?(s.axes.forEach(a=>t[a]=n),s.axes.forEach(a=>o[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),o.forEach((a,i)=>o[i]=Math.round(a*t[i]))),o},ac=(e,t,s,n,o)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { var original_indices: array<${e.type.value}, ${s.length}>; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Mt("uniforms.scales","i",n)}; var roi_low = ${Mt("uniforms.roi","i",o)}; var roi_hi = ${Mt("uniforms.roi",`i + ${t.length}`,o)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Mt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Mt("uniforms.output_shape","i",s.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,lc=(e,t,s,n,o,a,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Mt("uniforms.scales","i",o)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Mt("uniforms.roi","i",a)}; var roi_hi = ${Mt("uniforms.roi",`i + ${s.length}`,a)}; var input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; var output_shape_i = ${Mt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,uc=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Mt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,la=(e,t,s,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",s,"batch")}; `:"",dc=(e,t,s,n,o)=>{let[a,i,d,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(row, ${s[i]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(col, ${s[d]} - 1))`)}; ${la(e,p,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${i}]; var col:${h} = originalIndices[${d}]; ${n?`if (row < 0 || row > (${s[i]} - 1) || col < 0 || col > (${s[d]} - 1)) { return ${o}; }`:""}; row = max(0, min(row, ${s[i]} - 1)); col = max(0, min(col, ${s[d]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${s.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},cc=(e,t,s,n,o,a,i,d,p,h)=>{let k=s.length===2,[S,u]=k?[0,1]:[2,3],B=e.type.value,R=j=>{let Z=j===S?"row":"col";return` fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { var output_index = ${t.indicesGet("output_indices",j)}; var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[j]}, ${n[j]}, ${s[j]}, ${a[j]}, ${a[j]} + ${s.length}); var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${s[j]} - 1))) { return ${p}; } var data: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${Z}: ${B} = originalIdx + ${B}(i); if (${Z} < 0 || ${Z} >= ${s[j]}) { ${h?`coefs[i + 1] = 0.0; continue;`:d?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[j]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",j,`u32(${Z})`)}; data[i + 1] = ${j===S?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${R(S)}; ${R(u)}; fn getCubicInterpolationCoefs(s: ${B}) -> array<${B}, 4> { var absS = abs(s); var coeffs: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${B} = 1.0 - absS; var twoMinusAbsS: ${B} = 2.0 - absS; var onePlusAbsS: ${B} = 1.0 + absS; coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; return coeffs; } fn cubicInterpolation1D(x: array<${B}, 4>, coefs: array<${B}, 4>) -> ${B} { var coefsSum: ${B} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${B} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},pc=(e,t,s,n,o)=>{let[a,i,d,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(depth, ${s[i]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(height, ${s[d]} - 1))`)}; ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; ${la(e,h,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${k} = originalIndices[${i}]; var height:${k} = originalIndices[${d}]; var width:${k} = originalIndices[${p}]; ${n?`if (depth < 0 || depth > (${s[i]} - 1) || height < 0 || height > (${s[d]} - 1) || width < 0 || (width > ${s[p]} - 1)) { return ${o}; }`:""}; depth = max(0, min(depth, ${s[i]} - 1)); height = max(0, min(height, ${s[d]} - 1)); width = max(0, min(width, ${s[p]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; var batch: u32 = ${s.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${k} = abs(depth - ${k}(depth1)); var dx2: ${k} = abs(${k}(depth2) - depth); var dy1: ${k} = abs(height - ${k}(height1)); var dy2: ${k} = abs(${k}(height2) - height); var dz1: ${k} = abs(width - ${k}(width1)); var dz2: ${k} = abs(${k}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},hc=(e,t,s,n,o,a)=>{let i=e.dims,d=nc(a,t.axes,i.length),p=oc(i,n,o,t.axes),h=n.slice();n.length===0&&(h=i.map((X,_e)=>X===0?1:p[_e]/X),t.keepAspectRatioPolicy!=="stretch"&&(p=ic(i,h,t)));let k=wt("output",e.dataType,p.length),S=ze("input",e.dataType,i.length),u=Se.size(p),B=i.length===p.length&&i.every((X,_e)=>X===p[_e]),R=t.coordinateTransformMode==="tf_crop_and_resize",j=t.extrapolationValue,Z=S.type.value,te=X=>` ${B?"":` ${sc(t.coordinateTransformMode,Z)}; ${(()=>{switch(t.mode){case"nearest":return` ${uc(S,i)}; ${rc(t.nearestMode,s,Z)}; ${lc(S,k,i,p,h.length,d.length,R)}; `;case"linear":return` ${ac(k,i,p,h.length,d.length)}; ${(()=>{if(i.length===2||i.length===4)return`${dc(S,k,i,R,j)}`;if(i.length===3||i.length===5)return`${pc(S,k,i,R,j)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(i.length===2||i.length===4)return`${cc(S,k,i,p,h,d,t.cubicCoeffA,R,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${X.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(S,k)} ${X.mainStart()} ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${B?"output[global_idx] = input[global_idx];":` let output_indices = ${k.offsetToIndices("global_idx")}; var input_indices: ${S.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${S.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${h.length>0?h:""}|${o.length>0?o:""}|${d.length>0?d:""}|${B}|${i}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:h},{type:1,data:d},...vt(i,p)]})}},mc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},_c=(e,t)=>{let s=[],n=[],o=[],a=mc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");tc(e.inputs,t,a,s,n,o),e.compute(hc(e.inputs[0],t,a,s,n,o),{inputs:[0]})},fc=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,d=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return it({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:d,mode:p,nearestMode:h})}}),Xt,gc,js,Vs=w(()=>{zt(),Bt(),Pt(),Qt(),Xt=(e,t)=>{let[s,n,o,a]=e,{numHeads:i,rotaryEmbeddingDim:d}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!Se.areEqual(n.dims,[])&&!Se.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Se.areEqual(o.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=s.dims[0],h=s.dims[s.dims.length-2],k=o.dims[0],S=Se.sizeFromDimension(s.dims,1)/h,u=d===0?o.dims[1]*2:S/i;if(d>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(u/2!==o.dims[1]&&d/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},gc=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:o,scale:a}=t,i=e[0].dims[0],d=Se.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=d/p,k=e[2].dims[1],S=o===0?k*2:h/n,u=new Array(i,p,h/S,S-k),B=Se.computeStrides(u),R=[{type:1,data:a},{type:12,data:u},{type:12,data:B},...e[0].dims.length===3?new Array({type:12,data:[d,h,S,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,S,p*S,1]}):[],...vt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],j=Z=>{let te=ze("input",e[0].dataType,e[0].dims.length),X=ze("position_ids",e[1].dataType,e[1].dims.length),_e=ze("cos_cache",e[2].dataType,e[2].dims.length),me=ze("sin_cache",e[3].dataType,e[3].dims.length),ye=wt("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:B.length},{name:"input_output_strides",type:"u32",length:B.length}]),` ${Z.declareVariables(te,X,_e,me,ye)} ${Z.mainStart(Ns)} let half_rotary_emb_dim = uniforms.${_e.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${Z.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${X.broadcastedIndicesToOffset("bsnh.xy",wt("",X.type.tensor,2))}; let position_id = u32(${X.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); let j = i + select(half_rotary_emb_dim, 1, ${s}); let re = ${te.getByOffset("i")} * ${_e.get("position_id","bsnh[3]")} - ${te.getByOffset("j")} * ${me.get("position_id","bsnh[3]")}; ${ye.setByOffset("i","re")} let im = ${te.getByOffset("i")} * ${me.get("position_id","bsnh[3]")} + ${te.getByOffset("j")} * ${_e.get("position_id","bsnh[3]")}; ${ye.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${ye.setByOffset("k",te.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:it({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:j,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(u)/Ns)},programUniforms:R})}},js=(e,t)=>{Xt(e.inputs,t),e.compute(gc(e.inputs,t))}}),Xs,un,cp,pp=w(()=>{zt(),Bt(),Qt(),Xs=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},un=(e,t,s,n)=>{let o=t.simplified,a=e[0].dims,i=Se.size(a),d=a,p=i,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],S=!o&&e.length>3,u=e.length>4,B=n&&s>1,R=n&&s>2,j=s>3,Z=64,te=ys(h),X=[{type:12,data:p},{type:12,data:te},{type:12,data:h},{type:1,data:t.epsilon}],_e=ye=>{let $e=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ae=[ze("x",e[0].dataType,e[0].dims,te),ze("skip",e[1].dataType,e[1].dims,te),ze("gamma",e[2].dataType,e[2].dims,te)];S&&Ae.push(ze("beta",e[3].dataType,e[3].dims,te)),u&&Ae.push(ze("bias",e[4].dataType,e[4].dims,te)),Ae.push(wt("output",e[0].dataType,d,te)),B&&Ae.push(wt("mean_output",1,k)),R&&Ae.push(wt("inv_std_output",1,k)),j&&Ae.push(wt("input_skip_bias_sum",e[0].dataType,d,te));let Ge=es(e[0].dataType),lt=es(1,te);return` ${ye.registerUniforms($e).declareVariables(...Ae)} var sum_shared : array<${lt}, ${Z}>; var sum_squared_shared : array<${lt}, ${Z}>; ${ye.mainStart([Z,1,1])} let ix = local_id.x; let iy = global_id.x / ${Z}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${Z}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${Z-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${u?"bias[offset1d + i]":Ge+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${j?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Fs(Ge,te,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${Z}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${qs("sum",te)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${qs("square_sum",te)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); ${B?"mean_output[global_idx] = mean;":""} ${R?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${o?"":`- ${Ge}(mean)`}) * ${Ge}(inv_std_dev) * gamma[offset1d + i] ${S?"+ beta[offset1d + i]":""}; } }`},me=[{dims:d,dataType:e[0].dataType}];return s>1&&me.push({dims:k,dataType:1}),s>2&&me.push({dims:k,dataType:1}),s>3&&me.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${te};${B};${R};${j}`,inputDependencies:e.map((ye,$e)=>"type")},getShaderSource:_e,getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:X})}},cp=(e,t)=>{Xs(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(un(e.inputs,t,e.outputCount,!1),{outputs:s})}}),wc,_,x,W,be,Ie,ke,Ye,st=w(()=>{zt(),Bt(),Pt(),Qt(),wc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((s,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},_=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},x=(e,t)=>{if(e.length>1){let s=_(e,1),n=_(e,2),o=_(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),it({starts:s,ends:n,axes:o})}else return t},W=(e,t,s,n,o)=>{let a=e;return e<0&&(a+=s[n[t]]),o[t]<0?Math.max(0,Math.min(a,s[n[t]]-1)):Math.max(0,Math.min(a,s[n[t]]))},be=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${s.length}; i >= 0; i--) { let input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; let steps_i = ${Mt("uniforms.steps","i",s.length)}; let signs_i = ${Mt("uniforms.signs","i",s.length)}; let starts_i = ${Mt("uniforms.starts","i",s.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,Ie=(e,t)=>{let s=e[0].dims,n=Se.size(s),o=t.axes.length>0?Se.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=_(e,4);a.forEach(te=>te!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(o.length).fill(1));let i=t.starts.map((te,X)=>W(te,X,s,o,a)),d=t.ends.map((te,X)=>W(te,X,s,o,a));if(o.length!==i.length||o.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==s.length)for(let te=0;teMath.sign(te));a.forEach((te,X,_e)=>{if(te<0){let me=(d[X]-i[X])/te,ye=i[X],$e=ye+me*a[X];i[X]=$e,d[X]=ye,_e[X]=-te}});let h=s.slice(0);o.forEach((te,X)=>{h[te]=Math.ceil((d[te]-i[te])/a[te])});let k={dims:h,dataType:e[0].dataType},S=wt("output",e[0].dataType,h.length),u=ze("input",e[0].dataType,e[0].dims.length),B=Se.size(h),R=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],j=[{type:12,data:B},{type:12,data:i},{type:6,data:p},{type:12,data:a},...vt(e[0].dims,h)],Z=te=>` ${te.registerUniforms(R).declareVariables(u,S)} ${be(u,S,s)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${S.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${S.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:j})}},ke=(e,t)=>{wc(e.inputs,t);let s=x(e.inputs,t);e.compute(Ie(e.inputs,s),{inputs:[0]})},Ye=e=>{let t=e.starts,s=e.ends,n=e.axes;return it({starts:t,ends:s,axes:n})}}),mt,Tt,Lt,Ut,Dt=w(()=>{zt(),Bt(),Pt(),Gr(),Qt(),mt=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Tt=(e,t)=>{let s=e.inputs[0],n=s.dims,o=Se.size(n),a=n.length,i=Se.normalizeAxis(t.axis,a),d=iGe),h[i]=a-1,h[a-1]=i,p=e.compute(rr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,S=k[a-1],u=o/S,B=ys(S),R=S/B,j=64;u===1&&(j=256);let Z=(Ae,Ge)=>Ge===4?`max(max(${Ae}.x, ${Ae}.y), max(${Ae}.z, ${Ae}.w))`:Ge===2?`max(${Ae}.x, ${Ae}.y)`:Ge===3?`max(max(${Ae}.x, ${Ae}.y), ${Ae}.z)`:Ae,te=ze("x",p.dataType,p.dims,B),X=wt("result",p.dataType,p.dims,B),_e=te.type.value,me=es(p.dataType)==="f32"?`var threadMax = ${_e}(-3.402823e+38f);`:`var threadMax = ${_e}(-65504.0h);`,ye=Ae=>` var rowMaxShared : ${_e}; var rowSumShared : ${_e}; var threadShared : array<${_e}, ${j}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${_e} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${_e}) { let index = row * row_stride + col; result[index] = value; } ${Ae.registerUniform("packedCols","i32").declareVariables(te,X)} ${Ae.mainStart(j)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${j}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${me} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${_e}(${Z("threadShared[0]",B)}); } workgroupBarrier(); // find the rows sum var threadSum = ${_e}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${_e}(${qs("threadShared[0]",B)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`,$e=e.compute({name:"Softmax",shaderCache:{hint:`${B};${j}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:R}]}),getShaderSource:ye},{inputs:[p],outputs:[d?-1:0]})[0];d&&e.compute(rr($e,h),{inputs:[$e]})},Lt=(e,t)=>{mt(e.inputs),Tt(e,t)},Ut=e=>it({axis:e.axis})}),Wt,Zt,rs,qt,os,Ss=w(()=>{zt(),Bt(),Qt(),Wt=e=>Array.from(e.getBigInt64Array(),Number),Zt=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(Wt(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")},rs=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Wt(e[1]),o=rs(s,n),a=Se.size(o),i=e[0].dataType,d=ze("input",i,s.length),p=wt("output",i,o.length),h=k=>` const inputShape = ${d.indices(...s)}; ${k.registerUniform("output_size","u32").declareVariables(d,p)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${d.type.indices}; for (var i = 0; i < ${s.length}; i++) { let input_dim_i = ${d.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; ${d.indicesSet("input_indices","i","input_dim_value")} } ${p.setByOffset("global_idx",d.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...vt(e[0].dims,o)]}),getShaderSource:h}},os=e=>{Zt(e.inputs),e.compute(qt(e.inputs),{inputs:[0]})}}),Ts,ds,Ps,$s=w(()=>{zt(),Bt(),Qt(),Ts=(e,t,s,n,o)=>{let a=wt("output_data",o,s.length,4),i=ze("a_data",t[1].dataType,t[1].dims.length,4),d=ze("b_data",t[2].dataType,t[2].dims.length,4),p=ze("c_data",t[0].dataType,t[0].dims.length,4),h,k=(S,u,B)=>`select(${u}, ${S}, ${B})`;if(!n)h=a.setByOffset("global_idx",k(i.getByOffset("global_idx"),d.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let S=(u,B,R="")=>{let j=`a_data[index_a${B}][component_a${B}]`,Z=`b_data[index_b${B}][component_b${B}]`,te=`bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`;return` let output_indices${B} = ${a.offsetToIndices(`global_idx * 4u + ${B}u`)}; let offset_a${B} = ${i.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let offset_b${B} = ${d.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`,a)}; let index_a${B} = offset_a${B} / 4u; let index_b${B} = offset_b${B} / 4u; let index_c${B} = offset_c${B} / 4u; let component_a${B} = offset_a${B} % 4u; let component_b${B} = offset_b${B} % 4u; let component_c${B} = offset_c${B} % 4u; ${u}[${B}] = ${R}(${k(j,Z,te)}); `};o===9?h=` var data = vec4(0); ${S("data",0,"u32")} ${S("data",1,"u32")} ${S("data",2,"u32")} ${S("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` ${S("output_data[global_idx]",0)} ${S("output_data[global_idx]",1)} ${S("output_data[global_idx]",2)} ${S("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(p,i,d,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`},ds=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,o=e[1].dataType,a=!(Se.areEqual(t,s)&&Se.areEqual(s,n)),i=t,d=Se.size(t);if(a){let h=ss.calcShape(ss.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");i=h,d=Se.size(i)}let p=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Ts(h,e,i,a,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:p},...vt(n,t,s,i)]})}},Ps=e=>{e.compute(ds(e.inputs))}}),Gs,Us=w(()=>{Ja(),no(),Oc(),ul(),Fc(),Xl(),Dc(),Rc(),xu(),jc(),Iu(),Uc(),Wc(),Vc(),Fp(),Nn(),Gc(),Hc(),qc(),Qc(),gd(),Zc(),ep(),tp(),Dp(),Vi(),op(),ap(),Gd(),up(),dp(),ei(),Lp(),Vs(),pp(),st(),Dt(),md(),Ss(),Gr(),bi(),$s(),Gs=new Map([["Abs",[ai]],["Acos",[cl]],["Acosh",[pl]],["Add",[jl]],["ArgMax",[Ya,ri]],["ArgMin",[si,ri]],["Asin",[li]],["Asinh",[hl]],["Atan",[ml]],["Atanh",[ui]],["Attention",[rl]],["AveragePool",[Ld,Dd]],["BatchNormalization",[il]],["BiasAdd",[ll]],["BiasSplitGelu",[Bl]],["Cast",[fl,_l]],["Ceil",[wl]],["Clip",[gl]],["Concat",[Zl,Pi]],["Conv",[Di,go]],["ConvTranspose",[Tu,Mu]],["Cos",[ci]],["Cosh",[yl]],["CumSum",[Pu,Cu]],["DepthToSpace",[$u,Au]],["DequantizeLinear",[Vd,lp]],["Div",[Ul]],["Einsum",[Bu,Ru]],["Elu",[Ml,Ln]],["Equal",[Wl]],["Erf",[pi]],["Exp",[bl]],["Expand",[Rn]],["FastGelu",[Wu]],["Floor",[vl]],["FusedConv",[Di,go]],["Gather",[Ku,Gu]],["GatherElements",[td,ed]],["GatherBlockQuantized",[Ju,Zu]],["GatherND",[qu,Xu]],["Gelu",[hi]],["Gemm",[nd,Ri]],["GlobalAveragePool",[Bd,zd]],["GlobalMaxPool",[jd,Nd]],["Greater",[Kl]],["GreaterOrEqual",[Hl]],["GridSample",[Po,Xc]],["GroupQueryAttention",[fd]],["HardSigmoid",[kl,Cl]],["InstanceNormalization",[Md]],["LayerNormalization",[Td]],["LeakyRelu",[Tl,Ln]],["Less",[xi]],["LessOrEqual",[ql]],["Log",[Fl]],["MatMul",[xd]],["MatMulNBits",[fs,sp]],["MaxPool",[Rd,ip]],["Mul",[Vl]],["MultiHeadAttention",[pd,cd]],["Neg",[mi]],["Not",[xl]],["Pad",[np]],["Pow",[Ti]],["QuickGelu",[Ll,Ln]],["Range",[qd]],["Reciprocal",[El]],["ReduceMin",[qa]],["ReduceMean",[Qo]],["ReduceMax",[Ha]],["ReduceSum",[Xa]],["ReduceProd",[Jo]],["ReduceL1",[Ga]],["ReduceL2",[Ka]],["ReduceLogSum",[Zo]],["ReduceLogSumExp",[Yo]],["ReduceSumSquare",[Qa]],["Relu",[Pl]],["Resize",[_c,fc]],["RotaryEmbedding",[js]],["ScatterND",[Jd,Yd]],["Sigmoid",[_i]],["Sin",[fi]],["Sinh",[Sl]],["Slice",[ke,Ye]],["SkipLayerNormalization",[cp]],["Split",[hd,qi]],["Sqrt",[$l]],["Softmax",[Lt,Ut]],["Sub",[Gl]],["Tan",[gi]],["Tanh",[Al]],["ThresholdedRelu",[Ol,Ln]],["Tile",[os]],["Transpose",[Uo,Ea]],["Where",[Ps]]])}),wr,Wn=w(()=>{Qe(),Ys(),Qt(),wr=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,n,o){Ve(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let h of t)d.push({binding:d.length,resource:{buffer:h.buffer}});for(let h of s)d.push({binding:d.length,resource:{buffer:h.buffer}});o&&d.push({binding:d.length,resource:o});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}i.setPipeline(e.computePipeline),i.setBindGroup(0,p),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ne(e.programInfo.name)}dispose(){}build(e,t){Ve(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let o=Tn(t,this.backend.device.limits),a=e.getShaderSource(o),i=`${n.join(` `)} ${o.additionalImplementations} ${a}`,d=s.createShaderModule({code:i,label:e.name});is("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let p=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ne(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&n<=o)return[t,s,n];let a=t*s*n,i=Math.ceil(Math.sqrt(a));if(i>o){if(i=Math.ceil(Math.cbrt(a)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),ua,nr,Cr,da,ko,ca=w(()=>{Qe(),zt(),Ys(),Dn(),yt(),Us(),Wn(),ua=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{var o,a;let n=e.name;return(o=e.shaderCache)!=null&&o.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${ua(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Cr=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},da=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]}},ko=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let s=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},o=a=>t.features.has(a)&&s.push(a)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups")&&o("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new da(this.device),this.adapterInfo=new Cr(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ct(this),this.programManager=new wr(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,yn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ve(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=B);let j=Number(B-this.queryTimeBase),Z=Number(R-this.queryTimeBase);if(!Number.isSafeInteger(j)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:S.map(te=>({dims:te.dims,dataType:xr(te.dataType)})),outputsMetadata:u.map(te=>({dims:te.dims,dataType:xr(te.dataType)})),kernelId:i,kernelType:p,kernelName:h,programName:k,startTime:j,endTime:Z});else{let te="";S.forEach((_e,me)=>{te+=`input[${me}]: [${_e.dims}] | ${xr(_e.dataType)}, `});let X="";u.forEach((_e,me)=>{X+=`output[${me}]: [${_e.dims}] | ${xr(_e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${p}|${h}|${k}" ${te}${X}execution time: ${Z-j} ns`)}Re("GPU",`${k}::${B}::${R}`)}e.unmap(),this.pendingQueries.delete(e)}),Ne()}run(e,t,s,n,o,a){Ve(e.name);let i=[];for(let X=0;X_e):s;if(k.length!==d.length)throw new Error(`Output size ${k.length} must be equal to ${d.length}.`);let S=[],u=[];for(let X=0;X=a)throw new Error(`Invalid output index: ${k[X]}`);if(k[X]===-3)continue;let _e=k[X]===-1,me=k[X]===-2,ye=_e||me?o(d[X].dataType,d[X].dims):n(k[X],d[X].dataType,d[X].dims);if(S.push(ye),ye.data===0)continue;let $e=this.gpuDataManager.get(ye.data);if(!$e)throw new Error(`no GPU data for output: ${ye.data}`);if(_e&&this.temporaryData.push($e),me){let Ae=this.kernelPersistentData.get(this.currentKernelId);Ae||(Ae=[],this.kernelPersistentData.set(this.currentKernelId,Ae)),Ae.push($e)}u.push($e)}if(i.length!==t.length||u.length!==S.length){if(u.length===0)return Ne(e.name),S;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let B;if(h){let X=0,_e=[];h.forEach(Ae=>{let Ge=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ge.length===0)return;let lt=Ae.type===10?2:4,xt,Kt;Ae.type===10?(Kt=Ge.length>4?16:Ge.length>2?8:Ge.length*lt,xt=Ge.length>4?16:lt*Ge.length):(Kt=Ge.length<=2?Ge.length*lt:16,xt=16),X=Math.ceil(X/Kt)*Kt,_e.push(X);let Yt=Ae.type===10?8:4;X+=Ge.length>4?Math.ceil(Ge.length/Yt)*xt:Ge.length*lt});let me=16;X=Math.ceil(X/me)*me;let ye=new ArrayBuffer(X);h.forEach((Ae,Ge)=>{let lt=_e[Ge],xt=typeof Ae.data=="number"?[Ae.data]:Ae.data;if(Ae.type===6)new Int32Array(ye,lt,xt.length).set(xt);else if(Ae.type===12)new Uint32Array(ye,lt,xt.length).set(xt);else if(Ae.type===10)new Uint16Array(ye,lt,xt.length).set(xt);else if(Ae.type===1)new Float32Array(ye,lt,xt.length).set(xt);else throw new Error(`Unsupported uniform type: ${xr(Ae.type)}`)});let $e=this.gpuDataManager.create(X,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer($e.buffer,0,ye,0,X),this.gpuDataManager.release($e.id),B={offset:0,size:X,buffer:$e.buffer}}let R=this.programManager.normalizeDispatchGroupSize(p),j=R[1]===1&&R[2]===1,Z=nr(e,t,j),te=this.programManager.getArtifact(Z);if(te||(te=this.programManager.build(e,R),this.programManager.setArtifact(Z,te),is("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&te.uniformVariablesInfo){if(h.length!==te.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${te.uniformVariablesInfo.length}, got ${h.length} in program "${te.programInfo.name}".`);for(let X=0;X`[ProgramManager] run "${e.name}" (key=${Z}) with ${R[0]}x${R[1]}x${R[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let X={kernelId:this.currentKernelId,programName:te.programInfo.name,inputTensorViews:t,outputTensorViews:S};this.pendingKernels.push(X),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(X)}return this.programManager.run(te,i,u,R,B),Ne(e.name),S}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let o=Gs.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let o=n.kernelType,a=n.kernelName,i=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),is("info",()=>`[WebGPU] Start to run kernel "[${o}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),i(t,d[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${a}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${o}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let a=o.get(t),i=this.gpuDataManager.registerExternalBuffer(s,n,a);return o.set(t,[i,s]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await Pe(this,e,t);return Mn(n.buffer,s)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){is("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){is("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){is("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),So,xs,Ds,Lr,qr,dn,$o,pa,yc=w(()=>{Ys(),So=1,xs=()=>So++,Ds=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Lr=(e,t)=>{let s=Ds.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*s/8):0},qr=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 Lr(this.dataType,this.tensorShape)}destroy(){is("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}},dn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Lr(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else is("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},$o=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=xs();return this.tensorTrackersById.set(e,new dn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n){is("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){is("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let o=xs(),a=new qr({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(o,new dn(this,a)),this.externalTensors.add(a),o}async getCachedTensor(e,t,s,n,o){let a=this.backend.currentSessionId;for(let[p,h]of this.freeTensors.entries())if(h.sameTypeAndShape(e,t)){is("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}let i=this.backend.currentContext;is("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let d=await i.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new qr({sessionId:a,context:i,tensor:d,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},pa=(...e)=>new $o(...e)}),Ao,hp,ha,ma=w(()=>{zt(),Ot(),Dn(),yc(),Ys(),Ao=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),hp=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((o,a)=>o===n[a]&&e[o]===t[o])},ha=class{constructor(e){this.tensorManager=pa(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],yn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>hp(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(o=>o.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){is("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let o=Ao.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,o,s,n)}uploadTensor(e,t){if(!_t().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");is("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return Mn(s,t)}}registerMLTensor(e,t,s){let n=Ao.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(this.currentContext,e,n,s);return is("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,s,n,o,a){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let d=a.get(i);if(!d)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+s>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=d.slice(t,t+s).buffer,h;switch(o.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return is("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`),n.constant(o,h)}flush(){}}}),_a={};v(_a,{init:()=>Oo});var Io,fa,Oo,zp=w(()=>{zt(),ca(),Ys(),Bt(),ma(),Io=class Jm{constructor(t,s,n,o){this.module=t,this.dataType=s,this.data=n,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Se.size(t)!==Se.size(this.dims))throw new Error("Invalid new shape");return new Jm(this.module,this.dataType,this.data,t)}},fa=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,o=s/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*o++,a));let i=Number(e.getValue(n*o++,a));this.outputCount=Number(e.getValue(n*o++,a)),this.customDataOffset=Number(e.getValue(n*o++,"*")),this.customDataSize=Number(e.getValue(n*o++,a));let d=[];for(let p=0;ptypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(t==null?void 0:t.outputs)??[],o=(d,p,h)=>new Io(this.module,p,this.output(d,h),h),a=(d,p)=>{let h=ur(d,p);if(!h)throw new Error(`Unsupported data type: ${d}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new Io(this.module,d,k,p)};return this.backend.run(e,s,n,o,a,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,o=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,o);for(let i=0;i{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new ko;await a.initialize(s,n),o("webgpu",[a,i=>a.alloc(Number(i)),i=>a.free(i),(i,d,p,h=!1)=>{if(h)is("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(i)}, dst=${Number(d)}, size=${Number(p)}`),a.memcpy(Number(i),Number(d));else{is("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(i)}, gpuDataId=${Number(d)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(i>>>0),Number(i>>>0)+Number(p));a.upload(Number(d),k)}},async(i,d,p)=>{is("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${d}, size=${p}`),await a.download(Number(i),()=>t.HEAPU8.subarray(Number(d)>>>0,Number(d+p)>>>0))},(i,d,p)=>a.createKernel(i,Number(d),p,t.UTF8ToString(t._JsepGetNodeName(Number(d)))),i=>a.releaseKernel(i),(i,d,p,h)=>{is("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${i}, contextDataOffset=${d}`);let k=new fa(t,a,Number(d));return a.computeKernel(Number(i),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new ha(s);o("webnn",[a,()=>a.reserveTensorId(),i=>a.releaseTensorId(i),async(i,d,p,h)=>a.ensureTensor(i,d,p,h),(i,d)=>{a.uploadTensor(i,d)},async(i,d)=>a.downloadTensor(i,d)])}}}),mp,Mc,Xr,Ks,gh,_p,Bp,Rp,Np,jp,Up,Wp,wh=w(()=>{en(),Jn(),zt(),Ot(),tr(),$n(),mp=(e,t)=>{_t()._OrtInit(e,t)!==0&&ts("Can't initialize onnxruntime.")},Mc=async e=>{mp(e.wasm.numThreads,tn(e.logLevel))},Xr=async(e,t)=>{{let s=(zp(),M(_a)).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 o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);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:o,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await s("webgpu",_t(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",_t(),e)}}},Ks=new Map,gh=e=>{let t=_t(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&ts("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(s)}},_p=e=>{let t=_t(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Bp=async(e,t)=>{var S,u,B;let s,n,o=_t();Array.isArray(e)?[s,n]=e:e.buffer===o.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=_p(e);let a=0,i=0,d=0,p=[],h=[],k=[];try{if([i,p]=Sn(t),(t==null?void 0:t.externalData)&&o.mountExternalData){let ye=[];for(let $e of t.externalData){let Ae=typeof $e=="string"?$e:$e.path;ye.push(wn(typeof $e=="string"?$e:$e.data).then(Ge=>{o.mountExternalData(Ae,Ge)}))}await Promise.all(ye)}for(let ye of(t==null?void 0:t.executionProviders)??[])if((typeof ye=="string"?ye:ye.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof ye!="string"){let $e=ye,Ae=$e==null?void 0:$e.context,Ge=$e==null?void 0:$e.gpuDevice,lt=$e==null?void 0:$e.deviceType,xt=$e==null?void 0:$e.powerPreference;Ae?o.currentContext=Ae:Ge?o.currentContext=await o.jsepCreateMLContext(Ge):o.currentContext=await o.jsepCreateMLContext({deviceType:lt,powerPreference:xt})}else o.currentContext=await o.jsepCreateMLContext();break}a=await o._OrtCreateSession(s,n,i),a===0&&ts("Can't create a session."),(S=o.jsepOnCreateSession)==null||S.call(o),o.currentContext&&(o.jsepRegisterMLContext(a,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[R,j]=gh(a),Z=!!(t!=null&&t.enableGraphCapture),te=[],X=[],_e=[];for(let ye=0;yeye==="gpu-buffer"||ye==="ml-tensor")&&(d=o._OrtCreateBinding(a),d===0&&ts("Can't create IO binding."),me={handle:d,outputPreferredLocations:_e,outputPreferredLocationsEncoded:_e.map(ye=>Er(ye))}),Ks.set(a,[a,h,k,me,Z,!1]),[a,te,X]}catch(R){throw h.forEach(j=>o._OrtFree(j)),k.forEach(j=>o._OrtFree(j)),d!==0&&o._OrtReleaseBinding(d)!==0&&ts("Can't release IO binding."),a!==0&&o._OrtReleaseSession(a)!==0&&ts("Can't release session."),R}finally{o._free(s),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&ts("Can't release session options."),p.forEach(R=>o._free(R)),(B=o.unmountExternalData)==null||B.call(o)}},Rp=e=>{var p;let t=_t(),s=Ks.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,a,i,d]=s;i&&(d&&t._OrtClearBoundOutputs(i.handle)!==0&&ts("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&ts("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),o.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&ts("Can't release session."),Ks.delete(e)},Np=(e,t,s,n,o,a=!1)=>{if(!e){t.push(0);return}let i=_t(),d=i.PTR_SIZE,p=e[0],h=e[1],k=e[3],S,u;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let j=e[2].gpuBuffer;u=ur(Wr(p),h);let Z=i.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');S=Z(n,o,j,u)}else if(k==="ml-tensor"){let j=e[2].mlTensor;u=ur(Wr(p),h);let Z=i.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');S=Z(j,Wr(p),h)}else{let j=e[2];if(Array.isArray(j)){u=d*j.length,S=i._malloc(u),s.push(S);for(let Z=0;Zi.setValue(R+te*d,Z,d===4?"i32":"i64"));let j=i._OrtCreateTensor(Wr(p),S,u,R,h.length,Er(k));j===0&&ts(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(j)}finally{i.stackRestore(B)}},jp=async(e,t,s,n,o,a)=>{var Kt,Yt;let i=_t(),d=i.PTR_SIZE,p=Ks.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],S=p[2],u=p[3],B=p[4],R=p[5],j=t.length,Z=n.length,te=0,X=[],_e=[],me=[],ye=[],$e=i.stackSave(),Ae=i.stackAlloc(j*d),Ge=i.stackAlloc(j*d),lt=i.stackAlloc(Z*d),xt=i.stackAlloc(Z*d);try{(Kt=i.jsepOnRunStart)==null||Kt.call(i,h),[te,X]=Nr(a);for(let $t=0;$tIs*Es,1);Cs=xr(cs);let Lo=u==null?void 0:u.outputPreferredLocations[n[$t]];if(Cs==="string"){if(Lo==="gpu-buffer"||Lo==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Is=[];for(let Es=0;Es0){let Is=i.jsepGetBuffer;if(!Is)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Es=Is(ot),Gn=ur(cs,cn);if(Gn===void 0||!gn(Cs))throw new Error(`Unsupported data type: ${Cs}`);Gt=!0,Jt.push([Cs,Hs,{gpuBuffer:Es,download:i.jsepCreateDownloader(Es,Gn,Cs),dispose:()=>{i._OrtReleaseTensor(jt)!==0&&ts("Can't release tensor.")}},"gpu-buffer"])}else if(Lo==="ml-tensor"&&cn>0){let Is=i.jsepEnsureTensor;if(!Is)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ur(cs,cn)===void 0||!sn(Cs))throw new Error(`Unsupported data type: ${Cs}`);let Es=await Is(ot,cs,Hs,!1);Gt=!0,Jt.push([Cs,Hs,{mlTensor:Es,download:i.jsepCreateMLTensorDownloader(ot,Cs),dispose:()=>{i.jsepReleaseTensorId(ot),i._OrtReleaseTensor(jt)}},"ml-tensor"])}else{let Is=fn(Cs),Es=new Is(cn);new Uint8Array(Es.buffer,Es.byteOffset,Es.byteLength).set(i.HEAPU8.subarray(ot,ot+Es.byteLength)),Jt.push([Cs,Hs,Es,"cpu"])}}finally{i.stackRestore(vs),Cs==="string"&&ot&&i._free(ot),Gt||i._OrtReleaseTensor(jt)}}return u&&!B&&(i._OrtClearBoundOutputs(u.handle)!==0&&ts("Can't clear bound outputs."),Ks.set(e,[h,k,S,u,B,!1])),Jt}finally{i.stackRestore($e),_e.forEach(Ct=>i._OrtReleaseTensor(Ct)),me.forEach(Ct=>i._OrtReleaseTensor(Ct)),ye.forEach(Ct=>i._free(Ct)),te!==0&&i._OrtReleaseRunOptions(te),X.forEach(Ct=>i._free(Ct))}},Up=e=>{let t=_t(),s=Ks.get(e);if(!s)throw new Error("invalid session id");let n=s[0],o=t._OrtEndProfiling(n);o===0&&ts("Can't get an profile file name."),t._OrtFree(o)},Wp=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Vn,yr,ga,bc,vc,fp,Vp,gp,Fo,Do,yh,Mh,bh,vh,Th,xh,Eh,Ph,Ch=w(()=>{Qe(),wh(),Ot(),$r(),Vn=()=>!!T.wasm.proxy&&typeof document<"u",ga=!1,bc=!1,vc=!1,gp=new Map,Fo=(e,t)=>{let s=gp.get(e);s?s.push(t):gp.set(e,[t])},Do=()=>{if(ga||!bc||vc||!yr)throw new Error("worker not ready")},yh=e=>{switch(e.data.type){case"init-wasm":ga=!1,e.data.err?(vc=!0,Vp[1](e.data.err)):(bc=!0,Vp[0]()),fp&&(URL.revokeObjectURL(fp),fp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=gp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Mh=async()=>{if(!bc){if(ga)throw new Error("multiple calls to 'initWasm()' detected.");if(vc)throw new Error("previous call to 'initWasm()' failed.");if(ga=!0,Vn())return new Promise((e,t)=>{yr==null||yr.terminate(),Jr().then(([s,n])=>{try{yr=n,yr.onerror=a=>t(a),yr.onmessage=yh,Vp=[e,t];let o={type:"init-wasm",in:T};yr.postMessage(o),fp=s}catch(o){t(o)}},t)});try{await nt(T.wasm),await Mc(T),bc=!0}catch(e){throw vc=!0,e}finally{ga=!1}}},bh=async e=>{if(Vn())return Do(),new Promise((t,s)=>{Fo("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:T}};yr.postMessage(n)});await Xr(T,e)},vh=async e=>Vn()?(Do(),new Promise((t,s)=>{Fo("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};yr.postMessage(n,[e.buffer])})):_p(e),Th=async(e,t)=>{if(Vn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Do(),new Promise((s,n)=>{Fo("create",[s,n]);let o={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),yr.postMessage(o,a)})}else return Bp(e,t)},xh=async e=>{if(Vn())return Do(),new Promise((t,s)=>{Fo("release",[t,s]);let n={type:"release",in:e};yr.postMessage(n)});Rp(e)},Eh=async(e,t,s,n,o,a)=>{if(Vn()){if(s.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return Do(),new Promise((i,d)=>{Fo("run",[i,d]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};yr.postMessage(h,Wp(p))})}else return jp(e,t,s,n,o,a)},Ph=async e=>{if(Vn())return Do(),new Promise((t,s)=>{Fo("end-profiling",[t,s]);let n={type:"end-profiling",in:e};yr.postMessage(n)});Up(e)}}),Gp,kh,Sh,l_=w(()=>{Qe(),Ch(),zt(),rt(),$n(),Gp=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},kh=e=>{switch(e[3]){case"cpu":return new ce(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!gn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:o}=e[2];return ce.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!sn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:o}=e[2];return ce.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Sh=class{async fetchModelAndCopyToWasmMemory(e){return vh(await wn(e))}async loadModel(e,t){Ve();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Th(s,t),Ne()}async dispose(){return xh(this.sessionId)}async run(e,t,s){Ve();let n=[],o=[];Object.entries(e).forEach(S=>{let u=S[0],B=S[1],R=this.inputNames.indexOf(u);if(R===-1)throw new Error(`invalid input '${u}'`);n.push(B),o.push(R)});let a=[],i=[];Object.entries(t).forEach(S=>{let u=S[0],B=S[1],R=this.outputNames.indexOf(u);if(R===-1)throw new Error(`invalid output '${u}'`);a.push(B),i.push(R)});let d=n.map((S,u)=>Gp(S,()=>`input "${this.inputNames[o[u]]}"`)),p=a.map((S,u)=>S?Gp(S,()=>`output "${this.outputNames[i[u]]}"`):null),h=await Eh(this.sessionId,o,d,i,p,s),k={};for(let S=0;SHp,initializeFlags:()=>Kp,wasmBackend:()=>Ah});var Kp,Hp,Ah,u_=w(()=>{Qe(),Ch(),l_(),$r(),Kp=()=>{if((typeof T.wasm.initTimeout!="number"||T.wasm.initTimeout<0)&&(T.wasm.initTimeout=0),T.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof T.wasm.proxy!="boolean"&&(T.wasm.proxy=!1),typeof T.wasm.trace!="boolean"&&(T.wasm.trace=!1),typeof T.wasm.numThreads!="number"||!Number.isInteger(T.wasm.numThreads)||T.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)T.wasm.numThreads=1;else{let e=typeof navigator>"u"?U("node:os").cpus().length:navigator.hardwareConcurrency;T.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Hp=class{async init(e){Kp(),await Mh(),await bh(e)}async createInferenceSessionHandler(e,t){let s=new Sh;return await s.loadModel(e,t),Promise.resolve(s)}},Ah=new Hp});Qe(),Qe(),Qe();var d_="1.21.0-dev.20241205-d27fecd3d3",c_=Oe;{let e=(u_(),M($h)).wasmBackend;H("webgpu",e,5),H("webnn",e,5),H("cpu",e,10),H("wasm",e,10)}Object.defineProperty(T.versions,"web",{value:d_,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */},"./src/backends/onnx.js":(De,A,r)=>{var f;r.r(A),r.d(A,{Tensor:()=>U.Tensor,createInferenceSession:()=>ie,deviceToExecutionProviders:()=>H,isONNXProxy:()=>Q,isONNXTensor:()=>z});var L=r("./src/env.js"),N=r("?2ce3"),J=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"),U=r("./node_modules/onnxruntime-common/dist/esm/index.js");const w=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),v=[];let y,M;const b=Symbol.for("onnxruntime");if(b in globalThis)M=globalThis[b];else if(L.apis.IS_NODE_ENV){switch(M=N??(f||(f=r.t(N,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),y=["cpu"]}else M=J,L.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),L.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),y=["wasm"];const D=M.InferenceSession;function H(F=null){if(!F)return y;switch(F){case"auto":return v;case"gpu":return v.filter($=>["webgpu","cuda","dml","webnn-gpu"].includes($))}if(v.includes(F))return[w[F]??F];throw new Error(`Unsupported device: "${F}". Should be one of: ${v.join(", ")}.`)}let re=null;async function ie(F,$,g){re&&await re;const C=D.create(F,$);re??(re=C);const T=await C;return T.config=g,T}function z(F){return F instanceof M.Tensor}const V=M==null?void 0:M.env;V!=null&&V.wasm&&(V.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${L.env.version}/dist/`,V.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(V.wasm.numThreads=1)),V!=null&&V.webgpu&&(V.webgpu.powerPreference="high-performance");function Q(){var F;return(F=V==null?void 0:V.wasm)==null?void 0:F.proxy}L.env.backends.onnx=V},"./src/base/feature_extraction_utils.js":(De,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>J,validate_audio_inputs:()=>U});var f=r("./src/utils/constants.js"),L=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class J extends L.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,y){const M=await(0,N.getModelJSON)(v,f.FEATURE_EXTRACTOR_NAME,!0,y);return new this(M)}}function U(w,v){var y;if(!(w instanceof Float32Array||w instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((y=w==null?void 0:w.constructor)==null?void 0:y.name)??typeof w} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(De,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>F,post_process_instance_segmentation:()=>Q,post_process_object_detection:()=>b,post_process_panoptic_segmentation:()=>V,post_process_semantic_segmentation:()=>D});var f=r("./src/utils/generic.js"),L=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/utils/image.js");var J=r("./src/utils/core.js"),U=r("./src/utils/hub.js"),w=r("./src/utils/constants.js");function v($,g,C=0,T=null){const ee=$/g;let Y=(0,N.bankers_round)(ee)*g;return T!==null&&Y>T&&(Y=Math.floor(ee)*g),Yg&&he.push(Be)}else{let Be=(0,N.max)(se.data)[1];if(Be===fe-1||(Ee=(0,N.softmax)(se.data),Ee[Be]Xe*Le[(oe+1)%2])),qe.boxes.push(et),qe.classes.push(Be),qe.scores.push(Ee[Be])}}Ce.push(qe)}return Ce}function D($,g=null){const C=$.logits,T=C.dims[0];if(g!==null&&g.length!==T)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ee=[];for(let Y=0;YLe[he]&&(Le[he]=se[he],qe[he]=ue)}const Ue=new Array(de.dims[0]);for(let ue=0;ueue!==void 0);ee.push({segmentation:Te,labels:ut})}return ee}function H($,g,C,T){const ee=[],Y=[],le=[];for(let de=0;de<$.dims[0];++de){const fe=$[de],Ce=g[de],Te=(0,N.max)(fe.data)[1];if(Te===T)continue;const qe=(0,N.softmax)(fe.data)[Te];qe>C&&(ee.push(Ce),Y.push(qe),le.push(Te))}return[ee,Y,le]}function re($,g,C,T=.5,ee=.8){const Y=[];let le=0,de=0;const fe=g[C].data;for(let Te=0;Te<$.length;++Te)$[Te]===C&&(Y.push(Te),++le),fe[Te]>=T&&++de;let Ce=le>0&&de>0;return Ce&&(Ce=le/de>ee),[Ce,Y]}function ie($,g,C,T,ee,Y=null,le=null){const[de,fe]=le??$[0].dims,Ce=new L.Tensor("int32",new Int32Array(de*fe),[de,fe]),Te=[];if(le!==null)for(let ue=0;ue<$.length;++ue)$[ue]=(0,L.interpolate)($[ue],le,"bilinear",!1);const Le=new Int32Array($[0].data.length),qe=new Float32Array($[0].data.length);for(let ue=0;ue<$.length;++ue){let se=g[ue];const he=$[ue].data;for(let Ee=0;Eeqe[Ee]&&(Le[Ee]=ue,qe[Ee]=he[Ee])}let Ue=0;const ut=Ce.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max($,g)/Math.min($,g)}`);let Y=Math.round($/C)*C,le=Math.round(g/C)*C;if(Y*le>ee){const de=Math.sqrt($*g/ee);Y=Math.floor($/de/C)*C,le=Math.floor(g/de/C)*C}else if(Y*leY?Ce=Math.floor(Y*fe/ee):Y>ee&&(fe=Math.floor(ee*Ce/Y)),await g.resize(Ce,fe,{resample:T}))}async crop_margin(g,C=200){const T=g.clone().grayscale(),ee=(0,N.min)(T.data)[0],le=(0,N.max)(T.data)[0]-ee;if(le===0)return g;const de=C/255;let fe=T.width,Ce=T.height,Te=0,Le=0;const qe=T.data;for(let Ue=0;Uethis.preprocess(Y)));return{pixel_values:(0,L.stack)(T.map(Y=>Y.pixel_values),0),original_sizes:T.map(Y=>Y.original_size),reshaped_input_sizes:T.map(Y=>Y.reshaped_input_size)}}static async from_pretrained(g,C){const T=await(0,U.getModelJSON)(g,w.IMAGE_PROCESSOR_NAME,!0,C);return new this(T)}}},"./src/base/processing_utils.js":(De,A,r)=>{r.r(A),r.d(A,{Processor:()=>J});var f=r("./src/utils/constants.js"),L=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class J extends L.Callable{constructor(w,v){super(),this.config=w,this.components=v}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(w,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(w,{tokenize:!1,...v})}batch_decode(...w){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...w)}async _call(w,...v){for(const y of[this.image_processor,this.feature_extractor,this.tokenizer])if(y)return y(w,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(w,v){const[y,M]=await Promise.all([this.uses_processor_config?(0,N.getModelJSON)(w,f.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(b=>b in this).map(async b=>{const D=await this[b].from_pretrained(w,v);return[b.replace(/_class$/,""),D]})).then(Object.fromEntries)]);return new this(y,M)}}ge(J,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),ge(J,"uses_processor_config",!1)},"./src/configs.js":(De,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>v,PretrainedConfig:()=>w,getKeyValueShapes:()=>U});var f=r("./src/utils/core.js"),L=r("./src/utils/hub.js");async function N(y,M){return await(0,L.getModelJSON)(y,"config.json",!0,M)}function J(y){const M={};let b={};switch(y.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":b=J(y.text_config);break;case"moondream1":b=J(y.phi_config);break;case"musicgen":b=J(y.decoder);break;case"multi_modality":b=J(y.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":M.num_heads="num_attention_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size",M.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.dim_kv="head_dim";break;case"openelm":M.num_heads="num_kv_heads",M.num_layers="num_transformer_layers",M.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":M.num_heads="num_heads",M.num_layers="num_layers",M.hidden_size="hidden_size";break;case"bloom":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="hidden_size";break;case"mpt":M.num_heads="n_heads",M.num_layers="n_layers",M.hidden_size="d_model";break;case"exaone":M.num_heads="num_key_value_heads",M.num_layers="num_layers",M.dim_kv="head_dim",M.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":M.num_decoder_layers="num_decoder_layers",M.num_decoder_heads="num_heads",M.decoder_dim_kv="d_kv",M.num_encoder_layers="num_layers",M.num_encoder_heads="num_heads",M.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="d_model",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="d_model";break;case"speecht5":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="hidden_size",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="hidden_size";break;case"trocr":M.num_encoder_layers=M.num_decoder_layers="decoder_layers",M.num_encoder_heads=M.num_decoder_heads="decoder_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":M.num_encoder_layers=M.num_decoder_layers="num_hidden_layers",M.num_encoder_heads=M.num_decoder_heads="num_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const H=J(y.decoder),re="num_decoder_layers"in H,ie=(0,f.pick)(y,["model_type","is_encoder_decoder"]);return re?(ie.num_decoder_layers=H.num_decoder_layers,ie.num_decoder_heads=H.num_decoder_heads,ie.decoder_hidden_size=H.decoder_hidden_size,ie.num_encoder_layers=H.num_encoder_layers,ie.num_encoder_heads=H.num_encoder_heads,ie.encoder_hidden_size=H.encoder_hidden_size):(ie.num_layers=H.num_layers,ie.num_heads=H.num_heads,ie.hidden_size=H.hidden_size),ie}const D={...b,...(0,f.pick)(y,["model_type","multi_query","is_encoder_decoder"])};for(const H in M)D[H]=y[M[H]];return D}function U(y,{prefix:M="past_key_values",batch_size:b=1}={}){const D={},H=y.normalized_config;if(H.is_encoder_decoder&&"num_encoder_heads"in H&&"num_decoder_heads"in H){const re=H.encoder_dim_kv??H.encoder_hidden_size/H.num_encoder_heads,ie=H.decoder_dim_kv??H.decoder_hidden_size/H.num_decoder_heads,z=[b,H.num_encoder_heads,0,re],V=[b,H.num_decoder_heads,0,ie];for(let Q=0;Q{var T,ee;r.r(A),r.d(A,{apis:()=>ie,env:()=>g});var f=r("?569f"),L=r("?3f59"),N=r("?154a");const J="3.2.1",U=typeof window<"u"&&typeof window.document<"u",w=typeof self<"u"&&((T=self.constructor)==null?void 0:T.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,y=typeof navigator<"u"&&"gpu"in navigator,M=typeof navigator<"u"&&"ml"in navigator,b=typeof process<"u",D=b&&((ee=process==null?void 0:process.release)==null?void 0:ee.name)==="node",H=!C(f),re=!C(L),ie=Object.freeze({IS_BROWSER_ENV:U,IS_WEBWORKER_ENV:w,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:y,IS_WEBNN_AVAILABLE:M,IS_PROCESS_AVAILABLE:b,IS_NODE_ENV:D,IS_FS_AVAILABLE:H,IS_PATH_AVAILABLE:re}),z=H&&re;let V="./";if(z){const Y=Object({url:self.location.href}).url;Y?V=L.dirname(L.dirname(N.fileURLToPath(Y))):typeof __dirname<"u"&&(V=L.dirname(__dirname))}const Q=z?L.join(V,"/.cache/"):null,F="/models/",$=z?L.join(V,F):F,g={version:J,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(U||w),localModelPath:$,useFS:H,useBrowserCache:v,useFSCache:H,cacheDir:Q,useCustomCache:!1,customCache:null};function C(Y){return Object.keys(Y).length===0}},"./src/generation/configuration_utils.js":(De,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>L});var f=r("./src/utils/core.js");class L{constructor(J){ge(this,"max_length",20);ge(this,"max_new_tokens",null);ge(this,"min_length",0);ge(this,"min_new_tokens",null);ge(this,"early_stopping",!1);ge(this,"max_time",null);ge(this,"do_sample",!1);ge(this,"num_beams",1);ge(this,"num_beam_groups",1);ge(this,"penalty_alpha",null);ge(this,"use_cache",!0);ge(this,"temperature",1);ge(this,"top_k",50);ge(this,"top_p",1);ge(this,"typical_p",1);ge(this,"epsilon_cutoff",0);ge(this,"eta_cutoff",0);ge(this,"diversity_penalty",0);ge(this,"repetition_penalty",1);ge(this,"encoder_repetition_penalty",1);ge(this,"length_penalty",1);ge(this,"no_repeat_ngram_size",0);ge(this,"bad_words_ids",null);ge(this,"force_words_ids",null);ge(this,"renormalize_logits",!1);ge(this,"constraints",null);ge(this,"forced_bos_token_id",null);ge(this,"forced_eos_token_id",null);ge(this,"remove_invalid_values",!1);ge(this,"exponential_decay_length_penalty",null);ge(this,"suppress_tokens",null);ge(this,"streamer",null);ge(this,"begin_suppress_tokens",null);ge(this,"forced_decoder_ids",null);ge(this,"guidance_scale",null);ge(this,"num_return_sequences",1);ge(this,"output_attentions",!1);ge(this,"output_hidden_states",!1);ge(this,"output_scores",!1);ge(this,"return_dict_in_generate",!1);ge(this,"pad_token_id",null);ge(this,"bos_token_id",null);ge(this,"eos_token_id",null);ge(this,"encoder_no_repeat_ngram_size",0);ge(this,"decoder_start_token_id",null);ge(this,"generation_kwargs",{});Object.assign(this,(0,f.pick)(J,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(De,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>z,ForcedBOSTokenLogitsProcessor:()=>w,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>N,LogitsProcessorList:()=>U,LogitsWarper:()=>J,MinLengthLogitsProcessor:()=>H,MinNewTokensLengthLogitsProcessor:()=>re,NoBadWordsLogitsProcessor:()=>ie,NoRepeatNGramLogitsProcessor:()=>b,RepetitionPenaltyLogitsProcessor:()=>D,SuppressTokensAtBeginLogitsProcessor:()=>y,TemperatureLogitsWarper:()=>V,TopKLogitsWarper:()=>F,TopPLogitsWarper:()=>Q,WhisperTimeStampLogitsProcessor:()=>M});var f=r("./src/utils/generic.js");r("./src/utils/tensor.js");var L=r("./src/utils/maths.js");class N extends f.Callable{_call(g,C){throw Error("`_call` should be implemented in a subclass")}}class J extends f.Callable{_call(g,C){throw Error("`_call` should be implemented in a subclass")}}class U extends f.Callable{constructor(){super(),this.processors=[]}push(g){this.processors.push(g)}extend(g){this.processors.push(...g)}_call(g,C){let T=C;for(const ee of this.processors)T=ee(g,T);return T}[Symbol.iterator](){return this.processors.values()}}class w extends N{constructor(g){super(),this.bos_token_id=g}_call(g,C){for(let T=0;T=1&&Y[Y.length-1]>=this.timestamp_begin,de=Y.length<2||Y[Y.length-2]>=this.timestamp_begin;if(le&&(de?ee.subarray(this.timestamp_begin).fill(-1/0):ee.subarray(0,this.eos_token_id).fill(-1/0)),g[T].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Le=this.timestamp_begin+this.max_initial_timestamp_index;ee.subarray(Le+1).fill(-1/0)}const fe=(0,L.log_softmax)(ee),Ce=Math.log(fe.subarray(this.timestamp_begin).map(Math.exp).reduce((Le,qe)=>Le+qe)),Te=(0,L.max)(fe.subarray(0,this.timestamp_begin))[0];Ce>Te&&ee.subarray(0,this.timestamp_begin).fill(-1/0)}return C}}class b extends N{constructor(g){super(),this.no_repeat_ngram_size=g}getNgrams(g){const C=g.length,T=[];for(let Y=0;Y1 to use the classifier free guidance processor, got guidance scale ${g}.`);this.guidance_scale=g}_call(g,C){if(C.dims[0]!==2*g.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${C.dims[0]} for the logits and ${g.length} for the input ids.`);const T=g.length,ee=C.slice([0,T],null),Y=C.slice([T,C.dims[0]],null);for(let le=0;le1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${g}`);if(!Number.isInteger(T)||T<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${T}`);this.top_p=g,this.filter_value=C,this.min_tokens_to_keep=T}}class F extends J{constructor(g,{filter_value:C=-1/0,min_tokens_to_keep:T=1}={}){if(super(),!Number.isInteger(g)||g<0)throw new Error(`\`top_k\` must be a positive integer, but is ${g}`);this.top_k=Math.max(g,T),this.filter_value=C}}},"./src/generation/logits_sampler.js":(De,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>J});var f=r("./src/utils/generic.js"),L=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class J extends f.Callable{constructor(M){super(),this.generation_config=M}async _call(M){return this.sample(M)}async sample(M){throw Error("sample should be implemented in subclasses.")}getLogits(M,b){let D=M.dims.at(-1),H=M.data;if(b===-1)H=H.slice(-D);else{let re=b*D;H=H.slice(re,re+D)}return H}randomSelect(M){let b=0;for(let H=0;H1)return new v(M);if(M.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${M.num_return_sequences}.`);return new U(M)}}class U extends J{async sample(M){const b=(0,N.max)(M.data)[1];return[[BigInt(b),0]]}}class w extends J{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[D,H]=await(0,L.topk)(M,b),re=(0,N.softmax)(D.data);return Array.from({length:this.generation_config.num_beams},()=>{const ie=this.randomSelect(re);return[H.data[ie],Math.log(re[ie])]})}}class v extends J{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[D,H]=await(0,L.topk)(M,b),re=(0,N.softmax)(D.data);return Array.from({length:this.generation_config.num_beams},(ie,z)=>[H.data[z],Math.log(re[z])])}}},"./src/generation/stopping_criteria.js":(De,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>U,InterruptableStoppingCriteria:()=>w,MaxLengthCriteria:()=>J,StoppingCriteria:()=>L,StoppingCriteriaList:()=>N});var f=r("./src/utils/generic.js");class L extends f.Callable{_call(y,M){throw Error("StoppingCriteria needs to be subclassed")}}class N extends f.Callable{constructor(){super(),this.criteria=[]}push(y){this.criteria.push(y)}extend(y){y instanceof N?y=y.criteria:y instanceof L&&(y=[y]),this.criteria.push(...y)}_call(y,M){const b=new Array(y.length).fill(!1);for(const D of this.criteria){const H=D(y,M);for(let re=0;reM.length>=this.max_length)}}class U extends L{constructor(y){super(),Array.isArray(y)||(y=[y]),this.eos_token_id=y}_call(y,M){return y.map(b=>{const D=b.at(-1);return this.eos_token_id.some(H=>D==H)})}}class w extends L{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(y,M){return new Array(y.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(De,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>J,TextStreamer:()=>w,WhisperTextStreamer:()=>v});var f=r("./src/utils/core.js"),L=r("./src/tokenizers.js"),N=r("./src/env.js");class J{put(M){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const U=N.apis.IS_PROCESS_AVAILABLE?y=>process.stdout.write(y):y=>console.log(y);class w extends J{constructor(M,{skip_prompt:b=!1,callback_function:D=null,token_callback_function:H=null,decode_kwargs:re={},...ie}={}){super(),this.tokenizer=M,this.skip_prompt=b,this.callback_function=D??U,this.token_callback_function=H,this.decode_kwargs={...re,...ie},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(M){var re;if(M.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const b=M[0];(re=this.token_callback_function)==null||re.call(this,b),this.token_cache=(0,f.mergeArrays)(this.token_cache,b);const D=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let H;D.endsWith(` `)?(H=D.slice(this.print_len),this.token_cache=[],this.print_len=0):D.length>0&&(0,L.is_chinese_char)(D.charCodeAt(D.length-1))?(H=D.slice(this.print_len),this.print_len+=H.length):(H=D.slice(this.print_len,D.lastIndexOf(" ")+1),this.print_len+=H.length),this.on_finalized_text(H,!1)}end(){let M;this.token_cache.length>0?(M=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):M="",this.next_tokens_are_prompt=!0,this.on_finalized_text(M,!0)}on_finalized_text(M,b){var D,H;M.length>0&&((D=this.callback_function)==null||D.call(this,M)),b&&this.callback_function===U&&N.apis.IS_PROCESS_AVAILABLE&&((H=this.callback_function)==null||H.call(this,` `))}}class v extends w{constructor(M,{skip_prompt:b=!1,callback_function:D=null,token_callback_function:H=null,on_chunk_start:re=null,on_chunk_end:ie=null,on_finalize:z=null,time_precision:V=.02,skip_special_tokens:Q=!0,decode_kwargs:F={}}={}){super(M,{skip_prompt:b,callback_function:D,token_callback_function:H,decode_kwargs:{skip_special_tokens:Q,...F}}),this.timestamp_begin=M.timestamp_begin,this.on_chunk_start=re,this.on_chunk_end=ie,this.on_finalize=z,this.time_precision=V,this.waiting_for_timestamp=!1}put(M){var D,H;if(M.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const b=M[0];if(b.length===1){const re=Number(b[0])-this.timestamp_begin;if(re>=0){const ie=re*this.time_precision;this.waiting_for_timestamp?(D=this.on_chunk_end)==null||D.call(this,ie):(H=this.on_chunk_start)==null||H.call(this,ie),this.waiting_for_timestamp=!this.waiting_for_timestamp,M=[[]]}}return super.put(M)}end(){var M;super.end(),(M=this.on_finalize)==null||M.call(this)}}},"./src/models.js":(De,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>rr,ASTModel:()=>xa,ASTPreTrainedModel:()=>jo,AlbertForMaskedLM:()=>vn,AlbertForQuestionAnswering:()=>bn,AlbertForSequenceClassification:()=>Dn,AlbertModel:()=>Mn,AlbertPreTrainedModel:()=>Ys,AutoModel:()=>Gd,AutoModelForAudioClassification:()=>lc,AutoModelForAudioFrameClassification:()=>la,AutoModelForCTC:()=>ac,AutoModelForCausalLM:()=>Yd,AutoModelForDepthEstimation:()=>hc,AutoModelForDocumentQuestionAnswering:()=>dc,AutoModelForImageClassification:()=>ec,AutoModelForImageFeatureExtraction:()=>fc,AutoModelForImageMatting:()=>cc,AutoModelForImageSegmentation:()=>tc,AutoModelForImageToImage:()=>pc,AutoModelForMaskGeneration:()=>ic,AutoModelForMaskedLM:()=>Jd,AutoModelForNormalEstimation:()=>mc,AutoModelForObjectDetection:()=>nc,AutoModelForPoseEstimation:()=>_c,AutoModelForQuestionAnswering:()=>dp,AutoModelForSemanticSegmentation:()=>sc,AutoModelForSeq2SeqLM:()=>qd,AutoModelForSequenceClassification:()=>Kd,AutoModelForSpeechSeq2Seq:()=>up,AutoModelForTextToSpectrogram:()=>Xd,AutoModelForTextToWaveform:()=>Qd,AutoModelForTokenClassification:()=>Hd,AutoModelForUniversalSegmentation:()=>rc,AutoModelForVision2Seq:()=>Zd,AutoModelForXVector:()=>uc,AutoModelForZeroShotObjectDetection:()=>oc,BartForConditionalGeneration:()=>Pt,BartForSequenceClassification:()=>hs,BartModel:()=>it,BartPretrainedModel:()=>ht,BaseModelOutput:()=>Fe,BeitForImageClassification:()=>on,BeitModel:()=>Dc,BeitPreTrainedModel:()=>Pi,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>Ne,BertForSequenceClassification:()=>je,BertForTokenClassification:()=>Ve,BertModel:()=>ve,BertPreTrainedModel:()=>ce,BlenderbotForConditionalGeneration:()=>Ns,BlenderbotModel:()=>Bt,BlenderbotPreTrainedModel:()=>Zs,BlenderbotSmallForConditionalGeneration:()=>_s,BlenderbotSmallModel:()=>es,BlenderbotSmallPreTrainedModel:()=>hr,BloomForCausalLM:()=>Pl,BloomModel:()=>El,BloomPreTrainedModel:()=>mi,CLIPModel:()=>Da,CLIPPreTrainedModel:()=>nn,CLIPSegForImageSegmentation:()=>Wa,CLIPSegModel:()=>Ua,CLIPSegPreTrainedModel:()=>qo,CLIPTextModel:()=>$c,CLIPTextModelWithProjection:()=>La,CLIPVisionModel:()=>Ac,CLIPVisionModelWithProjection:()=>Ic,CamembertForMaskedLM:()=>Jr,CamembertForQuestionAnswering:()=>$r,CamembertForSequenceClassification:()=>Sr,CamembertForTokenClassification:()=>Rr,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>br,CausalLMOutput:()=>un,CausalLMOutputWithPast:()=>cp,ChineseCLIPModel:()=>Ba,ChineseCLIPPreTrainedModel:()=>_r,ClapAudioModelWithProjection:()=>ud,ClapModel:()=>ad,ClapPreTrainedModel:()=>Eo,ClapTextModelWithProjection:()=>ld,CodeGenForCausalLM:()=>ro,CodeGenModel:()=>Za,CodeGenPreTrainedModel:()=>Ja,CohereForCausalLM:()=>pl,CohereModel:()=>cl,CoherePreTrainedModel:()=>ai,ConvBertForMaskedLM:()=>Ft,ConvBertForQuestionAnswering:()=>gs,ConvBertForSequenceClassification:()=>At,ConvBertForTokenClassification:()=>ns,ConvBertModel:()=>St,ConvBertPreTrainedModel:()=>It,ConvNextForImageClassification:()=>yu,ConvNextModel:()=>wu,ConvNextPreTrainedModel:()=>Li,ConvNextV2ForImageClassification:()=>bu,ConvNextV2Model:()=>Mu,ConvNextV2PreTrainedModel:()=>wo,DPTForDepthEstimation:()=>pu,DPTModel:()=>cu,DPTPreTrainedModel:()=>Ii,DebertaForMaskedLM:()=>pr,DebertaForQuestionAnswering:()=>lr,DebertaForSequenceClassification:()=>Ir,DebertaForTokenClassification:()=>Zr,DebertaModel:()=>Ar,DebertaPreTrainedModel:()=>ar,DebertaV2ForMaskedLM:()=>Ot,DebertaV2ForQuestionAnswering:()=>ts,DebertaV2ForSequenceClassification:()=>ls,DebertaV2ForTokenClassification:()=>vr,DebertaV2Model:()=>_t,DebertaV2PreTrainedModel:()=>nt,DecisionTransformerModel:()=>Md,DecisionTransformerPreTrainedModel:()=>yd,DeiTForImageClassification:()=>nu,DeiTModel:()=>Si,DeiTPreTrainedModel:()=>uo,DepthAnythingForDepthEstimation:()=>hu,DepthAnythingPreTrainedModel:()=>zc,DepthProForDepthEstimation:()=>fo,DepthProPreTrainedModel:()=>_u,DetrForObjectDetection:()=>Ci,DetrForSegmentation:()=>Kr,DetrModel:()=>an,DetrObjectDetectionOutput:()=>Ws,DetrPreTrainedModel:()=>Or,DetrSegmentationOutput:()=>eu,Dinov2ForImageClassification:()=>Tu,Dinov2Model:()=>vu,Dinov2PreTrainedModel:()=>yo,DistilBertForMaskedLM:()=>kn,DistilBertForQuestionAnswering:()=>Tr,DistilBertForSequenceClassification:()=>en,DistilBertForTokenClassification:()=>jr,DistilBertModel:()=>Nr,DistilBertPreTrainedModel:()=>tr,DonutSwinModel:()=>Nc,DonutSwinPreTrainedModel:()=>gu,EfficientNetForImageClassification:()=>pd,EfficientNetModel:()=>jn,EfficientNetPreTrainedModel:()=>Wi,ElectraForMaskedLM:()=>Qs,ElectraForQuestionAnswering:()=>Br,ElectraForSequenceClassification:()=>ir,ElectraForTokenClassification:()=>Yr,ElectraModel:()=>As,ElectraPreTrainedModel:()=>ks,EsmForMaskedLM:()=>Jn,EsmForSequenceClassification:()=>Wr,EsmForTokenClassification:()=>xr,EsmModel:()=>Sn,EsmPreTrainedModel:()=>Ur,ExaoneForCausalLM:()=>rl,ExaoneModel:()=>sl,ExaonePreTrainedModel:()=>xn,FalconForCausalLM:()=>id,FalconModel:()=>od,FalconPreTrainedModel:()=>Hr,FastViTForImageClassification:()=>Ul,FastViTModel:()=>jl,FastViTPreTrainedModel:()=>cr,Florence2ForConditionalGeneration:()=>Aa,Florence2PreTrainedModel:()=>$a,GLPNForDepthEstimation:()=>Rc,GLPNModel:()=>Di,GLPNPreTrainedModel:()=>Fi,GPT2LMHeadModel:()=>fr,GPT2Model:()=>Va,GPT2PreTrainedModel:()=>Xo,GPTBigCodeForCausalLM:()=>ri,GPTBigCodeModel:()=>Ya,GPTBigCodePreTrainedModel:()=>si,GPTJForCausalLM:()=>ti,GPTJModel:()=>ei,GPTJPreTrainedModel:()=>Zo,GPTNeoForCausalLM:()=>qa,GPTNeoModel:()=>Ha,GPTNeoPreTrainedModel:()=>Yo,GPTNeoXForCausalLM:()=>Qa,GPTNeoXModel:()=>Xa,GPTNeoXPreTrainedModel:()=>Jo,Gemma2ForCausalLM:()=>fl,Gemma2Model:()=>_l,Gemma2PreTrainedModel:()=>ui,GemmaForCausalLM:()=>ml,GemmaModel:()=>hl,GemmaPreTrainedModel:()=>li,GraniteForCausalLM:()=>us,GraniteModel:()=>dl,GranitePreTrainedModel:()=>ul,GroupViTModel:()=>Nl,GroupViTPreTrainedModel:()=>Rl,HieraForImageClassification:()=>po,HieraModel:()=>ou,HieraPreTrainedModel:()=>co,HubertForCTC:()=>qu,HubertForSequenceClassification:()=>Xu,HubertModel:()=>Hu,HubertPreTrainedModel:()=>Fp,IJepaForImageClassification:()=>Il,IJepaModel:()=>yi,IJepaPreTrainedModel:()=>io,Idefics3ForConditionalGeneration:()=>Go,Idefics3PreTrainedModel:()=>Oa,ImageMattingOutput:()=>pp,JAISLMHeadModel:()=>Ka,JAISModel:()=>Ga,JAISPreTrainedModel:()=>Qo,JinaCLIPModel:()=>Ra,JinaCLIPPreTrainedModel:()=>so,JinaCLIPTextModel:()=>Na,JinaCLIPVisionModel:()=>ja,LlamaForCausalLM:()=>tl,LlamaModel:()=>el,LlamaPreTrainedModel:()=>ni,LlavaForConditionalGeneration:()=>eo,LlavaOnevisionForConditionalGeneration:()=>ka,LlavaPreTrainedModel:()=>Ca,LongT5ForConditionalGeneration:()=>Pe,LongT5Model:()=>Me,LongT5PreTrainedModel:()=>ae,M2M100ForConditionalGeneration:()=>Bn,M2M100Model:()=>Mo,M2M100PreTrainedModel:()=>Iu,MBartForCausalLM:()=>Js,MBartForConditionalGeneration:()=>ws,MBartForSequenceClassification:()=>Rs,MBartModel:()=>Se,MBartPreTrainedModel:()=>ss,MPNetForMaskedLM:()=>wn,MPNetForQuestionAnswering:()=>In,MPNetForSequenceClassification:()=>$n,MPNetForTokenClassification:()=>An,MPNetModel:()=>zt,MPNetPreTrainedModel:()=>Er,MT5ForConditionalGeneration:()=>yt,MT5Model:()=>ct,MT5PreTrainedModel:()=>He,MarianMTModel:()=>Au,MarianModel:()=>$u,MarianPreTrainedModel:()=>zi,MaskFormerForInstanceSegmentation:()=>fu,MaskFormerModel:()=>Oi,MaskFormerPreTrainedModel:()=>go,MaskedLMOutput:()=>Vs,MgpstrForSceneTextRecognition:()=>ep,MgpstrModelOutput:()=>vd,MgpstrPreTrainedModel:()=>Td,MistralForCausalLM:()=>qc,MistralModel:()=>nd,MistralPreTrainedModel:()=>Ri,MobileBertForMaskedLM:()=>tn,MobileBertForQuestionAnswering:()=>sn,MobileBertForSequenceClassification:()=>gn,MobileBertModel:()=>fn,MobileBertPreTrainedModel:()=>ur,MobileLLMForCausalLM:()=>ol,MobileLLMModel:()=>nl,MobileLLMPreTrainedModel:()=>no,MobileNetV1ForImageClassification:()=>hd,MobileNetV1Model:()=>Hi,MobileNetV1PreTrainedModel:()=>Ki,MobileNetV2ForImageClassification:()=>_d,MobileNetV2Model:()=>md,MobileNetV2PreTrainedModel:()=>qi,MobileNetV3ForImageClassification:()=>fd,MobileNetV3Model:()=>Qi,MobileNetV3PreTrainedModel:()=>Xi,MobileNetV4ForImageClassification:()=>wd,MobileNetV4Model:()=>Yi,MobileNetV4PreTrainedModel:()=>gd,MobileViTForImageClassification:()=>Kl,MobileViTModel:()=>Gl,MobileViTPreTrainedModel:()=>Ti,MobileViTV2ForImageClassification:()=>ql,MobileViTV2Model:()=>Hl,MobileViTV2PreTrainedModel:()=>xi,ModelOutput:()=>Je,ModernBertForMaskedLM:()=>ft,ModernBertForSequenceClassification:()=>dt,ModernBertForTokenClassification:()=>gt,ModernBertModel:()=>at,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>Sa,MoonshineForConditionalGeneration:()=>Pa,MoonshineModel:()=>Sc,MoonshinePreTrainedModel:()=>Wo,MptForCausalLM:()=>kl,MptModel:()=>Cl,MptPreTrainedModel:()=>_i,MultiModalityCausalLM:()=>bd,MultiModalityPreTrainedModel:()=>Zc,MusicgenForCausalLM:()=>Jc,MusicgenForConditionalGeneration:()=>Gi,MusicgenModel:()=>Yc,MusicgenPreTrainedModel:()=>Vi,NomicBertModel:()=>ne,NomicBertPreTrainedModel:()=>O,OPTForCausalLM:()=>$l,OPTModel:()=>Sl,OPTPreTrainedModel:()=>fi,Olmo2ForCausalLM:()=>ll,Olmo2Model:()=>al,Olmo2PreTrainedModel:()=>ii,OlmoForCausalLM:()=>Oc,OlmoModel:()=>il,OlmoPreTrainedModel:()=>oi,OpenELMForCausalLM:()=>wl,OpenELMModel:()=>gl,OpenELMPreTrainedModel:()=>di,OwlViTForObjectDetection:()=>Yl,OwlViTModel:()=>Ql,OwlViTPreTrainedModel:()=>Xl,Owlv2ForObjectDetection:()=>Zl,Owlv2Model:()=>Jl,Owlv2PreTrainedModel:()=>Ei,PaliGemmaForConditionalGeneration:()=>Ia,PaliGemmaPreTrainedModel:()=>mr,PatchTSMixerForPrediction:()=>Pd,PatchTSMixerModel:()=>Ed,PatchTSMixerPreTrainedModel:()=>Zi,PatchTSTForPrediction:()=>tp,PatchTSTModel:()=>xd,PatchTSTPreTrainedModel:()=>Ji,Phi3ForCausalLM:()=>xl,Phi3Model:()=>Tl,Phi3PreTrainedModel:()=>hi,Phi3VForCausalLM:()=>Ko,Phi3VPreTrainedModel:()=>Fa,PhiForCausalLM:()=>vl,PhiModel:()=>bl,PhiPreTrainedModel:()=>pi,PreTrainedModel:()=>oe,PretrainedMixin:()=>fs,PvtForImageClassification:()=>Ll,PvtModel:()=>Dl,PvtPreTrainedModel:()=>Mi,PyAnnoteForAudioFrameClassification:()=>Bu,PyAnnoteModel:()=>zu,PyAnnotePreTrainedModel:()=>bo,QuestionAnsweringModelOutput:()=>Xs,Qwen2ForCausalLM:()=>Ln,Qwen2Model:()=>yl,Qwen2PreTrainedModel:()=>ci,Qwen2VLForConditionalGeneration:()=>oo,Qwen2VLPreTrainedModel:()=>Ml,RTDetrForObjectDetection:()=>Lc,RTDetrModel:()=>tu,RTDetrObjectDetectionOutput:()=>zn,RTDetrPreTrainedModel:()=>ao,ResNetForImageClassification:()=>au,ResNetModel:()=>iu,ResNetPreTrainedModel:()=>ho,RoFormerForMaskedLM:()=>Oe,RoFormerForQuestionAnswering:()=>pt,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>rt,RoFormerModel:()=>pe,RoFormerPreTrainedModel:()=>K,RobertaForMaskedLM:()=>Pr,RobertaForQuestionAnswering:()=>Mt,RobertaForSequenceClassification:()=>Fs,RobertaForTokenClassification:()=>qs,RobertaModel:()=>ys,RobertaPreTrainedModel:()=>vt,SamImageSegmentationOutput:()=>Su,SamModel:()=>ku,SamPreTrainedModel:()=>jc,SapiensForDepthEstimation:()=>mu,SapiensForNormalEstimation:()=>_o,SapiensForSemanticSegmentation:()=>Bc,SapiensPreTrainedModel:()=>mo,SegformerForImageClassification:()=>Qc,SegformerForSemanticSegmentation:()=>er,SegformerModel:()=>Xc,SegformerPreTrainedModel:()=>Po,Seq2SeqLMOutput:()=>Lp,SequenceClassifierOutput:()=>Xt,SiglipModel:()=>za,SiglipPreTrainedModel:()=>dr,SiglipTextModel:()=>to,SiglipVisionModel:()=>Ho,SpeechT5ForSpeechToText:()=>ed,SpeechT5ForTextToSpeech:()=>td,SpeechT5HifiGan:()=>Hc,SpeechT5Model:()=>Kc,SpeechT5PreTrainedModel:()=>xo,SqueezeBertForMaskedLM:()=>yn,SqueezeBertForQuestionAnswering:()=>is,SqueezeBertForSequenceClassification:()=>Fn,SqueezeBertModel:()=>On,SqueezeBertPreTrainedModel:()=>Vr,StableLmForCausalLM:()=>Ui,StableLmModel:()=>cd,StableLmPreTrainedModel:()=>ji,Starcoder2ForCausalLM:()=>ln,Starcoder2Model:()=>Dr,Starcoder2PreTrainedModel:()=>gr,Swin2SRForImageSuperResolution:()=>Ai,Swin2SRModel:()=>du,Swin2SRPreTrainedModel:()=>En,SwinForImageClassification:()=>$i,SwinModel:()=>uu,SwinPreTrainedModel:()=>lu,T5ForConditionalGeneration:()=>q,T5Model:()=>P,T5PreTrainedModel:()=>xe,TableTransformerForObjectDetection:()=>su,TableTransformerModel:()=>ki,TableTransformerObjectDetectionOutput:()=>ru,TableTransformerPreTrainedModel:()=>lo,TokenClassifierOutput:()=>js,TrOCRForCausalLM:()=>rd,TrOCRPreTrainedModel:()=>sd,UniSpeechForCTC:()=>Nu,UniSpeechForSequenceClassification:()=>ju,UniSpeechModel:()=>Bi,UniSpeechPreTrainedModel:()=>vo,UniSpeechSatForAudioFrameClassification:()=>Vc,UniSpeechSatForCTC:()=>Uu,UniSpeechSatForSequenceClassification:()=>Wu,UniSpeechSatModel:()=>Wc,UniSpeechSatPreTrainedModel:()=>Rn,ViTForImageClassification:()=>Al,ViTMAEModel:()=>zl,ViTMAEPreTrainedModel:()=>bi,ViTMSNForImageClassification:()=>Fc,ViTMSNModel:()=>Bl,ViTMSNPreTrainedModel:()=>vi,ViTModel:()=>wi,ViTPreTrainedModel:()=>gi,VisionEncoderDecoderModel:()=>Vo,VitMatteForImageMatting:()=>Vl,VitMattePreTrainedModel:()=>Wl,VitPoseForPoseEstimation:()=>Fl,VitPosePreTrainedModel:()=>Ol,VitsModel:()=>Ni,VitsModelOutput:()=>wc,VitsPreTrainedModel:()=>dd,Wav2Vec2BertForCTC:()=>Gu,Wav2Vec2BertForSequenceClassification:()=>Ku,Wav2Vec2BertModel:()=>Vu,Wav2Vec2BertPreTrainedModel:()=>To,Wav2Vec2ForAudioFrameClassification:()=>Lu,Wav2Vec2ForCTC:()=>Fu,Wav2Vec2ForSequenceClassification:()=>Du,Wav2Vec2Model:()=>Ou,Wav2Vec2PreTrainedModel:()=>Fr,WavLMForAudioFrameClassification:()=>Gc,WavLMForCTC:()=>Yu,WavLMForSequenceClassification:()=>Ju,WavLMForXVector:()=>Zu,WavLMModel:()=>Qu,WavLMPreTrainedModel:()=>Nn,WeSpeakerResNetModel:()=>Uc,WeSpeakerResNetPreTrainedModel:()=>Ru,WhisperForConditionalGeneration:()=>Gr,WhisperModel:()=>Ea,WhisperPreTrainedModel:()=>Uo,XLMForQuestionAnswering:()=>Zn,XLMForSequenceClassification:()=>sr,XLMForTokenClassification:()=>rn,XLMModel:()=>ze,XLMPreTrainedModel:()=>bs,XLMRobertaForMaskedLM:()=>ba,XLMRobertaForQuestionAnswering:()=>Ta,XLMRobertaForSequenceClassification:()=>No,XLMRobertaForTokenClassification:()=>va,XLMRobertaModel:()=>Qt,XLMRobertaPreTrainedModel:()=>Tn,XLMWithLMHeadModel:()=>wt,XVectorOutput:()=>gc,YolosForObjectDetection:()=>Pu,YolosModel:()=>Eu,YolosObjectDetectionOutput:()=>Cu,YolosPreTrainedModel:()=>xu});var f=r("./src/configs.js"),L=r("./src/backends/onnx.js"),N=r("./src/utils/dtypes.js"),J=r("./src/utils/generic.js"),U=r("./src/utils/core.js"),w=r("./src/utils/hub.js"),v=r("./src/utils/constants.js"),y=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),b=r("./src/utils/tensor.js"),D=r("./src/utils/image.js"),H=r("./src/utils/maths.js"),re=r("./src/generation/stopping_criteria.js"),ie=r("./src/generation/logits_sampler.js"),z=r("./src/env.js"),V=r("./src/models/whisper/generation_whisper.js"),Q=r("./src/models/whisper/common_whisper.js");const F={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},$=new Map,g=new Map,C=new Map;async function T(_,x,W){var Ts;const be=((Ts=W.config)==null?void 0:Ts["transformers.js_config"])??{};let Ie=W.device??be.device;Ie&&typeof Ie!="string"&&(Ie.hasOwnProperty(x)?Ie=Ie[x]:(console.warn(`device not specified for "${x}". Using the default device.`),Ie=null));const ke=Ie??(z.apis.IS_NODE_ENV?"cpu":"wasm"),Ye=(0,L.deviceToExecutionProviders)(ke);let st=W.dtype??be.dtype;if(typeof st!="string"&&(st&&st.hasOwnProperty(x)?st=st[x]:(st=N.DEFAULT_DEVICE_DTYPE_MAPPING[ke]??N.DATA_TYPES.fp32,console.warn(`dtype not specified for "${x}". Using the default dtype (${st}) for this device (${ke}).`))),st===N.DATA_TYPES.auto){let ds=be.dtype;typeof ds!="string"&&(ds=ds[x]),ds&&ds!==N.DATA_TYPES.auto&&N.DATA_TYPES.hasOwnProperty(ds)?st=ds:st=N.DEFAULT_DEVICE_DTYPE_MAPPING[ke]??N.DATA_TYPES.fp32}const mt=st;if(N.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(mt)){if(mt===N.DATA_TYPES.fp16&&ke==="webgpu"&&!await(0,N.isWebGpuFp16Supported)())throw new Error(`The device (${ke}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${mt}. Should be one of: ${Object.keys(N.DATA_TYPES).join(", ")}`);const Tt=be.kv_cache_dtype?typeof be.kv_cache_dtype=="string"?be.kv_cache_dtype:be.kv_cache_dtype[mt]??"float32":void 0;if(Tt&&!["float32","float16"].includes(Tt))throw new Error(`Invalid kv_cache_dtype: ${Tt}. Should be one of: float32, float16`);const Lt={dtype:mt,kv_cache_dtype:Tt},Ut=N.DEFAULT_DTYPE_SUFFIX_MAPPING[mt],Dt=`${W.subfolder??""}/${x}${Ut}.onnx`,Wt={...W.session_options};Wt.executionProviders??(Wt.executionProviders=Ye);const Zt=be.free_dimension_overrides;Zt?Wt.freeDimensionOverrides??(Wt.freeDimensionOverrides=Zt):ke.startsWith("webnn")&&!Wt.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const rs=(0,w.getModelFile)(_,Dt,!0,W),qt=W.use_external_data_format??be.use_external_data_format;let os=[];if(qt&&(qt===!0||typeof qt=="object"&&qt.hasOwnProperty(x)&&qt[x]===!0)){if(z.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const ds=`${x}${Ut}.onnx_data`,Ps=`${W.subfolder??""}/${ds}`;os.push(new Promise(async($s,Gs)=>{const Us=await(0,w.getModelFile)(_,Ps,!0,W);$s({path:ds,data:Us})}))}else Wt.externalData!==void 0&&(os=Wt.externalData.map(async ds=>{if(typeof ds.data=="string"){const Ps=await(0,w.getModelFile)(_,ds.data,!0,W);return{...ds,data:Ps}}return ds}));if(os.length>0&&(Wt.externalData=await Promise.all(os)),ke==="webgpu"){const ds=(0,f.getKeyValueShapes)(W.config,{prefix:"present"});if(Object.keys(ds).length>0&&!(0,L.isONNXProxy)()){const Ps={};for(const $s in ds)Ps[$s]="gpu-buffer";Wt.preferredOutputLocation=Ps}}return{buffer:await rs,session_options:Wt,session_config:Lt}}async function ee(_,x,W){return Object.fromEntries(await Promise.all(Object.keys(x).map(async be=>{const{buffer:Ie,session_options:ke,session_config:Ye}=await T(_,x[be],W),st=await(0,L.createInferenceSession)(Ie,ke,Ye);return[be,st]})))}async function Y(_,x,W){return Object.fromEntries(await Promise.all(Object.keys(x).map(async be=>{const Ie=await(0,w.getModelJSON)(_,x[be],!1,W);return[be,Ie]})))}function le(_,x){const W=Object.create(null),be=[];for(const Ye of _.inputNames){const st=x[Ye];if(!(st instanceof b.Tensor)){be.push(Ye);continue}W[Ye]=(0,L.isONNXProxy)()?st.clone():st}if(be.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${be.join(", ")}.`);const Ie=Object.keys(x).length,ke=_.inputNames.length;if(Ie>ke){let Ye=Object.keys(x).filter(st=>!_.inputNames.includes(st));console.warn(`WARNING: Too many inputs were provided (${Ie} > ${ke}). The following inputs will be ignored: "${Ye.join(", ")}".`)}return W}async function de(_,x){const W=le(_,x);try{const be=Object.fromEntries(Object.entries(W).map(([ke,Ye])=>[ke,Ye.ort_tensor]));let Ie=await _.run(be);return Ie=fe(Ie),Ie}catch(be){const Ie=Object.fromEntries(Object.entries(W).map(([ke,{type:Ye,dims:st,data:mt}])=>[ke,{type:Ye,dims:st,data:mt}]));throw console.error(`An error occurred during model execution: "${be}".`),console.error("Inputs given to model:",Ie),be}}function fe(_){for(let x in _)(0,L.isONNXTensor)(_[x])?_[x]=new b.Tensor(_[x]):typeof _[x]=="object"&&fe(_[x]);return _}function Ce(_){if(_ instanceof b.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(x=>x.length!==_[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new b.Tensor("int64",BigInt64Array.from(_.flat().map(x=>BigInt(x))),[_.length,_[0].length])}else return new b.Tensor("int64",BigInt64Array.from(_.map(x=>BigInt(x))),[1,_.length])}function Te(_){return new b.Tensor("bool",[_],[1])}async function Le(_,x){let{encoder_outputs:W,input_ids:be,decoder_input_ids:Ie,...ke}=x;if(!W){const st=(0,U.pick)(x,_.sessions.model.inputNames);W=(await qe(_,st)).last_hidden_state}return ke.input_ids=Ie,ke.encoder_hidden_states=W,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ke.encoder_attention_mask=x.attention_mask),await Ue(_,ke,!0)}async function qe(_,x){const W=_.sessions.model,be=(0,U.pick)(x,W.inputNames);if(W.inputNames.includes("inputs_embeds")&&!be.inputs_embeds){if(!x.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");be.inputs_embeds=await _.encode_text({input_ids:x.input_ids})}return W.inputNames.includes("token_type_ids")&&!be.token_type_ids&&(be.token_type_ids=new b.Tensor("int64",new BigInt64Array(be.input_ids.data.length),be.input_ids.dims)),await de(W,be)}async function Ue(_,x,W=!1){const be=_.sessions[W?"decoder_model_merged":"model"],{past_key_values:Ie,...ke}=x;if(be.inputNames.includes("use_cache_branch")&&(ke.use_cache_branch=Te(!!Ie)),be.inputNames.includes("position_ids")&&ke.attention_mask&&!ke.position_ids){const st=_.config.model_type==="paligemma"?1:0;ke.position_ids=he(ke,Ie,st)}_.addPastKeyValues(ke,Ie);const Ye=(0,U.pick)(ke,be.inputNames);return await de(be,Ye)}function ut({image_token_id:_,inputs_embeds:x,image_features:W,input_ids:be,attention_mask:Ie}){const ke=be.tolist().map(Tt=>Tt.reduce((Lt,Ut,Dt)=>(Ut==_&&Lt.push(Dt),Lt),[])),Ye=ke.reduce((Tt,Lt)=>Tt+Lt.length,0),st=W.dims[0];if(Ye!==st)throw new Error(`Image features and image tokens do not match: tokens: ${Ye}, features ${st}`);let mt=0;for(let Tt=0;Ttke.dims[1])){if(Iest==_.config.image_token_index)){const st=_.config.num_image_tokens;if(!st)throw new Error("`num_image_tokens` is missing in the model configuration.");const mt=ke.dims[1]-(Ie-st);W.input_ids=ke.slice(null,[-mt,null]),W.attention_mask=(0,b.ones)([1,Ie+mt])}}}return W}function Be(_,x,W,be){return W.past_key_values&&(x=x.map(Ie=>[Ie.at(-1)])),{...W,decoder_input_ids:Ce(x)}}function et(_,...x){return _.config.is_encoder_decoder?Be(_,...x):Ee(_,...x)}function Xe(_,x,W,be){const Ie=!!W.past_key_values;return be.guidance_scale!==null&&be.guidance_scale>1&&(Ie?W.input_ids=(0,b.cat)([W.input_ids,W.input_ids],0):(W.input_ids=(0,b.cat)([W.input_ids,(0,b.full_like)(W.input_ids,BigInt(be.pad_token_id))],0),W.attention_mask=(0,b.cat)([W.attention_mask,(0,b.full_like)(W.attention_mask,0n)],0))),(Ie||!W.pixel_values)&&(W.pixel_values=(0,b.full)([0,0,3,384,384],1)),Ie&&(W.images_seq_mask=new b.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),W.images_emb_mask=new b.Tensor("bool",new Array(0).fill(!1),[1,1,0])),W}class oe extends J.Callable{constructor(W,be,Ie){super();ge(this,"main_input_name","input_ids");ge(this,"forward_params",["input_ids","attention_mask"]);this.config=W,this.sessions=be,this.configs=Ie;const ke=C.get(this.constructor),Ye=$.get(ke);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ye){case F.DecoderOnly:this.can_generate=!0,this._forward=Ue,this._prepare_inputs_for_generation=Ee;break;case F.Seq2Seq:case F.Vision2Seq:case F.Musicgen:this.can_generate=!0,this._forward=Le,this._prepare_inputs_for_generation=Be;break;case F.EncoderDecoder:this._forward=Le;break;case F.ImageTextToText:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=et;break;case F.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=et;break;case F.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Xe;break;default:this._forward=qe;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var be;const W=[];for(const Ie of Object.values(this.sessions))(be=Ie==null?void 0:Ie.handler)!=null&&be.dispose&&W.push(Ie.handler.dispose());return await Promise.all(W)}static async from_pretrained(W,{progress_callback:be=null,config:Ie=null,cache_dir:ke=null,local_files_only:Ye=!1,revision:st="main",model_file_name:mt=null,subfolder:Tt="onnx",device:Lt=null,dtype:Ut=null,use_external_data_format:Dt=null,session_options:Wt={}}={}){let Zt={progress_callback:be,config:Ie,cache_dir:ke,local_files_only:Ye,revision:st,model_file_name:mt,subfolder:Tt,device:Lt,dtype:Ut,use_external_data_format:Dt,session_options:Wt};const rs=C.get(this),qt=$.get(rs);Ie=Zt.config=await f.AutoConfig.from_pretrained(W,Zt);let os;if(qt===F.DecoderOnly)os=await Promise.all([ee(W,{model:Zt.model_file_name??"model"},Zt),Y(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.Seq2Seq||qt===F.Vision2Seq)os=await Promise.all([ee(W,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt),Y(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.MaskGeneration)os=await Promise.all([ee(W,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Zt)]);else if(qt===F.EncoderDecoder)os=await Promise.all([ee(W,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt)]);else if(qt===F.ImageTextToText){const Ss={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ie.is_encoder_decoder&&(Ss.model="encoder_model"),os=await Promise.all([ee(W,Ss,Zt),Y(W,{generation_config:"generation_config.json"},Zt)])}else if(qt===F.Musicgen)os=await Promise.all([ee(W,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Zt),Y(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.MultiModality)os=await Promise.all([ee(W,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},Zt),Y(W,{generation_config:"generation_config.json"},Zt)]);else if(qt===F.Phi3V)os=await Promise.all([ee(W,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},Zt),Y(W,{generation_config:"generation_config.json"},Zt)]);else{if(qt!==F.EncoderOnly){const Ss=rs??(Ie==null?void 0:Ie.model_type);Ss!=="custom"&&console.warn(`Model type for '${Ss}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}os=await Promise.all([ee(W,{model:Zt.model_file_name??"model"},Zt)])}return new this(Ie,...os)}async _call(W){return await this.forward(W)}async forward(W){return await this._forward(this,W)}get generation_config(){var W;return((W=this.configs)==null?void 0:W.generation_config)??null}_get_logits_warper(W){const be=new y.LogitsProcessorList;return W.temperature!==null&&W.temperature!==1&&be.push(new y.TemperatureLogitsWarper(W.temperature)),W.top_k!==null&&W.top_k!==0&&be.push(new y.TopKLogitsWarper(W.top_k)),W.top_p!==null&&W.top_p<1&&be.push(new y.TopPLogitsWarper(W.top_p)),be}_get_logits_processor(W,be,Ie=null){const ke=new y.LogitsProcessorList;if(W.repetition_penalty!==null&&W.repetition_penalty!==1&&ke.push(new y.RepetitionPenaltyLogitsProcessor(W.repetition_penalty)),W.no_repeat_ngram_size!==null&&W.no_repeat_ngram_size>0&&ke.push(new y.NoRepeatNGramLogitsProcessor(W.no_repeat_ngram_size)),W.bad_words_ids!==null&&ke.push(new y.NoBadWordsLogitsProcessor(W.bad_words_ids,W.eos_token_id)),W.min_length!==null&&W.eos_token_id!==null&&W.min_length>0&&ke.push(new y.MinLengthLogitsProcessor(W.min_length,W.eos_token_id)),W.min_new_tokens!==null&&W.eos_token_id!==null&&W.min_new_tokens>0&&ke.push(new y.MinNewTokensLengthLogitsProcessor(be,W.min_new_tokens,W.eos_token_id)),W.forced_bos_token_id!==null&&ke.push(new y.ForcedBOSTokenLogitsProcessor(W.forced_bos_token_id)),W.forced_eos_token_id!==null&&ke.push(new y.ForcedEOSTokenLogitsProcessor(W.max_length,W.forced_eos_token_id)),W.begin_suppress_tokens!==null){const Ye=be>1||W.forced_bos_token_id===null?be:be+1;ke.push(new y.SuppressTokensAtBeginLogitsProcessor(W.begin_suppress_tokens,Ye))}return W.guidance_scale!==null&&W.guidance_scale>1&&ke.push(new y.ClassifierFreeGuidanceLogitsProcessor(W.guidance_scale)),Ie!==null&&ke.extend(Ie),ke}_prepare_generation_config(W,be,Ie=M.GenerationConfig){const ke={...this.config};for(const st of["decoder","generator","text_config"])st in ke&&Object.assign(ke,ke[st]);const Ye=new Ie(ke);return Object.assign(Ye,this.generation_config??{}),W&&Object.assign(Ye,W),be&&Object.assign(Ye,(0,U.pick)(be,Object.getOwnPropertyNames(Ye))),Ye}_get_stopping_criteria(W,be=null){const Ie=new re.StoppingCriteriaList;return W.max_length!==null&&Ie.push(new re.MaxLengthCriteria(W.max_length,this.config.max_position_embeddings??null)),W.eos_token_id!==null&&Ie.push(new re.EosTokenCriteria(W.eos_token_id)),be&&Ie.extend(be),Ie}_validate_model_class(){if(!this.can_generate){const W=[sa,Co,ta,ea],be=C.get(this.constructor),Ie=new Set,ke=this.config.model_type;for(const st of W){const mt=st.get(ke);mt&&Ie.add(mt[0])}let Ye=`The current model class (${be}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ie.size>0&&(Ye+=` Please use the following class instead: ${[...Ie].join(", ")}`),Error(Ye)}}prepare_inputs_for_generation(...W){return this._prepare_inputs_for_generation(this,...W)}_update_model_kwargs_for_generation({generated_input_ids:W,outputs:be,model_inputs:Ie,is_encoder_decoder:ke}){return Ie.past_key_values=this.getPastKeyValues(be,Ie.past_key_values),Ie.input_ids=new b.Tensor("int64",W.flat(),[W.length,1]),ke||(Ie.attention_mask=(0,b.cat)([Ie.attention_mask,(0,b.ones)([Ie.attention_mask.dims[0],1])],1)),Ie.position_ids=null,Ie}_prepare_model_inputs({inputs:W,bos_token_id:be,model_kwargs:Ie}){const ke=(0,U.pick)(Ie,this.forward_params),Ye=this.main_input_name;if(Ye in ke){if(W)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ke[Ye]=W;return{inputs_tensor:ke[Ye],model_inputs:ke,model_input_name:Ye}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:W,model_inputs:be,model_input_name:Ie,generation_config:ke}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!be.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:st,pixel_values:mt,attention_mask:Tt,...Lt}=be,Ut=await this._prepare_inputs_embeds(be);be={...Lt,...(0,U.pick)(Ut,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ye}=await qe(this,be);if(ke.guidance_scale!==null&&ke.guidance_scale>1)Ye=(0,b.cat)([Ye,(0,b.full_like)(Ye,0)],0),"attention_mask"in be&&(be.attention_mask=(0,b.cat)([be.attention_mask,(0,b.zeros_like)(be.attention_mask)],0));else if(be.decoder_input_ids){const st=Ce(be.decoder_input_ids).dims[0];if(st!==Ye.dims[0]){if(Ye.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ye.dims[0]}) than the decoder inputs (${st}).`);Ye=(0,b.cat)(Array.from({length:st},()=>Ye),0)}}return be.encoder_outputs=Ye,be}_prepare_decoder_input_ids_for_generation({batch_size:W,model_input_name:be,model_kwargs:Ie,decoder_start_token_id:ke,bos_token_id:Ye,generation_config:st}){let{decoder_input_ids:mt,...Tt}=Ie;if(!(mt instanceof b.Tensor)){if(mt)Array.isArray(mt[0])||(mt=Array.from({length:W},()=>mt));else if(ke??(ke=Ye),this.config.model_type==="musicgen")mt=Array.from({length:W*this.config.decoder.num_codebooks},()=>[ke]);else if(Array.isArray(ke)){if(ke.length!==W)throw new Error(`\`decoder_start_token_id\` expcted to have length ${W} but got ${ke.length}`);mt=ke}else mt=Array.from({length:W},()=>[ke]);mt=Ce(mt)}return Ie.decoder_attention_mask=(0,b.ones_like)(mt),{input_ids:mt,model_inputs:Tt}}async generate({inputs:W=null,generation_config:be=null,logits_processor:Ie=null,stopping_criteria:ke=null,streamer:Ye=null,...st}){this._validate_model_class(),be=this._prepare_generation_config(be,st);let{inputs_tensor:mt,model_inputs:Tt,model_input_name:Lt}=this._prepare_model_inputs({inputs:W,model_kwargs:st});const Ut=this.config.is_encoder_decoder;Ut&&("encoder_outputs"in Tt||(Tt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:mt,model_inputs:Tt,model_input_name:Lt,generation_config:be})));let Dt;Ut?{input_ids:Dt,model_inputs:Tt}=this._prepare_decoder_input_ids_for_generation({batch_size:Tt[Lt].dims.at(0),model_input_name:Lt,model_kwargs:Tt,decoder_start_token_id:be.decoder_start_token_id,bos_token_id:be.bos_token_id,generation_config:be}):Dt=Tt[Lt];let Wt=Dt.dims.at(-1);be.max_new_tokens!==null&&(be.max_length=Wt+be.max_new_tokens);const Zt=this._get_logits_processor(be,Wt,Ie),rs=this._get_stopping_criteria(be,ke),qt=Tt[Lt].dims.at(0),os=ie.LogitsSampler.getSampler(be),Ss=new Array(qt).fill(0),Ts=Dt.tolist();Ye&&Ye.put(Ts);let ds,Ps={};for(;;){if(Tt=this.prepare_inputs_for_generation(Ts,Tt,be),ds=await this.forward(Tt),be.output_attentions&&be.return_dict_in_generate){const nr=this.getAttentions(ds);for(const Cr in nr)Cr in Ps||(Ps[Cr]=[]),Ps[Cr].push(nr[Cr])}const Us=ds.logits.slice(null,-1,null),wr=Zt(Ts,Us),Wn=[];for(let nr=0;nrnr))break;Tt=this._update_model_kwargs_for_generation({generated_input_ids:Wn,outputs:ds,model_inputs:Tt,is_encoder_decoder:Ut})}Ye&&Ye.end();const $s=this.getPastKeyValues(ds,Tt.past_key_values,!0),Gs=new b.Tensor("int64",Ts.flat(),[Ts.length,Ts[0].length]);if(be.return_dict_in_generate)return{sequences:Gs,past_key_values:$s,...Ps};for(const Us of Object.values(ds))Us.location==="gpu-buffer"&&Us.dispose();return Gs}getPastKeyValues(W,be,Ie=!1){const ke=Object.create(null);for(const Ye in W)if(Ye.startsWith("present")){const st=Ye.replace("present","past_key_values"),mt=Ye.includes("encoder");if(mt&&be?ke[st]=be[st]:ke[st]=W[Ye],be&&(!mt||Ie)){const Tt=be[st];Tt.location==="gpu-buffer"&&Tt.dispose()}}return ke}getAttentions(W){const be={};for(const Ie of["cross_attentions","encoder_attentions","decoder_attentions"])for(const ke in W)ke.startsWith(Ie)&&(Ie in be||(be[Ie]=[]),be[Ie].push(W[ke]));return be}addPastKeyValues(W,be){var Ie,ke,Ye;if(be)Object.assign(W,be);else{const st=this.sessions.decoder_model_merged??this.sessions.model,mt=((Ie=st==null?void 0:st.config)==null?void 0:Ie.kv_cache_dtype)??"float32",Tt=mt==="float16"?new Uint16Array:[],Lt=((Ye=(ke=W[this.main_input_name]??W.attention_mask)==null?void 0:ke.dims)==null?void 0:Ye[0])??1,Ut=(0,f.getKeyValueShapes)(this.config,{batch_size:Lt});for(const Dt in Ut)W[Dt]=new b.Tensor(mt,Tt,Ut[Dt])}}async encode_image({pixel_values:W}){const be=(await de(this.sessions.vision_encoder,{pixel_values:W})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${be.dims[1]}).`),this.config.num_image_tokens=be.dims[1]),be}async encode_text({input_ids:W}){return(await de(this.sessions.embed_tokens,{input_ids:W})).inputs_embeds}}class Je{}class Fe extends Je{constructor({last_hidden_state:x,hidden_states:W=null,attentions:be=null}){super(),this.last_hidden_state=x,this.hidden_states=W,this.attentions=be}}class ce extends oe{}class ve extends ce{}class Re extends ce{async _call(x){return new Vs(await super._call(x))}}class je extends ce{async _call(x){return new Xt(await super._call(x))}}class Ve extends ce{async _call(x){return new js(await super._call(x))}}class Ne extends ce{async _call(x){return new Xs(await super._call(x))}}class Ze extends oe{}class at extends Ze{}class ft extends Ze{async _call(x){return new Vs(await super._call(x))}}class dt extends Ze{async _call(x){return new Xt(await super._call(x))}}class gt extends Ze{async _call(x){return new js(await super._call(x))}}class O extends oe{}class ne extends O{}class K extends oe{}class pe extends K{}class Oe extends K{async _call(x){return new Vs(await super._call(x))}}class Qe extends K{async _call(x){return new Xt(await super._call(x))}}class rt extends K{async _call(x){return new js(await super._call(x))}}class pt extends K{async _call(x){return new Xs(await super._call(x))}}class It extends oe{}class St extends It{}class Ft extends It{async _call(x){return new Vs(await super._call(x))}}class At extends It{async _call(x){return new Xt(await super._call(x))}}class ns extends It{async _call(x){return new js(await super._call(x))}}class gs extends It{async _call(x){return new Xs(await super._call(x))}}class ks extends oe{}class As extends ks{}class Qs extends ks{async _call(x){return new Vs(await super._call(x))}}class ir extends ks{async _call(x){return new Xt(await super._call(x))}}class Yr extends ks{async _call(x){return new js(await super._call(x))}}class Br extends ks{async _call(x){return new Xs(await super._call(x))}}class br extends oe{}class Nt extends br{}class Jr extends br{async _call(x){return new Vs(await super._call(x))}}class Sr extends br{async _call(x){return new Xt(await super._call(x))}}class Rr extends br{async _call(x){return new js(await super._call(x))}}class $r extends br{async _call(x){return new Xs(await super._call(x))}}class ar extends oe{}class Ar extends ar{}class pr extends ar{async _call(x){return new Vs(await super._call(x))}}class Ir extends ar{async _call(x){return new Xt(await super._call(x))}}class Zr extends ar{async _call(x){return new js(await super._call(x))}}class lr extends ar{async _call(x){return new Xs(await super._call(x))}}class nt extends oe{}class _t extends nt{}class Ot extends nt{async _call(x){return new Vs(await super._call(x))}}class ls extends nt{async _call(x){return new Xt(await super._call(x))}}class vr extends nt{async _call(x){return new js(await super._call(x))}}class ts extends nt{async _call(x){return new Xs(await super._call(x))}}class tr extends oe{}class Nr extends tr{}class en extends tr{async _call(x){return new Xt(await super._call(x))}}class jr extends tr{async _call(x){return new js(await super._call(x))}}class Tr extends tr{async _call(x){return new Xs(await super._call(x))}}class kn extends tr{async _call(x){return new Vs(await super._call(x))}}class Ur extends oe{}class Sn extends Ur{}class Jn extends Ur{async _call(x){return new Vs(await super._call(x))}}class Wr extends Ur{async _call(x){return new Xt(await super._call(x))}}class xr extends Ur{async _call(x){return new js(await super._call(x))}}class ur extends oe{}class fn extends ur{}class tn extends ur{async _call(x){return new Vs(await super._call(x))}}class gn extends ur{async _call(x){return new Xt(await super._call(x))}}class sn extends ur{async _call(x){return new Xs(await super._call(x))}}class Er extends oe{}class zt extends Er{}class wn extends Er{async _call(x){return new Vs(await super._call(x))}}class $n extends Er{async _call(x){return new Xt(await super._call(x))}}class An extends Er{async _call(x){return new js(await super._call(x))}}class In extends Er{async _call(x){return new Xs(await super._call(x))}}class Vr extends oe{}class On extends Vr{}class yn extends Vr{async _call(x){return new Vs(await super._call(x))}}class Fn extends Vr{async _call(x){return new Xt(await super._call(x))}}class is extends Vr{async _call(x){return new Xs(await super._call(x))}}class Ys extends oe{}class Mn extends Ys{}class Dn extends Ys{async _call(x){return new Xt(await super._call(x))}}class bn extends Ys{async _call(x){return new Xs(await super._call(x))}}class vn extends Ys{async _call(x){return new Vs(await super._call(x))}}class xe extends oe{constructor(){super(...arguments);ge(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class P extends xe{}class q extends xe{}class ae extends oe{}class Me extends ae{}class Pe extends ae{}class He extends oe{}class ct extends He{}class yt extends He{}class ht extends oe{}class it extends ht{}class Pt extends ht{}class hs extends ht{async _call(x){return new Xt(await super._call(x))}}class ss extends oe{}class Se extends ss{}class ws extends ss{}class Rs extends ss{async _call(x){return new Xt(await super._call(x))}}class Js extends ss{}class Zs extends oe{}class Bt extends Zs{}class Ns extends Zs{}class hr extends oe{}class es extends hr{}class _s extends hr{}class vt extends oe{}class ys extends vt{}class Pr extends vt{async _call(x){return new Vs(await super._call(x))}}class Fs extends vt{async _call(x){return new Xt(await super._call(x))}}class qs extends vt{async _call(x){return new js(await super._call(x))}}class Mt extends vt{async _call(x){return new Xs(await super._call(x))}}class bs extends oe{}class ze extends bs{}class wt extends bs{async _call(x){return new Vs(await super._call(x))}}class sr extends bs{async _call(x){return new Xt(await super._call(x))}}class rn extends bs{async _call(x){return new js(await super._call(x))}}class Zn extends bs{async _call(x){return new Xs(await super._call(x))}}class Tn extends oe{}class Qt extends Tn{}class ba extends Tn{async _call(x){return new Vs(await super._call(x))}}class No extends Tn{async _call(x){return new Xt(await super._call(x))}}class va extends Tn{async _call(x){return new js(await super._call(x))}}class Ta extends Tn{async _call(x){return new Xs(await super._call(x))}}class jo extends oe{}class xa extends jo{}class rr extends jo{}class Uo extends oe{constructor(){super(...arguments);ge(this,"requires_attention_mask",!1);ge(this,"main_input_name","input_features");ge(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ea extends Uo{}class Gr extends Uo{_prepare_generation_config(x,W){return super._prepare_generation_config(x,W,V.WhisperGenerationConfig)}_retrieve_init_tokens(x){const W=[x.decoder_start_token_id];let be=x.language;const Ie=x.task;if(x.is_multilingual){be||(console.warn("No language specified - defaulting to English (en)."),be="en");const Ye=`<|${(0,Q.whisper_language_to_code)(be)}|>`;W.push(x.lang_to_id[Ye]),W.push(x.task_to_id[Ie??"transcribe"])}else if(be||Ie)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!x.return_timestamps&&x.no_timestamps_token_id&&W.at(-1)!==x.no_timestamps_token_id?W.push(x.no_timestamps_token_id):x.return_timestamps&&W.at(-1)===x.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),W.pop()),W.filter(ke=>ke!=null)}async generate({inputs:x=null,generation_config:W=null,logits_processor:be=null,stopping_criteria:Ie=null,...ke}){W=this._prepare_generation_config(W,ke);const Ye=ke.decoder_input_ids??this._retrieve_init_tokens(W);if(W.return_timestamps&&(be??(be=new y.LogitsProcessorList),be.push(new y.WhisperTimeStampLogitsProcessor(W,Ye))),W.begin_suppress_tokens&&(be??(be=new y.LogitsProcessorList),be.push(new y.SuppressTokensAtBeginLogitsProcessor(W.begin_suppress_tokens,Ye.length))),W.return_token_timestamps){if(!W.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");W.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),W.output_attentions=!0,W.return_dict_in_generate=!0}const st=await super.generate({inputs:x,generation_config:W,logits_processor:be,decoder_input_ids:Ye,...ke});return W.return_token_timestamps&&(st.token_timestamps=this._extract_token_timestamps(st,W.alignment_heads,W.num_frames)),st}_extract_token_timestamps(x,W,be=null,Ie=.02){if(!x.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");be==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let ke=this.config.median_filter_width;ke===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ke=7);const Ye=x.cross_attentions,st=Array.from({length:this.config.decoder_layers},(rs,qt)=>(0,b.cat)(Ye.map(os=>os[qt]),2)),mt=(0,b.stack)(W.map(([rs,qt])=>{if(rs>=st.length)throw new Error(`Layer index ${rs} is out of bounds for cross attentions (length ${st.length}).`);return be?st[rs].slice(null,qt,null,[0,be]):st[rs].slice(null,qt)})).transpose(1,0,2,3),[Tt,Lt]=(0,b.std_mean)(mt,-2,0,!0),Ut=mt.clone();for(let rs=0;rsos[Gs+1]-os[Gs]),ds=(0,U.mergeArrays)([1],Ts).map($s=>!!$s),Ps=[];for(let $s=0;$sDt.findIndex(Wt=>Wt==ke)),mt=st.every(Dt=>Dt===-1),Tt=st.every(Dt=>Dt!==-1);if(!mt&&!Tt)throw new Error("Every input should contain either 0 or 1 image token.");if(mt)return{inputs_embeds:x,attention_mask:Ie};const Lt=[],Ut=[];for(let Dt=0;DtArray.from({length:x.dims[0]},Ts=>Array.from({length:x.dims[1]},ds=>1))),Zt=W?W.tolist():[],rs=be?be.tolist():[];let qt=0,os=0;for(let Ss=0;SsDt[Ss][Ds]==1),Ps=Ts.reduce((xs,Ds,Lr)=>(Ds==mt&&xs.push(Lr),xs),[]).map(xs=>Ts[xs+1]),$s=Ps.filter(xs=>xs==Ye).length,Gs=Ps.filter(xs=>xs==st).length;let Us=[],wr=0,Wn=$s,ua=Gs;for(let xs=0;xsKs>wr&&Xr==Ye),Lr=Ts.findIndex((Xr,Ks)=>Ks>wr&&Xr==st),qr=Wn>0&&Ds!==-1?Ds:Ts.length+1,dn=ua>0&&Lr!==-1?Lr:Ts.length+1;let $o,pa,yc,Ao;qr0?(0,H.max)(Us.at(-1))[0]+1:0;Us.push(Array.from({length:3*_a},(Xr,Ks)=>Io+Ks%_a));const fa=_a+Io,Oo=hp*ha*ma,zp=Array.from({length:Oo},(Xr,Ks)=>fa+Math.floor(Ks/(ha*ma))),mp=Array.from({length:Oo},(Xr,Ks)=>fa+Math.floor(Ks/ma)%ha),Mc=Array.from({length:Oo},(Xr,Ks)=>fa+Ks%ma);Us.push([zp,mp,Mc].flat()),wr=$o+Oo}if(wr0?(0,H.max)(Us.at(-1))[0]+1:0,Ds=Ts.length-wr;Us.push(Array.from({length:3*Ds},(Lr,qr)=>xs+qr%Ds))}const nr=Us.reduce((xs,Ds)=>xs+Ds.length,0),Cr=new Array(nr);let da=0;for(let xs=0;xs<3;++xs)for(let Ds=0;DsUt[qt%Ut.length]),Zt=Array.from({length:Dt[0]},(rs,qt)=>(0,H.max)(Ut.subarray(Dt[1]*qt,Dt[1]*(qt+1)))[0]+1+Dt[1]);return[new b.Tensor("int64",Wt,[3,...Dt]),new b.Tensor("int64",Zt,[Zt.length,1])]}else{const[Ut,Dt]=x.dims,Wt=BigInt64Array.from({length:3*Ut*Dt},(Zt,rs)=>BigInt(Math.floor(rs%Dt/Ut)));return[new b.Tensor("int64",Wt,[3,...x.dims]),(0,b.zeros)([Ut,1])]}}async encode_image({pixel_values:x,image_grid_thw:W}){return(await de(this.sessions.vision_encoder,{pixel_values:x,grid_thw:W})).image_features}_merge_input_ids_with_image_features(x){return ut({image_token_id:this.config.image_token_id,...x})}prepare_inputs_for_generation(x,W,be){if(W.attention_mask&&!W.position_ids)if(!W.past_key_values)[W.position_ids,W.rope_deltas]=this.get_rope_index(W.input_ids,W.image_grid_thw,W.video_grid_thw,W.attention_mask);else{W.pixel_values=null;const Ie=BigInt(Object.values(W.past_key_values)[0].dims.at(-2)),ke=W.rope_deltas.map(Ye=>Ie+Ye);W.position_ids=(0,b.stack)([ke,ke,ke],0)}return W}}class pi extends oe{}class bl extends pi{}class vl extends pi{}class hi extends oe{}class Tl extends hi{}class xl extends hi{}class mi extends oe{}class El extends mi{}class Pl extends mi{}class _i extends oe{}class Cl extends _i{}class kl extends _i{}class fi extends oe{}class Sl extends fi{}class $l extends fi{}class gi extends oe{}class wi extends gi{}class Al extends gi{async _call(x){return new Xt(await super._call(x))}}class io extends oe{}class yi extends io{}class Il extends io{async _call(x){return new Xt(await super._call(x))}}class Ol extends oe{}class Fl extends Ol{}class Mi extends oe{}class Dl extends Mi{}class Ll extends Mi{async _call(x){return new Xt(await super._call(x))}}class bi extends oe{}class zl extends bi{}class vi extends oe{}class Bl extends vi{}class Fc extends vi{async _call(x){return new Xt(await super._call(x))}}class Rl extends oe{}class Nl extends Rl{}class cr extends oe{}class jl extends cr{}class Ul extends cr{async _call(x){return new Xt(await super._call(x))}}class Wl extends oe{}class Vl extends Wl{async _call(x){return new pp(await super._call(x))}}class Ti extends oe{}class Gl extends Ti{}class Kl extends Ti{async _call(x){return new Xt(await super._call(x))}}class xi extends oe{}class Hl extends xi{}class ql extends xi{async _call(x){return new Xt(await super._call(x))}}class Xl extends oe{}class Ql extends Xl{}class Yl extends Xl{}class Ei extends oe{}class Jl extends Ei{}class Zl extends Ei{}class Pi extends oe{}class Dc extends Pi{}class on extends Pi{async _call(x){return new Xt(await super._call(x))}}class Or extends oe{}class an extends Or{}class Ci extends Or{async _call(x){return new Ws(await super._call(x))}}class Kr extends Or{async _call(x){return new eu(await super._call(x))}}class Ws extends Je{constructor({logits:x,pred_boxes:W}){super(),this.logits=x,this.pred_boxes=W}}class eu extends Je{constructor({logits:x,pred_boxes:W,pred_masks:be}){super(),this.logits=x,this.pred_boxes=W,this.pred_masks=be}}class ao extends oe{}class tu extends ao{}class Lc extends ao{async _call(x){return new zn(await super._call(x))}}class zn extends Je{constructor({logits:x,pred_boxes:W}){super(),this.logits=x,this.pred_boxes=W}}class lo extends oe{}class ki extends lo{}class su extends lo{async _call(x){return new ru(await super._call(x))}}class ru extends Ws{}class uo extends oe{}class Si extends uo{}class nu extends uo{async _call(x){return new Xt(await super._call(x))}}class co extends oe{}class ou extends co{}class po extends co{async _call(x){return new Xt(await super._call(x))}}class ho extends oe{}class iu extends ho{}class au extends ho{async _call(x){return new Xt(await super._call(x))}}class lu extends oe{}class uu extends lu{}class $i extends lu{async _call(x){return new Xt(await super._call(x))}}class En extends oe{}class du extends En{}class Ai extends En{}class Ii extends oe{}class cu extends Ii{}class pu extends Ii{}class zc extends oe{}class hu extends zc{}class mo extends oe{}class Bc extends mo{}class mu extends mo{}class _o extends mo{}class _u extends oe{}class fo extends _u{}class go extends oe{}class Oi extends go{}class fu extends go{}class Fi extends oe{}class Di extends Fi{}class Rc extends Fi{}class gu extends oe{}class Nc extends gu{}class Li extends oe{}class wu extends Li{}class yu extends Li{async _call(x){return new Xt(await super._call(x))}}class wo extends oe{}class Mu extends wo{}class bu extends wo{async _call(x){return new Xt(await super._call(x))}}class yo extends oe{}class vu extends yo{}class Tu extends yo{async _call(x){return new Xt(await super._call(x))}}class xu extends oe{}class Eu extends xu{}class Pu extends xu{async _call(x){return new Cu(await super._call(x))}}class Cu extends Je{constructor({logits:x,pred_boxes:W}){super(),this.logits=x,this.pred_boxes=W}}class jc extends oe{}class ku extends jc{async get_image_embeddings({pixel_values:x}){return await qe(this,{pixel_values:x})}async forward(x){if((!x.image_embeddings||!x.image_positional_embeddings)&&(x={...x,...await this.get_image_embeddings(x)}),!x.input_labels&&x.input_points){const be=x.input_points.dims.slice(0,-1),Ie=be.reduce((ke,Ye)=>ke*Ye,1);x.input_labels=new b.Tensor("int64",new BigInt64Array(Ie).fill(1n),be)}const W={image_embeddings:x.image_embeddings,image_positional_embeddings:x.image_positional_embeddings};return x.input_points&&(W.input_points=x.input_points),x.input_labels&&(W.input_labels=x.input_labels),x.input_boxes&&(W.input_boxes=x.input_boxes),await de(this.sessions.prompt_encoder_mask_decoder,W)}async _call(x){return new Su(await super._call(x))}}class Su extends Je{constructor({iou_scores:x,pred_masks:W}){super(),this.iou_scores=x,this.pred_masks=W}}class zi extends oe{}class $u extends zi{}class Au extends zi{}class Iu extends oe{}class Mo extends Iu{}class Bn extends Iu{}class Fr extends oe{}class Ou extends Fr{}class Fu extends Fr{async _call(x){return new un(await super._call(x))}}class Du extends Fr{async _call(x){return new Xt(await super._call(x))}}class Lu extends Fr{async _call(x){return new js(await super._call(x))}}class bo extends oe{}class zu extends bo{}class Bu extends bo{async _call(x){return new js(await super._call(x))}}class Ru extends oe{}class Uc extends Ru{}class vo extends oe{}class Bi extends vo{}class Nu extends vo{async _call(x){return new un(await super._call(x))}}class ju extends vo{async _call(x){return new Xt(await super._call(x))}}class Rn extends oe{}class Wc extends Rn{}class Uu extends Rn{async _call(x){return new un(await super._call(x))}}class Wu extends Rn{async _call(x){return new Xt(await super._call(x))}}class Vc extends Rn{async _call(x){return new js(await super._call(x))}}class To extends oe{}class Vu extends To{}class Gu extends To{async _call(x){return new un(await super._call(x))}}class Ku extends To{async _call(x){return new Xt(await super._call(x))}}class Fp extends oe{}class Hu extends Fr{}class qu extends Fr{async _call(x){return new un(await super._call(x))}}class Xu extends Fr{async _call(x){return new Xt(await super._call(x))}}class Nn extends oe{}class Qu extends Nn{}class Yu extends Nn{async _call(x){return new un(await super._call(x))}}class Ju extends Nn{async _call(x){return new Xt(await super._call(x))}}class Zu extends Nn{async _call(x){return new gc(await super._call(x))}}class Gc extends Nn{async _call(x){return new js(await super._call(x))}}class xo extends oe{}class Kc extends xo{}class ed extends xo{}class td extends xo{async generate_speech(x,W,{threshold:be=.5,minlenratio:Ie=0,maxlenratio:ke=20,vocoder:Ye=null}={}){const st={input_ids:x},{encoder_outputs:mt,encoder_attention_mask:Tt}=await qe(this,st),Lt=mt.dims[1]/this.config.reduction_factor,Ut=Math.floor(Lt*ke),Dt=Math.floor(Lt*Ie),Wt=this.config.num_mel_bins;let Zt=[],rs=null,qt=null,os=0;for(;;){++os;const ds=Te(!!qt);let Ps;qt?Ps=qt.output_sequence_out:Ps=new b.Tensor("float32",new Float32Array(Wt),[1,1,Wt]);let $s={use_cache_branch:ds,output_sequence:Ps,encoder_attention_mask:Tt,speaker_embeddings:W,encoder_hidden_states:mt};this.addPastKeyValues($s,rs),qt=await de(this.sessions.decoder_model_merged,$s),rs=this.getPastKeyValues(qt,rs);const{prob:Gs,spectrum:Us}=qt;if(Zt.push(Us),os>=Dt&&(Array.from(Gs.data).filter(wr=>wr>=be).length>0||os>=Ut))break}const Ss=(0,b.cat)(Zt),{waveform:Ts}=await de(Ye.sessions.model,{spectrogram:Ss});return{spectrogram:Ss,waveform:Ts}}}class Hc extends oe{constructor(){super(...arguments);ge(this,"main_input_name","spectrogram")}}class sd extends oe{}class rd extends sd{}class Ri extends oe{}class nd extends Ri{}class qc extends Ri{}class gr extends oe{}class Dr extends gr{}class ln extends gr{}class Hr extends oe{}class od extends Hr{}class id extends Hr{}class Eo extends oe{}class ad extends Eo{}class ld extends Eo{static async from_pretrained(x,W={}){return super.from_pretrained(x,{model_file_name:"text_model",...W})}}class ud extends Eo{static async from_pretrained(x,W={}){return super.from_pretrained(x,{model_file_name:"audio_model",...W})}}class dd extends oe{}class Ni extends dd{async _call(x){return new wc(await super._call(x))}}class Po extends oe{}class Xc extends Po{}class Qc extends Po{}class er extends Po{}class ji extends oe{}class cd extends ji{}class Ui extends ji{}class Wi extends oe{}class jn extends Wi{}class pd extends Wi{async _call(x){return new Xt(await super._call(x))}}class Vi extends oe{}class Yc extends Vi{}class Jc extends Vi{}class Gi extends oe{constructor(){super(...arguments);ge(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(W){const[be,Ie]=W.dims,ke=this.config.decoder.num_codebooks,Ye=Ie-ke;let st=0;for(let Lt=0;Lt0&&Wt<=Ye&&(W.data[st++]=W.data[Lt])}const mt=Math.floor(be/ke),Tt=st/(mt*ke);return new b.Tensor(W.type,W.data.slice(0,st),[mt,ke,Tt])}prepare_inputs_for_generation(W,be,Ie){let ke=structuredClone(W);for(let st=0;st=mt&&(ke[st][mt]=BigInt(this.config.decoder.pad_token_id));return Ie.guidance_scale!==null&&Ie.guidance_scale>1&&(ke=ke.concat(ke)),super.prepare_inputs_for_generation(ke,be,Ie)}async generate(W){const be=await super.generate(W),Ie=this._apply_and_filter_by_delay_pattern_mask(be).unsqueeze_(0),{audio_values:ke}=await de(this.sessions.encodec_decode,{audio_codes:Ie});return ke}}class Ki extends oe{}class Hi extends Ki{}class hd extends Ki{async _call(x){return new Xt(await super._call(x))}}class qi extends oe{}class md extends qi{}class _d extends qi{async _call(x){return new Xt(await super._call(x))}}class Xi extends oe{}class Qi extends Xi{}class fd extends Xi{async _call(x){return new Xt(await super._call(x))}}class gd extends oe{}class Yi extends gd{}class wd extends gd{async _call(x){return new Xt(await super._call(x))}}class yd extends oe{}class Md extends yd{}class Zc extends oe{}class bd extends Zc{constructor(...W){super(...W);ge(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(W){const be=this._generation_mode??"text";let Ie;if(be==="text"||!W.past_key_values){const Tt=this.sessions.prepare_inputs_embeds,Lt=(0,U.pick)(W,Tt.inputNames);Ie=await de(Tt,Lt)}else{const Tt=this.sessions.gen_img_embeds,Lt=(0,U.pick)({image_ids:W.input_ids},Tt.inputNames);Ie=await de(Tt,Lt)}const ke={...W,...Ie},Ye=await Ue(this,ke),st=this.sessions[be==="text"?"lm_head":"gen_head"];if(!st)throw new Error(`Unable to find "${st}" generation head`);const mt=await de(st,(0,U.pick)(Ye,st.inputNames));return{...Ie,...Ye,...mt}}async generate(W){return this._generation_mode="text",super.generate(W)}async generate_images(W){this._generation_mode="image";const be=(W.inputs??W[this.main_input_name]).dims[1],ke=(await super.generate(W)).slice(null,[be,null]),Ye=this.sessions.image_decode,{decoded_image:st}=await de(Ye,{generated_tokens:ke}),mt=st.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Tt=[];for(const Lt of mt){const Ut=D.RawImage.fromTensor(Lt);Tt.push(Ut)}return Tt}}class vd extends Je{constructor({char_logits:x,bpe_logits:W,wp_logits:be}){super(),this.char_logits=x,this.bpe_logits=W,this.wp_logits=be}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Td extends oe{}class ep extends Td{async _call(x){return new vd(await super._call(x))}}class Ji extends oe{}class xd extends Ji{}class tp extends Ji{}class Zi extends oe{}class Ed extends Zi{}class Pd extends Zi{}class fs{static async from_pretrained(x,{progress_callback:W=null,config:be=null,cache_dir:Ie=null,local_files_only:ke=!1,revision:Ye="main",model_file_name:st=null,subfolder:mt="onnx",device:Tt=null,dtype:Lt=null,use_external_data_format:Ut=null,session_options:Dt={}}={}){const Wt={progress_callback:W,config:be,cache_dir:Ie,local_files_only:ke,revision:Ye,model_file_name:st,subfolder:mt,device:Tt,dtype:Lt,use_external_data_format:Ut,session_options:Dt};if(Wt.config=await f.AutoConfig.from_pretrained(x,Wt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Zt of this.MODEL_CLASS_MAPPINGS){const rs=Zt.get(Wt.config.model_type);if(rs)return await rs[1].from_pretrained(x,Wt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Wt.config.model_type}", attempting to construct from base class.`),await oe.from_pretrained(x,Wt);throw Error(`Unsupported model type: ${Wt.config.model_type}`)}}ge(fs,"MODEL_CLASS_MAPPINGS",null),ge(fs,"BASE_IF_FAIL",!1);const sp=new Map([["bert",["BertModel",ve]],["modernbert",["ModernBertModel",at]],["nomic_bert",["NomicBertModel",ne]],["roformer",["RoFormerModel",pe]],["electra",["ElectraModel",As]],["esm",["EsmModel",Sn]],["convbert",["ConvBertModel",St]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",Ar]],["deberta-v2",["DebertaV2Model",_t]],["mpnet",["MPNetModel",zt]],["albert",["AlbertModel",Mn]],["distilbert",["DistilBertModel",Nr]],["roberta",["RobertaModel",ys]],["xlm",["XLMModel",ze]],["xlm-roberta",["XLMRobertaModel",Qt]],["clap",["ClapModel",ad]],["clip",["CLIPModel",Da]],["clipseg",["CLIPSegModel",Ua]],["chinese_clip",["ChineseCLIPModel",Ba]],["siglip",["SiglipModel",za]],["jina_clip",["JinaCLIPModel",Ra]],["mobilebert",["MobileBertModel",fn]],["squeezebert",["SqueezeBertModel",On]],["wav2vec2",["Wav2Vec2Model",Ou]],["wav2vec2-bert",["Wav2Vec2BertModel",Vu]],["unispeech",["UniSpeechModel",Bi]],["unispeech-sat",["UniSpeechSatModel",Wc]],["hubert",["HubertModel",Hu]],["wavlm",["WavLMModel",Qu]],["audio-spectrogram-transformer",["ASTModel",xa]],["vits",["VitsModel",Ni]],["pyannote",["PyAnnoteModel",zu]],["wespeaker-resnet",["WeSpeakerResNetModel",Uc]],["detr",["DetrModel",an]],["rt_detr",["RTDetrModel",tu]],["table-transformer",["TableTransformerModel",ki]],["vit",["ViTModel",wi]],["ijepa",["IJepaModel",yi]],["pvt",["PvtModel",Dl]],["vit_msn",["ViTMSNModel",Bl]],["vit_mae",["ViTMAEModel",zl]],["groupvit",["GroupViTModel",Nl]],["fastvit",["FastViTModel",jl]],["mobilevit",["MobileViTModel",Gl]],["mobilevitv2",["MobileViTV2Model",Hl]],["owlvit",["OwlViTModel",Ql]],["owlv2",["Owlv2Model",Jl]],["beit",["BeitModel",Dc]],["deit",["DeiTModel",Si]],["hiera",["HieraModel",ou]],["convnext",["ConvNextModel",wu]],["convnextv2",["ConvNextV2Model",Mu]],["dinov2",["Dinov2Model",vu]],["resnet",["ResNetModel",iu]],["swin",["SwinModel",uu]],["swin2sr",["Swin2SRModel",du]],["donut-swin",["DonutSwinModel",Nc]],["yolos",["YolosModel",Eu]],["dpt",["DPTModel",cu]],["glpn",["GLPNModel",Di]],["hifigan",["SpeechT5HifiGan",Hc]],["efficientnet",["EfficientNetModel",jn]],["decision_transformer",["DecisionTransformerModel",Md]],["patchtst",["PatchTSTForPrediction",xd]],["patchtsmixer",["PatchTSMixerForPrediction",Ed]],["mobilenet_v1",["MobileNetV1Model",Hi]],["mobilenet_v2",["MobileNetV2Model",md]],["mobilenet_v3",["MobileNetV3Model",Qi]],["mobilenet_v4",["MobileNetV4Model",Yi]],["maskformer",["MaskFormerModel",Oi]],["mgp-str",["MgpstrForSceneTextRecognition",ep]]]),Dp=new Map([["t5",["T5Model",P]],["longt5",["LongT5Model",Me]],["mt5",["MT5Model",ct]],["bart",["BartModel",it]],["mbart",["MBartModel",Se]],["marian",["MarianModel",$u]],["whisper",["WhisperModel",Ea]],["m2m_100",["M2M100Model",Mo]],["blenderbot",["BlenderbotModel",Bt]],["blenderbot-small",["BlenderbotSmallModel",es]]]),rp=new Map([["bloom",["BloomModel",El]],["jais",["JAISModel",Ga]],["gpt2",["GPT2Model",Va]],["gptj",["GPTJModel",ei]],["gpt_bigcode",["GPTBigCodeModel",Ya]],["gpt_neo",["GPTNeoModel",Ha]],["gpt_neox",["GPTNeoXModel",Xa]],["codegen",["CodeGenModel",Za]],["llama",["LlamaModel",el]],["exaone",["ExaoneModel",sl]],["olmo",["OlmoModel",il]],["olmo2",["Olmo2Model",al]],["mobilellm",["MobileLLMModel",nl]],["granite",["GraniteModel",dl]],["cohere",["CohereModel",cl]],["gemma",["GemmaModel",hl]],["gemma2",["Gemma2Model",_l]],["openelm",["OpenELMModel",gl]],["qwen2",["Qwen2Model",yl]],["phi",["PhiModel",bl]],["phi3",["Phi3Model",Tl]],["mpt",["MptModel",Cl]],["opt",["OPTModel",Sl]],["mistral",["MistralModel",nd]],["starcoder2",["Starcoder2Model",Dr]],["falcon",["FalconModel",od]],["stablelm",["StableLmModel",cd]]]),ea=new Map([["speecht5",["SpeechT5ForSpeechToText",ed]],["whisper",["WhisperForConditionalGeneration",Gr]],["moonshine",["MoonshineForConditionalGeneration",Pa]]]),Cd=new Map([["speecht5",["SpeechT5ForTextToSpeech",td]]]),kd=new Map([["vits",["VitsModel",Ni]],["musicgen",["MusicgenForConditionalGeneration",Gi]]]),Sd=new Map([["bert",["BertForSequenceClassification",je]],["modernbert",["ModernBertForSequenceClassification",dt]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",ir]],["esm",["EsmForSequenceClassification",Wr]],["convbert",["ConvBertForSequenceClassification",At]],["camembert",["CamembertForSequenceClassification",Sr]],["deberta",["DebertaForSequenceClassification",Ir]],["deberta-v2",["DebertaV2ForSequenceClassification",ls]],["mpnet",["MPNetForSequenceClassification",$n]],["albert",["AlbertForSequenceClassification",Dn]],["distilbert",["DistilBertForSequenceClassification",en]],["roberta",["RobertaForSequenceClassification",Fs]],["xlm",["XLMForSequenceClassification",sr]],["xlm-roberta",["XLMRobertaForSequenceClassification",No]],["bart",["BartForSequenceClassification",hs]],["mbart",["MBartForSequenceClassification",Rs]],["mobilebert",["MobileBertForSequenceClassification",gn]],["squeezebert",["SqueezeBertForSequenceClassification",Fn]]]),$d=new Map([["bert",["BertForTokenClassification",Ve]],["modernbert",["ModernBertForTokenClassification",gt]],["roformer",["RoFormerForTokenClassification",rt]],["electra",["ElectraForTokenClassification",Yr]],["esm",["EsmForTokenClassification",xr]],["convbert",["ConvBertForTokenClassification",ns]],["camembert",["CamembertForTokenClassification",Rr]],["deberta",["DebertaForTokenClassification",Zr]],["deberta-v2",["DebertaV2ForTokenClassification",vr]],["mpnet",["MPNetForTokenClassification",An]],["distilbert",["DistilBertForTokenClassification",jr]],["roberta",["RobertaForTokenClassification",qs]],["xlm",["XLMForTokenClassification",rn]],["xlm-roberta",["XLMRobertaForTokenClassification",va]]]),ta=new Map([["t5",["T5ForConditionalGeneration",q]],["longt5",["LongT5ForConditionalGeneration",Pe]],["mt5",["MT5ForConditionalGeneration",yt]],["bart",["BartForConditionalGeneration",Pt]],["mbart",["MBartForConditionalGeneration",ws]],["marian",["MarianMTModel",Au]],["m2m_100",["M2M100ForConditionalGeneration",Bn]],["blenderbot",["BlenderbotForConditionalGeneration",Ns]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",_s]]]),sa=new Map([["bloom",["BloomForCausalLM",Pl]],["gpt2",["GPT2LMHeadModel",fr]],["jais",["JAISLMHeadModel",Ka]],["gptj",["GPTJForCausalLM",ti]],["gpt_bigcode",["GPTBigCodeForCausalLM",ri]],["gpt_neo",["GPTNeoForCausalLM",qa]],["gpt_neox",["GPTNeoXForCausalLM",Qa]],["codegen",["CodeGenForCausalLM",ro]],["llama",["LlamaForCausalLM",tl]],["exaone",["ExaoneForCausalLM",rl]],["olmo",["OlmoForCausalLM",Oc]],["olmo2",["Olmo2ForCausalLM",ll]],["mobilellm",["MobileLLMForCausalLM",ol]],["granite",["GraniteForCausalLM",us]],["cohere",["CohereForCausalLM",pl]],["gemma",["GemmaForCausalLM",ml]],["gemma2",["Gemma2ForCausalLM",fl]],["openelm",["OpenELMForCausalLM",wl]],["qwen2",["Qwen2ForCausalLM",Ln]],["phi",["PhiForCausalLM",vl]],["phi3",["Phi3ForCausalLM",xl]],["mpt",["MptForCausalLM",kl]],["opt",["OPTForCausalLM",$l]],["mbart",["MBartForCausalLM",Js]],["mistral",["MistralForCausalLM",qc]],["starcoder2",["Starcoder2ForCausalLM",ln]],["falcon",["FalconForCausalLM",id]],["trocr",["TrOCRForCausalLM",rd]],["stablelm",["StableLmForCausalLM",Ui]],["phi3_v",["Phi3VForCausalLM",Ko]]]),np=new Map([["multi_modality",["MultiModalityCausalLM",bd]]]),op=new Map([["bert",["BertForMaskedLM",Re]],["modernbert",["ModernBertForMaskedLM",ft]],["roformer",["RoFormerForMaskedLM",Oe]],["electra",["ElectraForMaskedLM",Qs]],["esm",["EsmForMaskedLM",Jn]],["convbert",["ConvBertForMaskedLM",Ft]],["camembert",["CamembertForMaskedLM",Jr]],["deberta",["DebertaForMaskedLM",pr]],["deberta-v2",["DebertaV2ForMaskedLM",Ot]],["mpnet",["MPNetForMaskedLM",wn]],["albert",["AlbertForMaskedLM",vn]],["distilbert",["DistilBertForMaskedLM",kn]],["roberta",["RobertaForMaskedLM",Pr]],["xlm",["XLMWithLMHeadModel",wt]],["xlm-roberta",["XLMRobertaForMaskedLM",ba]],["mobilebert",["MobileBertForMaskedLM",tn]],["squeezebert",["SqueezeBertForMaskedLM",yn]]]),Un=new Map([["bert",["BertForQuestionAnswering",Ne]],["roformer",["RoFormerForQuestionAnswering",pt]],["electra",["ElectraForQuestionAnswering",Br]],["convbert",["ConvBertForQuestionAnswering",gs]],["camembert",["CamembertForQuestionAnswering",$r]],["deberta",["DebertaForQuestionAnswering",lr]],["deberta-v2",["DebertaV2ForQuestionAnswering",ts]],["mpnet",["MPNetForQuestionAnswering",In]],["albert",["AlbertForQuestionAnswering",bn]],["distilbert",["DistilBertForQuestionAnswering",Tr]],["roberta",["RobertaForQuestionAnswering",Mt]],["xlm",["XLMForQuestionAnswering",Zn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ta]],["mobilebert",["MobileBertForQuestionAnswering",sn]],["squeezebert",["SqueezeBertForQuestionAnswering",is]]]),Co=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Vo]],["idefics3",["Idefics3ForConditionalGeneration",Go]]]),Ad=new Map([["llava",["LlavaForConditionalGeneration",eo]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",ka]],["moondream1",["Moondream1ForConditionalGeneration",Sa]],["florence2",["Florence2ForConditionalGeneration",Aa]],["qwen2-vl",["Qwen2VLForConditionalGeneration",oo]],["idefics3",["Idefics3ForConditionalGeneration",Go]],["paligemma",["PaliGemmaForConditionalGeneration",Ia]]]),Id=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Vo]]]),ra=new Map([["vit",["ViTForImageClassification",Al]],["ijepa",["IJepaForImageClassification",Il]],["pvt",["PvtForImageClassification",Ll]],["vit_msn",["ViTMSNForImageClassification",Fc]],["fastvit",["FastViTForImageClassification",Ul]],["mobilevit",["MobileViTForImageClassification",Kl]],["mobilevitv2",["MobileViTV2ForImageClassification",ql]],["beit",["BeitForImageClassification",on]],["deit",["DeiTForImageClassification",nu]],["hiera",["HieraForImageClassification",po]],["convnext",["ConvNextForImageClassification",yu]],["convnextv2",["ConvNextV2ForImageClassification",bu]],["dinov2",["Dinov2ForImageClassification",Tu]],["resnet",["ResNetForImageClassification",au]],["swin",["SwinForImageClassification",$i]],["segformer",["SegformerForImageClassification",Qc]],["efficientnet",["EfficientNetForImageClassification",pd]],["mobilenet_v1",["MobileNetV1ForImageClassification",hd]],["mobilenet_v2",["MobileNetV2ForImageClassification",_d]],["mobilenet_v3",["MobileNetV3ForImageClassification",fd]],["mobilenet_v4",["MobileNetV4ForImageClassification",wd]]]),Od=new Map([["detr",["DetrForObjectDetection",Ci]],["rt_detr",["RTDetrForObjectDetection",Lc]],["table-transformer",["TableTransformerForObjectDetection",su]],["yolos",["YolosForObjectDetection",Pu]]]),Fd=new Map([["owlvit",["OwlViTForObjectDetection",Yl]],["owlv2",["Owlv2ForObjectDetection",Zl]]]),na=new Map([["detr",["DetrForSegmentation",Kr]],["clipseg",["CLIPSegForImageSegmentation",Wa]]]),oa=new Map([["segformer",["SegformerForSemanticSegmentation",er]],["sapiens",["SapiensForSemanticSegmentation",Bc]]]),Dd=new Map([["detr",["DetrForSegmentation",Kr]],["maskformer",["MaskFormerForInstanceSegmentation",fu]]]),Ld=new Map([["sam",["SamModel",ku]]]),ia=new Map([["wav2vec2",["Wav2Vec2ForCTC",Fu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Gu]],["unispeech",["UniSpeechForCTC",Nu]],["unispeech-sat",["UniSpeechSatForCTC",Uu]],["wavlm",["WavLMForCTC",Yu]],["hubert",["HubertForCTC",qu]]]),zd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Du]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Ku]],["unispeech",["UniSpeechForSequenceClassification",ju]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Wu]],["wavlm",["WavLMForSequenceClassification",Ju]],["hubert",["HubertForSequenceClassification",Xu]],["audio-spectrogram-transformer",["ASTForAudioClassification",rr]]]),Bd=new Map([["wavlm",["WavLMForXVector",Zu]]]),aa=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Vc]],["wavlm",["WavLMForAudioFrameClassification",Gc]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Lu]],["pyannote",["PyAnnoteForAudioFrameClassification",Bu]]]),Rd=new Map([["vitmatte",["VitMatteForImageMatting",Vl]]]),ip=new Map([["patchtst",["PatchTSTForPrediction",tp]],["patchtsmixer",["PatchTSMixerForPrediction",Pd]]]),Nd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ai]]]),jd=new Map([["dpt",["DPTForDepthEstimation",pu]],["depth_anything",["DepthAnythingForDepthEstimation",hu]],["glpn",["GLPNForDepthEstimation",Rc]],["sapiens",["SapiensForDepthEstimation",mu]],["depth_pro",["DepthProForDepthEstimation",fo]]]),ap=new Map([["sapiens",["SapiensForNormalEstimation",_o]]]),Ud=new Map([["vitpose",["VitPoseForPoseEstimation",Fl]]]),Wd=new Map([["clip",["CLIPVisionModelWithProjection",Ic]],["siglip",["SiglipVisionModel",Ho]],["jina_clip",["JinaCLIPVisionModel",ja]]]),Vd=[[sp,F.EncoderOnly],[Dp,F.EncoderDecoder],[rp,F.DecoderOnly],[Sd,F.EncoderOnly],[$d,F.EncoderOnly],[ta,F.Seq2Seq],[ea,F.Seq2Seq],[sa,F.DecoderOnly],[np,F.MultiModality],[op,F.EncoderOnly],[Un,F.EncoderOnly],[Co,F.Vision2Seq],[Ad,F.ImageTextToText],[ra,F.EncoderOnly],[na,F.EncoderOnly],[Dd,F.EncoderOnly],[oa,F.EncoderOnly],[Rd,F.EncoderOnly],[ip,F.EncoderOnly],[Nd,F.EncoderOnly],[jd,F.EncoderOnly],[ap,F.EncoderOnly],[Ud,F.EncoderOnly],[Od,F.EncoderOnly],[Fd,F.EncoderOnly],[Ld,F.MaskGeneration],[ia,F.EncoderOnly],[zd,F.EncoderOnly],[Cd,F.Seq2Seq],[kd,F.EncoderOnly],[Bd,F.EncoderOnly],[aa,F.EncoderOnly],[Wd,F.EncoderOnly]];for(const[_,x]of Vd)for(const[W,be]of _.values())$.set(W,x),C.set(be,W),g.set(W,be);const lp=[["MusicgenForConditionalGeneration",Gi,F.Musicgen],["Phi3VForCausalLM",Ko,F.Phi3V],["CLIPTextModelWithProjection",La,F.EncoderOnly],["SiglipTextModel",to,F.EncoderOnly],["JinaCLIPTextModel",Na,F.EncoderOnly],["ClapTextModelWithProjection",ld,F.EncoderOnly],["ClapAudioModelWithProjection",ud,F.EncoderOnly]];for(const[_,x,W]of lp)$.set(_,W),C.set(x,_),g.set(_,x);class Gd extends fs{}ge(Gd,"MODEL_CLASS_MAPPINGS",Vd.map(x=>x[0])),ge(Gd,"BASE_IF_FAIL",!0);class Kd extends fs{}ge(Kd,"MODEL_CLASS_MAPPINGS",[Sd]);class Hd extends fs{}ge(Hd,"MODEL_CLASS_MAPPINGS",[$d]);class qd extends fs{}ge(qd,"MODEL_CLASS_MAPPINGS",[ta]);class up extends fs{}ge(up,"MODEL_CLASS_MAPPINGS",[ea]);class Xd extends fs{}ge(Xd,"MODEL_CLASS_MAPPINGS",[Cd]);class Qd extends fs{}ge(Qd,"MODEL_CLASS_MAPPINGS",[kd]);class Yd extends fs{}ge(Yd,"MODEL_CLASS_MAPPINGS",[sa]);class Jd extends fs{}ge(Jd,"MODEL_CLASS_MAPPINGS",[op]);class dp extends fs{}ge(dp,"MODEL_CLASS_MAPPINGS",[Un]);class Zd extends fs{}ge(Zd,"MODEL_CLASS_MAPPINGS",[Co]);class ec extends fs{}ge(ec,"MODEL_CLASS_MAPPINGS",[ra]);class tc extends fs{}ge(tc,"MODEL_CLASS_MAPPINGS",[na]);class sc extends fs{}ge(sc,"MODEL_CLASS_MAPPINGS",[oa]);class rc extends fs{}ge(rc,"MODEL_CLASS_MAPPINGS",[Dd]);class nc extends fs{}ge(nc,"MODEL_CLASS_MAPPINGS",[Od]);class oc extends fs{}ge(oc,"MODEL_CLASS_MAPPINGS",[Fd]);class ic extends fs{}ge(ic,"MODEL_CLASS_MAPPINGS",[Ld]);class ac extends fs{}ge(ac,"MODEL_CLASS_MAPPINGS",[ia]);class lc extends fs{}ge(lc,"MODEL_CLASS_MAPPINGS",[zd]);class uc extends fs{}ge(uc,"MODEL_CLASS_MAPPINGS",[Bd]);class la extends fs{}ge(la,"MODEL_CLASS_MAPPINGS",[aa]);class dc extends fs{}ge(dc,"MODEL_CLASS_MAPPINGS",[Id]);class cc extends fs{}ge(cc,"MODEL_CLASS_MAPPINGS",[Rd]);class pc extends fs{}ge(pc,"MODEL_CLASS_MAPPINGS",[Nd]);class hc extends fs{}ge(hc,"MODEL_CLASS_MAPPINGS",[jd]);class mc extends fs{}ge(mc,"MODEL_CLASS_MAPPINGS",[ap]);class _c extends fs{}ge(_c,"MODEL_CLASS_MAPPINGS",[Ud]);class fc extends fs{}ge(fc,"MODEL_CLASS_MAPPINGS",[Wd]);class Lp extends Je{constructor({logits:x,past_key_values:W,encoder_outputs:be,decoder_attentions:Ie=null,cross_attentions:ke=null}){super(),this.logits=x,this.past_key_values=W,this.encoder_outputs=be,this.decoder_attentions=Ie,this.cross_attentions=ke}}class Xt extends Je{constructor({logits:x}){super(),this.logits=x}}class gc extends Je{constructor({logits:x,embeddings:W}){super(),this.logits=x,this.embeddings=W}}class js extends Je{constructor({logits:x}){super(),this.logits=x}}class Vs extends Je{constructor({logits:x}){super(),this.logits=x}}class Xs extends Je{constructor({start_logits:x,end_logits:W}){super(),this.start_logits=x,this.end_logits=W}}class un extends Je{constructor({logits:x}){super(),this.logits=x}}class cp extends Je{constructor({logits:x,past_key_values:W}){super(),this.logits=x,this.past_key_values=W}}class pp extends Je{constructor({alphas:x}){super(),this.alphas=x}}class wc extends Je{constructor({waveform:x,spectrogram:W}){super(),this.waveform=x,this.spectrogram=W}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(De,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(U){super(U);const w=this.config.sampling_rate,v=(0,L.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(w/2),w,null,"kaldi",!0);for(let y=0;y{r.r(A),r.d(A,{AutoFeatureExtractor:()=>J});var f=r("./src/utils/constants.js"),L=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var N=r("./src/models/feature_extractors.js");class J{static async from_pretrained(w,v={}){const y=await(0,L.getModelJSON)(w,f.FEATURE_EXTRACTOR_NAME,!0,v),M=y.feature_extractor_type,b=N[M];if(!b)throw new Error(`Unknown feature_extractor_type: '${M}'. Please report this at ${f.GITHUB_ISSUE_URL}.`);return new b(y)}}},"./src/models/auto/image_processing_auto.js":(De,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>U});var f=r("./src/utils/constants.js"),L=r("./src/utils/hub.js"),N=r("./src/base/image_processors_utils.js"),J=r("./src/models/image_processors.js");class U{static async from_pretrained(v,y={}){const M=await(0,L.getModelJSON)(v,f.IMAGE_PROCESSOR_NAME,!0,y),b=M.image_processor_type??M.feature_extractor_type;let D=J[b];return D||(b!==void 0&&console.warn(`Image processor type '${b}' not found, assuming base ImageProcessor. Please report this at ${f.GITHUB_ISSUE_URL}.`),D=N.ImageProcessor),new D(M)}}},"./src/models/auto/processing_auto.js":(De,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>v});var f=r("./src/utils/constants.js"),L=r("./src/utils/hub.js"),N=r("./src/base/processing_utils.js"),J=r("./src/models/processors.js"),U=r("./src/models/image_processors.js"),w=r("./src/models/feature_extractors.js");class v{static async from_pretrained(M,b={}){const D=await(0,L.getModelJSON)(M,f.IMAGE_PROCESSOR_NAME,!0,b),{image_processor_type:H,feature_extractor_type:re,processor_class:ie}=D;if(ie&&J[ie])return J[ie].from_pretrained(M,b);if(!H&&!re)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const z={};if(H){const Q=U[H];if(!Q)throw new Error(`Unknown image_processor_type: '${H}'.`);z.image_processor=new Q(D)}if(re){const Q=U[re];if(Q)z.image_processor=new Q(D);else{const F=w[re];if(!F)throw new Error(`Unknown feature_extractor_type: '${re}'.`);z.feature_extractor=new F(D)}}const V={};return new N.Processor(V,z)}}},"./src/models/beit/image_processing_beit.js":(De,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(De,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(De,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(De,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(U){super(U),this.mel_filters=(0,L.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,L.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,L.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(U,w,v,y){let M;const b=U.length-w;if(b>0)if(v==="rand_trunc"){const D=Math.floor(Math.random()*(b+1));U=U.subarray(D,D+w),M=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(b<0){let D=new Float64Array(w);if(D.set(U),y==="repeat")for(let H=U.length;H{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/convnext/image_processing_convnext.js":(De,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>N,ConvNextImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){var v;const w=(v=this.size)==null?void 0:v.shortest_edge;if(w===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(w<384){const y=Math.floor(w/this.crop_pct),[M,b]=this.get_resize_output_image_size(U,{shortest_edge:y});U=await U.resize(M,b,{resample:this.resample}),U=await U.center_crop(w,w)}else U=await U.resize(w,w,{resample:this.resample});return U}}class N extends L{}},"./src/models/deit/image_processing_deit.js":(De,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>N,DeiTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/detr/image_processing_detr.js":(De,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>J,DetrImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(w){const v=await super._call(w),y=[v.pixel_values.dims[0],64,64],M=(0,L.full)(y,1n);return{...v,pixel_mask:M}}post_process_object_detection(...w){return(0,f.post_process_object_detection)(...w)}post_process_panoptic_segmentation(...w){return(0,f.post_process_panoptic_segmentation)(...w)}post_process_instance_segmentation(...w){return(0,f.post_process_instance_segmentation)(...w)}}class J extends N{}},"./src/models/donut/image_processing_donut.js":(De,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>N,DonutImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{pad_image(U,w,v,y={}){const[M,b,D]=w;let H=this.image_mean;Array.isArray(this.image_mean)||(H=new Array(D).fill(H));let re=this.image_std;Array.isArray(re)||(re=new Array(D).fill(H));const ie=H.map((z,V)=>-z/re[V]);return super.pad_image(U,w,v,{center:!0,constant_values:ie,...y})}}class N extends L{}},"./src/models/dpt/image_processing_dpt.js":(De,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>N,DPTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/efficientnet/image_processing_efficientnet.js":(De,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(J){super(J),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(U=>U*U))}}},"./src/models/feature_extractors.js":(De,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>f.ASTFeatureExtractor,ClapFeatureExtractor:()=>L.ClapFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>N.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>J.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>U.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>w.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var f=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),L=r("./src/models/clap/feature_extraction_clap.js"),N=r("./src/models/moonshine/feature_extraction_moonshine.js"),J=r("./src/models/pyannote/feature_extraction_pyannote.js"),U=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),w=r("./src/models/speecht5/feature_extraction_speecht5.js"),v=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),M=r("./src/models/whisper/feature_extraction_whisper.js"),b=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(De,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class J extends f.Processor{constructor(w,v){super(w,v);const{tasks_answer_post_processing_type:y,task_prompts_without_inputs:M,task_prompts_with_input:b}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(y??{})),this.task_prompts_without_inputs=new Map(Object.entries(M??{})),this.task_prompts_with_input=new Map(Object.entries(b??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(w){typeof w=="string"&&(w=[w]);const v=[];for(const y of w)if(this.task_prompts_without_inputs.has(y))v.push(this.task_prompts_without_inputs.get(y));else{for(const[M,b]of this.task_prompts_with_input)if(y.includes(M)){v.push(b.replaceAll("{input}",y).replaceAll(M,""));break}v.length!==w.length&&v.push(y)}return v}post_process_generation(w,v,y){const M=this.tasks_answer_post_processing_type.get(v)??"pure_text";w=w.replaceAll("","").replaceAll("","");let b;switch(M){case"pure_text":b=w;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const D=M==="ocr"?"quad_boxes":"bboxes",H=w.matchAll(this.regexes[D]),re=[],ie=[];for(const[z,V,...Q]of H)re.push(V?V.trim():re.at(-1)??""),ie.push(Q.map((F,$)=>(Number(F)+.5)/this.size_per_bin*y[$%2]));b={labels:re,[D]:ie};break;default:throw new Error(`Task "${v}" (of type "${M}") not yet implemented.`)}return{[v]:b}}async _call(w,v=null,y={}){if(!w&&!v)throw new Error("Either text or images must be provided");const M=await this.image_processor(w,y),b=v?this.tokenizer(v,y):{};return{...M,...b}}}ge(J,"tokenizer_class",N.AutoTokenizer),ge(J,"image_processor_class",L.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(De,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(De,A,r)=>{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class N extends f.ImageProcessor{constructor(U){super(U),this.do_image_splitting=U.do_image_splitting??!0,this.max_image_size=U.max_image_size}get_resize_for_vision_encoder(U,w){let[v,y]=U.dims.slice(-2);const M=y/v;return y>=v?(y=Math.ceil(y/w)*w,v=Math.floor(y/M),v=Math.ceil(v/w)*w):(v=Math.ceil(v/w)*w,y=Math.floor(v*M),y=Math.ceil(y/w)*w),{height:v,width:y}}async _call(U,{do_image_splitting:w=null,return_row_col_info:v=!1}={}){let y;if(!Array.isArray(U))y=[[U]];else{if(U.length===0||!U[0])throw new Error("No images provided.");Array.isArray(U[0])?y=U:y=[U]}let M=[],b=[],D=[];const H=[],re=[];for(const C of y){let T=await Promise.all(C.map(le=>this.preprocess(le)));H.push(...T.map(le=>le.original_size)),re.push(...T.map(le=>le.reshaped_input_size)),T.forEach(le=>le.pixel_values.unsqueeze_(0));const{longest_edge:ee}=this.max_image_size;let Y;if(w??this.do_image_splitting){let le=new Array(T.length),de=new Array(T.length);Y=await Promise.all(T.map(async(fe,Ce)=>{const Te=this.get_resize_for_vision_encoder(fe.pixel_values,ee),Le=await(0,L.interpolate_4d)(fe.pixel_values,{size:[Te.height,Te.width]}),{frames:qe,num_splits_h:Ue,num_splits_w:ut}=await this.split_image(Le,this.max_image_size);return le[Ce]=Ue,de[Ce]=ut,(0,L.cat)(qe,0)})),b.push(le),D.push(de)}else{const le=[ee,ee];Y=await Promise.all(T.map(de=>(0,L.interpolate_4d)(de.pixel_values,{size:le}))),b.push(new Array(T.length).fill(0)),D.push(new Array(T.length).fill(0))}M.push((0,L.cat)(Y,0))}const ie=M.length,[z,V,Q,F]=M[0].dims;let $,g;if(ie===1)$=M[0].unsqueeze_(0),g=(0,L.full)([ie,z,Q,F],!0);else{const C=Math.max(...M.map(Y=>Y.dims.at(0)));g=(0,L.full)([ie,C,Q,F],!0);const T=g.data,ee=C*Q*F;for(let Y=0;Yv||D>y){H=Math.ceil(b/v),re=Math.ceil(D/y);const ie=Math.ceil(b/H),z=Math.ceil(D/re);for(let F=0;F{r.r(A),r.d(A,{Idefics3Processor:()=>y});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");var J=r("./src/utils/core.js");function U(M,b,D,H,re,ie){let z="";for(let V=0;V`+re.repeat(M);z+=` `}return z+=` ${H}${ie}`+re.repeat(M)+`${H}`,z}function w(M,b,D,H){return`${b}${H}`+D.repeat(M)+`${b}`}function v(M,b,D,H,re,ie){return M===0&&b===0?w(D,H,re,ie):U(D,M,b,H,re,ie)}class y extends f.Processor{constructor(){super(...arguments);ge(this,"fake_image_token","");ge(this,"image_token","");ge(this,"global_img_token","")}async _call(D,H=null,re={}){re.return_row_col_info??(re.return_row_col_info=!0);let ie;H&&(ie=await this.image_processor(H,re)),Array.isArray(D)||(D=[D]);const z=ie.rows??[new Array(D.length).fill(0)],V=ie.cols??[new Array(D.length).fill(0)],Q=this.config.image_seq_len,F=[],$=[];for(let C=0;Cv(Ce,Y[Te],Q,this.fake_image_token,this.image_token,this.global_img_token)),de=T.split(this.image_token);if(de.length===0)throw new Error("The image token should be present in the text.");let fe=de[0];for(let Ce=0;Ce{r.r(A),r.d(A,{BeitFeatureExtractor:()=>f.BeitFeatureExtractor,BitImageProcessor:()=>L.BitImageProcessor,CLIPFeatureExtractor:()=>J.CLIPFeatureExtractor,CLIPImageProcessor:()=>J.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>N.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>U.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>U.ConvNextImageProcessor,DPTFeatureExtractor:()=>M.DPTFeatureExtractor,DPTImageProcessor:()=>M.DPTImageProcessor,DeiTFeatureExtractor:()=>w.DeiTFeatureExtractor,DeiTImageProcessor:()=>w.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>y.DonutFeatureExtractor,DonutImageProcessor:()=>y.DonutImageProcessor,EfficientNetImageProcessor:()=>b.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>D.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>H.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>ie.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>V.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Q.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>Q.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>F.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>F.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>$.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>$.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>g.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>g.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>T.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>T.MobileViTImageProcessor,NougatImageProcessor:()=>ee.NougatImageProcessor,OwlViTFeatureExtractor:()=>le.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>le.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Y.Owlv2ImageProcessor,Phi3VImageProcessor:()=>de.Phi3VImageProcessor,PvtImageProcessor:()=>fe.PvtImageProcessor,Qwen2VLImageProcessor:()=>Ce.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Te.RTDetrImageProcessor,SamImageProcessor:()=>Le.SamImageProcessor,SegformerFeatureExtractor:()=>qe.SegformerFeatureExtractor,SegformerImageProcessor:()=>qe.SegformerImageProcessor,SiglipImageProcessor:()=>Ue.SiglipImageProcessor,Swin2SRImageProcessor:()=>ut.Swin2SRImageProcessor,VLMImageProcessor:()=>re.VLMImageProcessor,ViTFeatureExtractor:()=>ue.ViTFeatureExtractor,ViTImageProcessor:()=>ue.ViTImageProcessor,VitMatteImageProcessor:()=>se.VitMatteImageProcessor,VitPoseImageProcessor:()=>he.VitPoseImageProcessor,YolosFeatureExtractor:()=>Ee.YolosFeatureExtractor,YolosImageProcessor:()=>Ee.YolosImageProcessor});var f=r("./src/models/beit/image_processing_beit.js"),L=r("./src/models/bit/image_processing_bit.js"),N=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),J=r("./src/models/clip/image_processing_clip.js"),U=r("./src/models/convnext/image_processing_convnext.js"),w=r("./src/models/deit/image_processing_deit.js"),v=r("./src/models/detr/image_processing_detr.js"),y=r("./src/models/donut/image_processing_donut.js"),M=r("./src/models/dpt/image_processing_dpt.js"),b=r("./src/models/efficientnet/image_processing_efficientnet.js"),D=r("./src/models/glpn/image_processing_glpn.js"),H=r("./src/models/idefics3/image_processing_idefics3.js"),re=r("./src/models/janus/image_processing_janus.js"),ie=r("./src/models/jina_clip/image_processing_jina_clip.js"),z=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),V=r("./src/models/mask2former/image_processing_mask2former.js"),Q=r("./src/models/maskformer/image_processing_maskformer.js"),F=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),$=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),g=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),T=r("./src/models/mobilevit/image_processing_mobilevit.js"),ee=r("./src/models/nougat/image_processing_nougat.js"),Y=r("./src/models/owlv2/image_processing_owlv2.js"),le=r("./src/models/owlvit/image_processing_owlvit.js"),de=r("./src/models/phi3_v/image_processing_phi3_v.js"),fe=r("./src/models/pvt/image_processing_pvt.js"),Ce=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Te=r("./src/models/rt_detr/image_processing_rt_detr.js"),Le=r("./src/models/sam/image_processing_sam.js"),qe=r("./src/models/segformer/image_processing_segformer.js"),Ue=r("./src/models/siglip/image_processing_siglip.js"),ut=r("./src/models/swin2sr/image_processing_swin2sr.js"),ue=r("./src/models/vit/image_processing_vit.js"),se=r("./src/models/vitmatte/image_processing_vitmatte.js"),he=r("./src/models/vitpose/image_processing_vitpose.js"),Ee=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(De,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(J){super({do_pad:!0,pad_size:{width:J.image_size,height:J.image_size},...J}),this.constant_values=this.config.background_color.map(U=>U*this.rescale_factor)}pad_image(J,U,w,v){return super.pad_image(J,U,w,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(De,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>v});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),J=r("./src/utils/core.js"),U=r("./src/utils/tensor.js"),w=r("./src/utils/image.js");class v extends f.Processor{constructor(M,b){super(M,b),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(M,{images:b=null,chat_template:D="default"}={}){b?Array.isArray(b)||(b=[b]):b=await Promise.all(M.filter(Y=>Y.images).flatMap(Y=>Y.images).map(Y=>w.RawImage.read(Y)));const H=this.tokenizer,re=H.apply_chat_template(M,{tokenize:!1,add_generation_prompt:!0,chat_template:D}),ie=Y=>H.encode(Y,{add_special_tokens:!1}),z=re.split(this.image_tag),V=z.length-1;if(b.length!==V)throw new Error(`Number of images provided (${b.length}) does not match number of "${this.image_tag}" image tags (${V})`);const[Q,F,$]=H.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let g=ie(z[0]),C=new Array(g.length).fill(!1);for(let Y=1;Y0){const Y=await this.image_processor(b);return Y.pixel_values.unsqueeze_(0),{...ee,...Y}}return ee}}ge(v,"image_processor_class",L.AutoImageProcessor),ge(v,"tokenizer_class",N.AutoTokenizer),ge(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(De,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{constructor(J){const{resize_mode:U,fill_color:w,interpolation:v,size:y,...M}=J,b=U==="squash"?{width:y,height:y}:U==="shortest"?{shortest_edge:y}:{longest_edge:y},D=v==="bicubic"?3:2;super({...M,size:b,resample:D,do_center_crop:!0,crop_size:y,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(De,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class J extends f.Processor{async _call(w=null,v=null,y={}){if(!w&&!v)throw new Error("Either text or images must be provided");const M=w?this.tokenizer(w,y):{},b=v?await this.image_processor(v,y):{};return{...M,...b}}}ge(J,"tokenizer_class",N.AutoTokenizer),ge(J,"image_processor_class",L.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(De,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(De,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>L});var f=r("./src/models/maskformer/image_processing_maskformer.js");class L extends f.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(De,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>N,MaskFormerImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_panoptic_segmentation(...U){return(0,f.post_process_panoptic_segmentation)(...U)}post_process_instance_segmentation(...U){return(0,f.post_process_instance_segmentation)(...U)}}class N extends L{}},"./src/models/mgp_str/processing_mgp_str.js":(De,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>w});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),J=r("./src/utils/maths.js");const U={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class w extends f.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(y,M){if(!U.hasOwnProperty(M))throw new Error(`Format ${M} is not supported.`);const[b,D]=U[M],H=this[b].bind(this),[re,ie]=y.dims,z=[],V=[],Q=y.tolist();for(let $=0;$0?T.reduce((Y,le)=>Y*le,1):0;V.push(C),z.push(ee)}return[H(V),z]}char_decode(y){return this.char_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}bpe_decode(y){return this.bpe_tokenizer.batch_decode(y)}wp_decode(y){return this.wp_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}batch_decode([y,M,b]){const[D,H]=this._decode_helper(y,"char"),[re,ie]=this._decode_helper(M,"bpe"),[z,V]=this._decode_helper(b,"wp"),Q=[],F=[];for(let $=0;${r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>N,MobileNetV1ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>N,MobileNetV2ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>N,MobileNetV3ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>N,MobileNetV4ImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/mobilevit/image_processing_mobilevit.js":(De,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>N,MobileViTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/moonshine/feature_extraction_moonshine.js":(De,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js");class N extends f.FeatureExtractor{async _call(U){(0,f.validate_audio_inputs)(U,"MoonshineFeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));const w=[1,U.length];return{input_values:new L.Tensor("float32",U,w)}}}},"./src/models/moonshine/processing_moonshine.js":(De,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>J});var f=r("./src/models/auto/feature_extraction_auto.js"),L=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class J extends N.Processor{async _call(w){return await this.feature_extractor(w)}}ge(J,"tokenizer_class",L.AutoTokenizer),ge(J,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(De,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>L});var f=r("./src/models/donut/image_processing_donut.js");class L extends f.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(De,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>L});var f=r("./src/models/owlvit/image_processing_owlvit.js");class L extends f.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(De,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>N,OwlViTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_object_detection(...U){return(0,f.post_process_object_detection)(...U)}}class N extends L{}},"./src/models/owlvit/processing_owlvit.js":(De,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class J extends f.Processor{}ge(J,"tokenizer_class",N.AutoTokenizer),ge(J,"image_processor_class",L.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(De,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>w});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");const J="";function U(v,y,M,b,D){return`${b.repeat(M*D)}${y}${v} `}class w extends f.Processor{async _call(y,M=null,b={}){M||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),M=""),Array.isArray(y)||(y=[y]),Array.isArray(M)||(M=[M]);const D=this.tokenizer.bos_token,H=this.image_processor.config.image_seq_length;let re;M.some(V=>V.includes(J))?re=M.map(V=>{const Q=V.replaceAll(J,J.repeat(H)),F=Q.lastIndexOf(J),$=F===-1?0:F+J.length;return Q.slice(0,$)+D+Q.slice($)+` `}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),re=M.map(V=>U(V,D,H,J,y.length)));const ie=this.tokenizer(re,b);return{...await this.image_processor(y,b),...ie}}}ge(w,"tokenizer_class",N.AutoTokenizer),ge(w,"image_processor_class",L.AutoImageProcessor),ge(w,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(De,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>y});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");const N=336,J=[2,3],{ceil:U,floor:w,sqrt:v}=Math;class y extends f.ImageProcessor{constructor(b){super({...b,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=b.num_crops}calc_num_image_tokens_from_image_size(b,D){const{num_img_tokens:H}=this.config;return w((w(D/N)*w(b/N)+1)*H+1+(w(D/N)+1)*v(H))}get_resize_output_image_size(b,D){const H=this._num_crops,[re,ie]=b.size;let z=re/ie,V=1;for(;V*Math.ceil(V/z)<=H;)V+=1;V-=1;const Q=Math.floor(V*336),F=Math.floor(Q/z);return[Q,F]}pad_image(b,D,H,re={}){const[ie,z]=D,V=N*U(ie/N),Q=N*U(z/N),F=[1,1,1].map(($,g)=>($-this.image_mean[g])/this.image_std[g]);return super.pad_image(b,D,{width:Q,height:V},{center:!0,constant_values:F,...re})}async _call(b,{num_crops:D=null}={}){if(this._num_crops=D??(D=this.config.num_crops),D<4||v(D)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(b)||(b=[b]);const H=b.length,re=await Promise.all(b.map(C=>this.preprocess(C))),ie=re.map(C=>C.original_size),z=re.map(C=>C.reshaped_input_size),V=[];for(const{pixel_values:C}of re){C.unsqueeze_(0);const[T,ee]=C.dims.slice(-2),Y=await(0,L.interpolate_4d)(C,{size:[N,N],mode:"bicubic"});if(D>0){const le=[],de=v(D),fe=w(ee/de),Ce=w(T/de);for(let Le=0;LeC.map(T=>N*U(T/N))),$=new L.Tensor("int64",F.flat(),[H,2]),g=F.map(([C,T])=>this.calc_num_image_tokens_from_image_size(T,C));return{pixel_values:Q,original_sizes:ie,reshaped_input_sizes:z,image_sizes:$,num_img_tokens:g}}}},"./src/models/phi3_v/processing_phi3_v.js":(De,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>w});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");const J="<|image|>",U=/<\|image_\d+\|>/g;class w extends f.Processor{async _call(y,M=null,{padding:b=!0,truncation:D=!0,num_crops:H=null}={}){Array.isArray(y)||(y=[y]);let re,ie;if(M){ie=await this.image_processor(M,{num_crops:H});const{num_img_tokens:z}=ie,V=y.map((F,$)=>F.split(U).join(J.repeat(z[$])));re=this.tokenizer(V,{padding:b,truncation:D});const Q=this.tokenizer.model.convert_tokens_to_ids([J])[0];re.input_ids.map_(F=>F==Q?-F:F)}else re=this.tokenizer(y);return{...re,...ie}}}ge(w,"image_processor_class",L.AutoImageProcessor),ge(w,"tokenizer_class",N.AutoTokenizer)},"./src/models/processors.js":(De,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>f.Florence2Processor,Idefics3Processor:()=>J.Idefics3Processor,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,MgpstrProcessor:()=>L.MgpstrProcessor,MoonshineProcessor:()=>N.MoonshineProcessor,OwlViTProcessor:()=>v.OwlViTProcessor,PaliGemmaProcessor:()=>M.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>b.PyAnnoteProcessor,Qwen2VLProcessor:()=>D.Qwen2VLProcessor,SamProcessor:()=>H.SamProcessor,SpeechT5Processor:()=>re.SpeechT5Processor,VLChatProcessor:()=>U.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>ie.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>z.WhisperProcessor});var f=r("./src/models/florence2/processing_florence2.js"),L=r("./src/models/mgp_str/processing_mgp_str.js"),N=r("./src/models/moonshine/processing_moonshine.js"),J=r("./src/models/idefics3/processing_idefics3.js"),U=r("./src/models/janus/processing_janus.js"),w=r("./src/models/jina_clip/processing_jina_clip.js"),v=r("./src/models/owlvit/processing_owlvit.js"),y=r("./src/models/phi3_v/processing_phi3_v.js"),M=r("./src/models/paligemma/processing_paligemma.js"),b=r("./src/models/pyannote/processing_pyannote.js"),D=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),H=r("./src/models/sam/processing_sam.js"),re=r("./src/models/speecht5/processing_speecht5.js"),ie=r("./src/models/wav2vec2/processing_wav2vec2.js"),z=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(De,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(De,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>J});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");class J extends f.FeatureExtractor{async _call(w){(0,f.validate_audio_inputs)(w,"PyAnnoteFeatureExtractor"),w instanceof Float64Array&&(w=new Float32Array(w));const v=[1,1,w.length];return{input_values:new L.Tensor("float32",w,v)}}samples_to_frames(w){return(w-this.config.offset)/this.config.step}post_process_speaker_diarization(w,v){const y=v/this.samples_to_frames(v)/this.config.sampling_rate,M=[];for(const b of w.tolist()){const D=[];let H=-1;for(let re=0;re({id:re,start:ie*y,end:z*y,confidence:V/(z-ie)})))}return M}}},"./src/models/pyannote/processing_pyannote.js":(De,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>N});var f=r("./src/base/processing_utils.js"),L=r("./src/models/pyannote/feature_extraction_pyannote.js");class N extends f.Processor{async _call(U){return await this.feature_extractor(U)}post_process_speaker_diarization(...U){return this.feature_extractor.post_process_speaker_diarization(...U)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}ge(N,"feature_extractor_class",L.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(De,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(U,...w){const{pixel_values:v,original_sizes:y,reshaped_input_sizes:M}=await super._call(U,...w);let b=v;const{temporal_patch_size:D,merge_size:H,patch_size:re}=this.config;b.dims[0]===1&&(b=(0,L.cat)(Array.from({length:D},()=>b),0));const ie=b.dims[0]/D,z=b.dims[1],V=Math.floor(b.dims[2]/re),Q=Math.floor(b.dims[3]/re),F=b.view(ie,D,z,Math.floor(V/H),H,re,Math.floor(Q/H),H,re).permute(0,3,6,4,7,2,1,5,8).view(ie*V*Q,z*D*re*re),$=new L.Tensor("int64",[ie,V,Q],[1,3]);return{pixel_values:F,image_grid_thw:$,original_sizes:y,reshaped_input_sizes:M}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(De,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");class J extends f.Processor{async _call(w,v=null,...y){Array.isArray(w)||(w=[w]);let M,b;if(v&&(M=await this.image_processor(v),b=M.image_grid_thw),b){let H=this.image_processor.config.merge_size**2,re=0;const ie=b.tolist();w=w.map(z=>{for(;z.includes("<|image_pad|>");){const V=Number(ie[re++].reduce((Q,F)=>Q*F,1n));z=z.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(V/H)))}return z.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(w),...M}}}ge(J,"image_processor_class",L.AutoImageProcessor),ge(J,"tokenizer_class",N.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(De,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_object_detection(...J){return(0,f.post_process_object_detection)(...J)}}},"./src/models/sam/image_processing_sam.js":(De,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>J});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/core.js"),N=r("./src/utils/tensor.js");class J extends f.ImageProcessor{reshape_input_points(w,v,y,M=!1){w=structuredClone(w);let b=(0,L.calculateDimensions)(w);if(b.length===3)M||(b=[1,...b]),w=[w];else if(b.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let D=0;DM!==v.dims[b]))throw Error(`The first ${y.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N.Tensor("int64",w.flat(1/0).map(BigInt),y)}async _call(w,{input_points:v=null,input_labels:y=null,input_boxes:M=null}={}){const b=await super._call(w);if(v&&(b.input_points=this.reshape_input_points(v,b.original_sizes,b.reshaped_input_sizes)),y){if(!b.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");b.input_labels=this.add_input_labels(y,b.input_points)}return M&&(b.input_boxes=this.reshape_input_points(M,b.original_sizes,b.reshaped_input_sizes,!0)),b}async post_process_masks(w,v,y,{mask_threshold:M=0,binarize:b=!0,pad_size:D=null}={}){const H=[];D=D??this.pad_size;const re=[D.height,D.width];for(let ie=0;ieM&&($[g]=1);Q=new N.Tensor("bool",$,Q.dims)}H.push(Q)}return H}generate_crop_boxes(w,v,{crop_n_layers:y=0,overlap_ratio:M=.3413333333333333,points_per_crop:b=32,crop_n_points_downscale_factor:D=1}={}){}}},"./src/models/sam/processing_sam.js":(De,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>N});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/image_processing_auto.js");class N extends f.Processor{async _call(...U){return await this.image_processor(...U)}post_process_masks(...U){return this.image_processor.post_process_masks(...U)}reshape_input_points(...U){return this.image_processor.reshape_input_points(...U)}}ge(N,"image_processor_class",L.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(De,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>J});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js"),N=r("./src/utils/audio.js");class J extends f.FeatureExtractor{constructor(w){super(w);const v=this.config.sampling_rate,y=(0,N.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let M=0;My*32768),(0,N.spectrogram)(w,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:v,transpose:!0})}async _call(w,{padding:v=!0,pad_to_multiple_of:y=2,do_normalize_per_mel_bins:M=!0,return_attention_mask:b=!0}={}){(0,f.validate_audio_inputs)(w,"SeamlessM4TFeatureExtractor");let D=await this._extract_fbank_features(w,this.config.max_length);if(M){const[$,g]=D.dims,C=D.data;for(let T=0;T0){const ee=new Float32Array(g*($+T));ee.set(C),ee.fill(this.config.padding_value,C.length);const Y=$+T;D=new L.Tensor(D.type,ee,[Y,g]),b&&(H=new L.Tensor("int64",new BigInt64Array(Y),[1,Y]),H.data.fill(1n,0,$))}}const[re,ie]=D.dims,z=this.config.stride;if(re%z!==0)throw new Error(`The number of frames (${re}) must be a multiple of the stride (${z}).`);const Q=D.view(1,Math.floor(re/z),ie*z),F={input_features:Q};if(b){const $=Q.dims[1],g=new BigInt64Array($);if(H){const C=H.data;for(let T=1,ee=0;T{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>N,SegformerImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_semantic_segmentation(...U){return(0,f.post_process_semantic_segmentation)(...U)}}class N extends L{}},"./src/models/siglip/image_processing_siglip.js":(De,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(De,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>L});var f=r("./src/base/feature_extraction_utils.js");class L extends f.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(De,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>J});var f=r("./src/base/processing_utils.js"),L=r("./src/tokenizers.js"),N=r("./src/models/auto/feature_extraction_auto.js");class J extends f.Processor{async _call(w){return await this.feature_extractor(w)}}ge(J,"tokenizer_class",L.AutoTokenizer),ge(J,"feature_extractor_class",N.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(De,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{pad_image(J,U,w,v={}){const[y,M,b]=U;return super.pad_image(J,U,{width:M+(w-M%w)%w,height:y+(w-y%w)%w},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(De,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>N,ViTImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{}class N extends L{}},"./src/models/vitmatte/image_processing_vitmatte.js":(De,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>N});var f=r("./src/base/image_processors_utils.js"),L=r("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(U,w){Array.isArray(U)||(U=[U]),Array.isArray(w)||(w=[w]);const v=await Promise.all(U.map(b=>this.preprocess(b))),y=await Promise.all(w.map(b=>this.preprocess(b,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,L.stack)(v.map((b,D)=>(0,L.cat)([b.pixel_values,y[D].pixel_values],0)),0),original_sizes:v.map(b=>b.original_size),reshaped_input_sizes:v.map(b=>b.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(De,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_pose_estimation(J,U,{threshold:w=null}={}){const v=J.tolist(),[y,M,b,D]=J.dims,H=[];for(let re=0;re{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js"),L=r("./src/utils/tensor.js");class N extends f.FeatureExtractor{_zero_mean_unit_var_norm(U){const v=U.reduce((M,b)=>M+b,0)/U.length,y=U.reduce((M,b)=>M+(b-v)**2,0)/U.length;return U.map(M=>(M-v)/Math.sqrt(y+1e-7))}async _call(U){(0,f.validate_audio_inputs)(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let w=U;this.config.do_normalize&&(w=this._zero_mean_unit_var_norm(w));const v=[1,w.length];return{input_values:new L.Tensor("float32",w,v),attention_mask:new L.Tensor("int64",new BigInt64Array(w.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(De,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>N});var f=r("./src/base/processing_utils.js"),L=r("./src/models/auto/feature_extraction_auto.js");class N extends f.Processor{async _call(U){return await this.feature_extractor(U)}}ge(N,"feature_extractor_class",L.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(De,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>N});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(U){super(U);const w=this.config.sampling_rate,v=(0,L.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(w/2),w,null,"kaldi",!0);for(let y=0;yw*32768),(0,L.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){(0,f.validate_audio_inputs)(U,"WeSpeakerFeatureExtractor");const w=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=w.mean(1).data,y=w.data,[M,b,D]=w.dims;for(let H=0;H{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>L,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>N,whisper_language_to_code:()=>J});const f=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],L=new Map(f),N=new Map([...f.map(([U,w])=>[w,U]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function J(U){U=U.toLowerCase();let w=N.get(U);if(w===void 0)if(L.has(U))w=U;else{const y=U.length===2?L.keys():L.values();throw new Error(`Language "${U}" is not supported. Must be one of: ${JSON.stringify(y)}`)}return w}},"./src/models/whisper/feature_extraction_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>J});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var L=r("./src/utils/audio.js"),N=r("./src/utils/maths.js");class J extends f.FeatureExtractor{constructor(w){var v;super(w),(v=this.config).mel_filters??(v.mel_filters=(0,L.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,L.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(w){const v=await(0,L.spectrogram)(w,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),y=v.data,M=(0,N.max)(y)[0];for(let b=0;bthis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),v=w.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(w)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>L});var f=r("./src/generation/configuration_utils.js");class L extends f.GenerationConfig{constructor(){super(...arguments);ge(this,"return_timestamps",null);ge(this,"return_token_timestamps",null);ge(this,"num_frames",null);ge(this,"alignment_heads",null);ge(this,"task",null);ge(this,"language",null);ge(this,"no_timestamps_token_id",null);ge(this,"prompt_ids",null);ge(this,"is_multilingual",null);ge(this,"lang_to_id",null);ge(this,"task_to_id",null);ge(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>J});var f=r("./src/models/auto/feature_extraction_auto.js"),L=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class J extends N.Processor{async _call(w){return await this.feature_extractor(w)}}ge(J,"tokenizer_class",L.AutoTokenizer),ge(J,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(De,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>N,YolosImageProcessor:()=>L});var f=r("./src/base/image_processors_utils.js");class L extends f.ImageProcessor{post_process_object_detection(...U){return(0,f.post_process_object_detection)(...U)}}class N extends L{}},"./src/ops/registry.js":(De,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>J});var f=r("./src/backends/onnx.js"),L=r("./src/utils/tensor.js");const N=async(U,w,v)=>{const y=await(0,f.createInferenceSession)(new Uint8Array(U),w);return async M=>{const b=Object.fromEntries(Object.entries(M).map(([H,re])=>[H,re.ort_tensor])),D=await y.run(b);return Array.isArray(v)?v.map(H=>new L.Tensor(D[H])):new L.Tensor(D[v])}};class J{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=N([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=N([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=N([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=N([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=N([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=N([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=N([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}ge(J,"session_options",{})},"./src/pipelines.js":(De,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>de,AutomaticSpeechRecognitionPipeline:()=>Ce,DepthEstimationPipeline:()=>Be,DocumentQuestionAnsweringPipeline:()=>se,FeatureExtractionPipeline:()=>Y,FillMaskPipeline:()=>Q,ImageClassificationPipeline:()=>Le,ImageFeatureExtractionPipeline:()=>le,ImageSegmentationPipeline:()=>qe,ImageToImagePipeline:()=>Ee,ImageToTextPipeline:()=>Te,ObjectDetectionPipeline:()=>ut,Pipeline:()=>re,QuestionAnsweringPipeline:()=>V,SummarizationPipeline:()=>$,Text2TextGenerationPipeline:()=>F,TextClassificationPipeline:()=>ie,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>he,TokenClassificationPipeline:()=>z,TranslationPipeline:()=>g,ZeroShotAudioClassificationPipeline:()=>fe,ZeroShotClassificationPipeline:()=>ee,ZeroShotImageClassificationPipeline:()=>Ue,ZeroShotObjectDetectionPipeline:()=>ue,pipeline:()=>oe});var f=r("./src/tokenizers.js"),L=r("./src/models.js"),N=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var J=r("./src/utils/generic.js"),U=r("./src/utils/core.js"),w=r("./src/utils/maths.js"),v=r("./src/utils/audio.js"),y=r("./src/utils/tensor.js"),M=r("./src/utils/image.js");async function b(Fe){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(ce=>M.RawImage.read(ce)))}async function D(Fe,ce){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(ve=>typeof ve=="string"||ve instanceof URL?(0,v.read_audio)(ve,ce):ve instanceof Float64Array?new Float32Array(ve):ve))}function H(Fe,ce){ce&&(Fe=Fe.map(Ne=>Ne|0));const[ve,Re,je,Ve]=Fe;return{xmin:ve,ymin:Re,xmax:je,ymax:Ve}}class re extends J.Callable{constructor({task:ce,model:ve,tokenizer:Re=null,processor:je=null}){super(),this.task=ce,this.model=ve,this.tokenizer=Re,this.processor=je}async dispose(){await this.model.dispose()}}class ie extends re{constructor(ce){super(ce)}async _call(ce,{top_k:ve=1}={}){const Re=this.tokenizer(ce,{padding:!0,truncation:!0}),je=await this.model(Re),Ve=this.model.config.problem_type==="multi_label_classification"?at=>at.sigmoid():at=>new y.Tensor("float32",(0,w.softmax)(at.data),at.dims),Ne=this.model.config.id2label,Ze=[];for(const at of je.logits){const ft=Ve(at),dt=await(0,y.topk)(ft,ve),gt=dt[0].tolist(),ne=dt[1].tolist().map((K,pe)=>({label:Ne?Ne[K]:`LABEL_${K}`,score:gt[pe]}));ve===1?Ze.push(...ne):Ze.push(ne)}return Array.isArray(ce)||ve===1?Ze:Ze[0]}}class z extends re{constructor(ce){super(ce)}async _call(ce,{ignore_labels:ve=["O"]}={}){const Re=Array.isArray(ce),je=this.tokenizer(Re?ce:[ce],{padding:!0,truncation:!0}),Ne=(await this.model(je)).logits,Ze=this.model.config.id2label,at=[];for(let ft=0;ftpt==this.tokenizer.sep_token_id);at[gt].map((pt,It)=>pt==1&&(It===0||It>ne&&ft.findIndex(St=>St==O[It])===-1));const K=Ve[gt].tolist(),pe=Ne[gt].tolist();for(let pt=1;ptIt==O[pt])!==-1)&&(K[pt]=-1/0,pe[pt]=-1/0);const Oe=(0,w.softmax)(K).map((pt,It)=>[pt,It]),Qe=(0,w.softmax)(pe).map((pt,It)=>[pt,It]);Oe[0][0]=0,Qe[0][0]=0;const rt=(0,U.product)(Oe,Qe).filter(pt=>pt[0][1]<=pt[1][1]).map(pt=>[pt[0][1],pt[1][1],pt[0][0]*pt[1][0]]).sort((pt,It)=>It[2]-pt[2]);for(let pt=0;ptK==this.tokenizer.mask_token_id);if(ft===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const dt=je[Ze][ft],gt=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(dt.data),dt.dims),ve),O=gt[0].tolist(),ne=gt[1].tolist();Ve.push(ne.map((K,pe)=>{const Oe=at.slice();return Oe[ft]=K,{score:O[pe],token:Number(K),token_str:this.tokenizer.decode([K]),sequence:this.tokenizer.decode(Oe,{skip_special_tokens:!0})}}))}return Array.isArray(ce)?Ve:Ve[0]}}class F extends re{constructor(ve){super(ve);ge(this,"_key","generated_text")}async _call(ve,Re={}){Array.isArray(ve)||(ve=[ve]),this.model.config.prefix&&(ve=ve.map(ft=>this.model.config.prefix+ft));const je=this.model.config.task_specific_params;je&&je[this.task]&&je[this.task].prefix&&(ve=ve.map(ft=>je[this.task].prefix+ft));const Ve=this.tokenizer,Ne={padding:!0,truncation:!0};let Ze;this instanceof g&&"_build_translation_inputs"in Ve?Ze=Ve._build_translation_inputs(ve,Ne,Re):Ze=Ve(ve,Ne);const at=await this.model.generate({...Ze,...Re});return Ve.batch_decode(at,{skip_special_tokens:!0}).map(ft=>({[this._key]:ft}))}}class $ extends F{constructor(ve){super(ve);ge(this,"_key","summary_text")}}class g extends F{constructor(ve){super(ve);ge(this,"_key","translation_text")}}function C(Fe){return Array.isArray(Fe)&&Fe.every(ce=>"role"in ce&&"content"in ce)}class T extends re{constructor(ce){super(ce)}async _call(ce,ve={}){let Re=!1,je=!1,Ve;if(typeof ce=="string")Ve=ce=[ce];else if(Array.isArray(ce)&&ce.every(ne=>typeof ne=="string"))Re=!0,Ve=ce;else{if(C(ce))ce=[ce];else if(Array.isArray(ce)&&ce.every(C))Re=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");je=!0,Ve=ce.map(ne=>this.tokenizer.apply_chat_template(ne,{tokenize:!1,add_generation_prompt:!0}))}const Ne=ve.add_special_tokens??!1,Ze=je?!1:ve.return_full_text??!0;this.tokenizer.padding_side="left";const at=this.tokenizer(Ve,{add_special_tokens:Ne,padding:!0,truncation:!0}),ft=await this.model.generate({...at,...ve}),dt=this.tokenizer.batch_decode(ft,{skip_special_tokens:!0});let gt;!Ze&&at.input_ids.dims.at(-1)>0&&(gt=this.tokenizer.batch_decode(at.input_ids,{skip_special_tokens:!0}).map(ne=>ne.length));const O=Array.from({length:ce.length},ne=>[]);for(let ne=0;ne[ve.toLowerCase(),Re])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(ce,ve,{hypothesis_template:Re="This example is {}.",multi_label:je=!1}={}){const Ve=Array.isArray(ce);Ve||(ce=[ce]),Array.isArray(ve)||(ve=[ve]);const Ne=ve.map(ft=>Re.replace("{}",ft)),Ze=je||ve.length===1,at=[];for(const ft of ce){const dt=[];for(const ne of Ne){const K=this.tokenizer(ft,{text_pair:ne,padding:!0,truncation:!0}),pe=await this.model(K);Ze?dt.push([pe.logits.data[this.contradiction_id],pe.logits.data[this.entailment_id]]):dt.push(pe.logits.data[this.entailment_id])}const O=(Ze?dt.map(ne=>(0,w.softmax)(ne)[1]):(0,w.softmax)(dt)).map((ne,K)=>[ne,K]).sort((ne,K)=>K[0]-ne[0]);at.push({sequence:ft,labels:O.map(ne=>ve[ne[1]]),scores:O.map(ne=>ne[0])})}return Ve?at:at[0]}}class Y extends re{constructor(ce){super(ce)}async _call(ce,{pooling:ve="none",normalize:Re=!1,quantize:je=!1,precision:Ve="binary"}={}){const Ne=this.tokenizer(ce,{padding:!0,truncation:!0}),Ze=await this.model(Ne);let at=Ze.last_hidden_state??Ze.logits??Ze.token_embeddings;if(ve!=="none")if(ve==="mean")at=(0,y.mean_pooling)(at,Ne.attention_mask);else if(ve==="cls")at=at.slice(null,0);else throw Error(`Pooling method '${ve}' not supported.`);return Re&&(at=at.normalize(2,-1)),je&&(at=(0,y.quantize_embeddings)(at,Ve)),at}}class le extends re{constructor(ce){super(ce)}async _call(ce,{pool:ve=null}={}){const Re=await b(ce),{pixel_values:je}=await this.processor(Re),Ve=await this.model({pixel_values:je});let Ne;if(ve){if(!("pooler_output"in Ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ne=Ve.pooler_output}else Ne=Ve.last_hidden_state??Ve.logits??Ve.image_embeds;return Ne}}class de extends re{constructor(ce){super(ce)}async _call(ce,{top_k:ve=5}={}){const Re=this.processor.feature_extractor.config.sampling_rate,je=await D(ce,Re),Ve=this.model.config.id2label,Ne=[];for(const Ze of je){const at=await this.processor(Ze),dt=(await this.model(at)).logits[0],gt=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(dt.data),dt.dims),ve),O=gt[0].tolist(),K=gt[1].tolist().map((pe,Oe)=>({label:Ve?Ve[pe]:`LABEL_${pe}`,score:O[Oe]}));Ne.push(K)}return Array.isArray(ce)?Ne:Ne[0]}}class fe extends re{constructor(ce){super(ce)}async _call(ce,ve,{hypothesis_template:Re="This is a sound of {}."}={}){const je=!Array.isArray(ce);je&&(ce=[ce]);const Ve=ve.map(dt=>Re.replace("{}",dt)),Ne=this.tokenizer(Ve,{padding:!0,truncation:!0}),Ze=this.processor.feature_extractor.config.sampling_rate,at=await D(ce,Ze),ft=[];for(const dt of at){const gt=await this.processor(dt),O=await this.model({...Ne,...gt}),ne=(0,w.softmax)(O.logits_per_audio.data);ft.push([...ne].map((K,pe)=>({score:K,label:ve[pe]})))}return je?ft[0]:ft}}class Ce extends re{constructor(ce){super(ce)}async _call(ce,ve={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ce,ve);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ce,ve);case"moonshine":return this._call_moonshine(ce,ve);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ce,ve){ve.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ve.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Re=!Array.isArray(ce);Re&&(ce=[ce]);const je=this.processor.feature_extractor.config.sampling_rate,Ve=await D(ce,je),Ne=[];for(const Ze of Ve){const at=await this.processor(Ze),dt=(await this.model(at)).logits[0],gt=[];for(const ne of dt)gt.push((0,w.max)(ne.data)[1]);const O=this.tokenizer.decode(gt);Ne.push({text:O})}return Re?Ne[0]:Ne}async _call_whisper(ce,ve){const Re=ve.return_timestamps??!1,je=ve.chunk_length_s??0,Ve=ve.force_full_sequences??!1;let Ne=ve.stride_length_s??null;const Ze={...ve};Re==="word"&&(Ze.return_token_timestamps=!0,Ze.return_timestamps=!1);const at=!Array.isArray(ce);at&&(ce=[ce]);const ft=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,dt=this.processor.feature_extractor.config.hop_length,gt=this.processor.feature_extractor.config.sampling_rate,O=await D(ce,gt),ne=[];for(const K of O){let pe=[];if(je>0){if(Ne===null)Ne=je/6;else if(je<=Ne)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const rt=gt*je,pt=gt*Ne,It=rt-2*pt;let St=0;for(;;){const Ft=St+rt,At=K.subarray(St,Ft),ns=await this.processor(At),gs=St===0,ks=Ft>=K.length;if(pe.push({stride:[At.length,gs?0:pt,ks?0:pt],input_features:ns.input_features,is_last:ks}),ks)break;St+=It}}else pe=[{stride:[K.length,0,0],input_features:(await this.processor(K)).input_features,is_last:!0}];for(const rt of pe){Ze.num_frames=Math.floor(rt.stride[0]/dt);const pt=await this.model.generate({inputs:rt.input_features,...Ze});Re==="word"?(rt.tokens=pt.sequences.tolist()[0],rt.token_timestamps=pt.token_timestamps.tolist()[0].map(It=>(0,w.round)(It,2))):rt.tokens=pt[0].tolist(),rt.stride=rt.stride.map(It=>It/gt)}const[Oe,Qe]=this.tokenizer._decode_asr(pe,{time_precision:ft,return_timestamps:Re,force_full_sequences:Ve});ne.push({text:Oe,...Qe})}return at?ne[0]:ne}async _call_moonshine(ce,ve){const Re=!Array.isArray(ce);Re&&(ce=[ce]);const je=this.processor.feature_extractor.config.sampling_rate,Ve=await D(ce,je),Ne=[];for(const Ze of Ve){const at=await this.processor(Ze),ft=Math.floor(Ze.length/je)*6,dt=await this.model.generate({max_new_tokens:ft,...ve,...at}),gt=this.processor.batch_decode(dt,{skip_special_tokens:!0})[0];Ne.push({text:gt})}return Re?Ne[0]:Ne}}class Te extends re{constructor(ce){super(ce)}async _call(ce,ve={}){const Re=Array.isArray(ce),je=await b(ce),{pixel_values:Ve}=await this.processor(je),Ne=[];for(const Ze of Ve){Ze.dims=[1,...Ze.dims];const at=await this.model.generate({inputs:Ze,...ve}),ft=this.tokenizer.batch_decode(at,{skip_special_tokens:!0}).map(dt=>({generated_text:dt.trim()}));Ne.push(ft)}return Re?Ne:Ne[0]}}class Le extends re{constructor(ce){super(ce)}async _call(ce,{top_k:ve=5}={}){const Re=await b(ce),{pixel_values:je}=await this.processor(Re),Ve=await this.model({pixel_values:je}),Ne=this.model.config.id2label,Ze=[];for(const at of Ve.logits){const ft=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(at.data),at.dims),ve),dt=ft[0].tolist(),O=ft[1].tolist().map((ne,K)=>({label:Ne?Ne[ne]:`LABEL_${ne}`,score:dt[K]}));Ze.push(O)}return Array.isArray(ce)?Ze:Ze[0]}}class qe extends re{constructor(ce){super(ce),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ce,{threshold:ve=.5,mask_threshold:Re=.5,overlap_mask_area_threshold:je=.8,label_ids_to_fuse:Ve=null,target_sizes:Ne=null,subtask:Ze=null}={}){if(Array.isArray(ce)&&ce.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ft=await b(ce),dt=ft.map(Qe=>[Qe.height,Qe.width]),{pixel_values:gt,pixel_mask:O}=await this.processor(ft),ne=await this.model({pixel_values:gt,pixel_mask:O});let K=null;if(Ze!==null)K=this.subtasks_mapping[Ze];else for(let[Qe,rt]of Object.entries(this.subtasks_mapping))if(rt in this.processor.image_processor){K=this.processor.image_processor[rt].bind(this.processor.image_processor),Ze=Qe;break}const pe=this.model.config.id2label,Oe=[];if(Ze==="panoptic"||Ze==="instance"){const Qe=K(ne,ve,Re,je,Ve,Ne??dt)[0],rt=Qe.segmentation;for(const pt of Qe.segments_info){const It=new Uint8ClampedArray(rt.data.length);for(let Ft=0;FtRe.replace("{}",O)),Ze=this.tokenizer(Ne,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:at}=await this.processor(Ve),ft=await this.model({...Ze,pixel_values:at}),dt=this.model.config.model_type==="siglip"?O=>O.sigmoid().data:O=>(0,w.softmax)(O.data),gt=[];for(const O of ft.logits_per_image){const K=[...dt(O)].map((pe,Oe)=>({score:pe,label:ve[Oe]}));K.sort((pe,Oe)=>Oe.score-pe.score),gt.push(K)}return je?gt:gt[0]}}class ut extends re{constructor(ce){super(ce)}async _call(ce,{threshold:ve=.9,percentage:Re=!1}={}){const je=Array.isArray(ce);if(je&&ce.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ve=await b(ce),Ne=Re?null:Ve.map(ne=>[ne.height,ne.width]),{pixel_values:Ze,pixel_mask:at}=await this.processor(Ve),ft=await this.model({pixel_values:Ze,pixel_mask:at}),dt=this.processor.image_processor.post_process_object_detection(ft,ve,Ne),gt=this.model.config.id2label,O=dt.map(ne=>ne.boxes.map((K,pe)=>({score:ne.scores[pe],label:gt[ne.classes[pe]],box:H(K,!Re)})));return je?O:O[0]}}class ue extends re{constructor(ce){super(ce)}async _call(ce,ve,{threshold:Re=.1,top_k:je=null,percentage:Ve=!1}={}){const Ne=Array.isArray(ce),Ze=await b(ce),at=this.tokenizer(ve,{padding:!0,truncation:!0}),ft=await this.processor(Ze),dt=[];for(let gt=0;gt({score:Oe.scores[pt],label:ve[Oe.classes[pt]],box:H(rt,!Ve)})).sort((rt,pt)=>pt.score-rt.score);je!==null&&(Qe=Qe.slice(0,je)),dt.push(Qe)}return Ne?dt:dt[0]}}class se extends re{constructor(ce){super(ce)}async _call(ce,ve,Re={}){const je=(await b(ce))[0],{pixel_values:Ve}=await this.processor(je),Ne=`${ve}`,Ze=this.tokenizer(Ne,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,at=await this.model.generate({inputs:Ve,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ze,...Re}),dt=this.tokenizer.batch_decode(at)[0].match(/(.*?)<\/s_answer>/);let gt=null;return dt&&dt.length>=2&&(gt=dt[1].trim()),[{answer:gt}]}}class he extends re{constructor(ve){super(ve);ge(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ve.vocoder??null}async _call(ve,{speaker_embeddings:Re=null}={}){return this.processor?this._call_text_to_spectrogram(ve,{speaker_embeddings:Re}):this._call_text_to_waveform(ve)}async _call_text_to_waveform(ve){const Re=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:je}=await this.model(Re),Ve=this.model.config.sampling_rate;return{audio:je.data,sampling_rate:Ve}}async _call_text_to_spectrogram(ve,{speaker_embeddings:Re}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await L.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Re=="string"||Re instanceof URL)&&(Re=new Float32Array(await(await fetch(Re)).arrayBuffer())),Re instanceof Float32Array)Re=new y.Tensor("float32",Re,[1,Re.length]);else if(!(Re instanceof y.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:je}=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model.generate_speech(je,Re,{vocoder:this.vocoder}),Ne=this.processor.feature_extractor.config.sampling_rate;return{audio:Ve.data,sampling_rate:Ne}}}class Ee extends re{constructor(ce){super(ce)}async _call(ce){const ve=await b(ce),Re=await this.processor(ve),je=await this.model(Re),Ve=[];for(const Ne of je.reconstruction){const Ze=Ne.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ve.push(M.RawImage.fromTensor(Ze))}return Ve.length>1?Ve:Ve[0]}}class Be extends re{constructor(ce){super(ce)}async _call(ce){const ve=await b(ce),Re=await this.processor(ve),{predicted_depth:je}=await this.model(Re),Ve=[];for(let Ne=0;Ne1?Ve:Ve[0]}}const et=Object.freeze({"text-classification":{tokenizer:f.AutoTokenizer,pipeline:ie,model:L.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:f.AutoTokenizer,pipeline:z,model:L.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:f.AutoTokenizer,pipeline:V,model:L.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:f.AutoTokenizer,pipeline:Q,model:L.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:f.AutoTokenizer,pipeline:$,model:L.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:f.AutoTokenizer,pipeline:g,model:L.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:f.AutoTokenizer,pipeline:F,model:L.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:f.AutoTokenizer,pipeline:T,model:L.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:f.AutoTokenizer,pipeline:ee,model:L.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:de,model:L.AutoModelForAudioClassification,processor:N.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:f.AutoTokenizer,pipeline:fe,model:L.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:f.AutoTokenizer,pipeline:Ce,model:[L.AutoModelForSpeechSeq2Seq,L.AutoModelForCTC],processor:N.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:f.AutoTokenizer,pipeline:he,model:[L.AutoModelForTextToWaveform,L.AutoModelForTextToSpectrogram],processor:[N.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:f.AutoTokenizer,pipeline:Te,model:L.AutoModelForVision2Seq,processor:N.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Le,model:L.AutoModelForImageClassification,processor:N.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:qe,model:[L.AutoModelForImageSegmentation,L.AutoModelForSemanticSegmentation,L.AutoModelForUniversalSegmentation],processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:f.AutoTokenizer,pipeline:Ue,model:L.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ut,model:L.AutoModelForObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:f.AutoTokenizer,pipeline:ue,model:L.AutoModelForZeroShotObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:f.AutoTokenizer,pipeline:se,model:L.AutoModelForDocumentQuestionAnswering,processor:N.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Ee,model:L.AutoModelForImageToImage,processor:N.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Be,model:L.AutoModelForDepthEstimation,processor:N.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:f.AutoTokenizer,pipeline:Y,model:L.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:N.AutoProcessor,pipeline:le,model:[L.AutoModelForImageFeatureExtraction,L.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Xe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function oe(Fe,ce=null,{progress_callback:ve=null,config:Re=null,cache_dir:je=null,local_files_only:Ve=!1,revision:Ne="main",device:Ze=null,dtype:at=null,model_file_name:ft=null,session_options:dt={}}={}){Fe=Xe[Fe]??Fe;const gt=et[Fe.split("_",1)[0]];if(!gt)throw Error(`Unsupported pipeline: ${Fe}. Must be one of [${Object.keys(et)}]`);ce||(ce=gt.default.model,console.log(`No model specified. Using default model: "${ce}".`));const O={progress_callback:ve,config:Re,cache_dir:je,local_files_only:Ve,revision:Ne,device:Ze,dtype:at,model_file_name:ft,session_options:dt},ne=new Map([["tokenizer",gt.tokenizer],["model",gt.model],["processor",gt.processor]]),K=await Je(ne,ce,O);K.task=Fe,(0,U.dispatchCallback)(ve,{status:"ready",task:Fe,model:ce});const pe=gt.pipeline;return new pe(K)}async function Je(Fe,ce,ve){const Re=Object.create(null),je=[];for(const[Ve,Ne]of Fe.entries()){if(!Ne)continue;let Ze;Array.isArray(Ne)?Ze=new Promise(async(at,ft)=>{var gt,O;let dt;for(const ne of Ne){if(ne===null){at(null);return}try{at(await ne.from_pretrained(ce,ve));return}catch(K){if((gt=K.message)!=null&>.includes("Unsupported model type"))dt=K;else if((O=K.message)!=null&&O.includes("Could not locate file"))dt=K;else{ft(K);return}}}ft(dt)}):Ze=Ne.from_pretrained(ce,ve),Re[Ve]=Ze,je.push(Ze)}await Promise.all(je);for(const[Ve,Ne]of Object.entries(Re))Re[Ve]=await Ne;return Re}},"./src/tokenizers.js":(De,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>Sr,AutoTokenizer:()=>vn,BartTokenizer:()=>ts,BertTokenizer:()=>Jr,BlenderbotSmallTokenizer:()=>Fn,BlenderbotTokenizer:()=>yn,BloomTokenizer:()=>jr,CLIPTokenizer:()=>An,CamembertTokenizer:()=>nt,CodeGenTokenizer:()=>$n,CodeLlamaTokenizer:()=>Ur,CohereTokenizer:()=>Dn,ConvBertTokenizer:()=>Ir,DebertaTokenizer:()=>ar,DebertaV2Tokenizer:()=>Ar,DistilBertTokenizer:()=>lr,ElectraTokenizer:()=>Ot,EsmTokenizer:()=>ur,FalconTokenizer:()=>Wr,GPT2Tokenizer:()=>vr,GPTNeoXTokenizer:()=>xr,GemmaTokenizer:()=>tn,Grok1Tokenizer:()=>gn,HerbertTokenizer:()=>pr,LlamaTokenizer:()=>kn,M2M100Tokenizer:()=>zt,MBart50Tokenizer:()=>Nr,MBartTokenizer:()=>tr,MPNetTokenizer:()=>Jn,MarianTokenizer:()=>Vr,MgpstrTokenizer:()=>bn,MobileBertTokenizer:()=>Rr,NllbTokenizer:()=>Er,NougatTokenizer:()=>Ys,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>fn,RoFormerTokenizer:()=>Zr,RobertaTokenizer:()=>en,SiglipTokenizer:()=>In,SpeechT5Tokenizer:()=>is,SqueezeBertTokenizer:()=>$r,T5Tokenizer:()=>ls,TokenizerModel:()=>le,VitsTokenizer:()=>Mn,Wav2Vec2CTCTokenizer:()=>On,WhisperTokenizer:()=>wn,XLMRobertaTokenizer:()=>Sn,XLMTokenizer:()=>_t,is_chinese_char:()=>Q});var f=r("./src/utils/generic.js"),L=r("./src/utils/core.js"),N=r("./src/utils/hub.js"),J=r("./src/utils/maths.js"),U=r("./src/utils/tensor.js"),w=r("./src/utils/data-structures.js"),v=r("./node_modules/@huggingface/jinja/dist/index.js"),y=r("./src/models/whisper/common_whisper.js");r("./src/utils/constants.js");async function M(xe,P){const q=await Promise.all([(0,N.getModelJSON)(xe,"tokenizer.json",!0,P),(0,N.getModelJSON)(xe,"tokenizer_config.json",!0,P)]);return P.legacy!==null&&(q[1].legacy=P.legacy),q}function b(xe,P){const q=[];let ae=0;for(const Me of xe.matchAll(P)){const Pe=Me[0];ae0&&q.push(Pe),ae=Me.index+Pe.length}return ae=19968&&xe<=40959||xe>=13312&&xe<=19903||xe>=131072&&xe<=173791||xe>=173824&&xe<=177983||xe>=177984&&xe<=178207||xe>=178208&&xe<=183983||xe>=63744&&xe<=64255||xe>=194560&&xe<=195103}function F(xe,P,q){const ae=[];let Me=0;for(;Methis.tokens_to_ids.get(q)??this.unk_token_id)}convert_ids_to_tokens(P){return P.map(q=>this.vocab[q]??this.unk_token)}}class de extends le{constructor(P){super(P),this.tokens_to_ids=H(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.max_input_chars_per_word=P.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[q,ae]of this.tokens_to_ids)this.vocab[ae]=q}encode(P){const q=[];for(const ae of P){const Me=[...ae];if(Me.length>this.max_input_chars_per_word){q.push(this.unk_token);continue}let Pe=!1,He=0;const ct=[];for(;He0&&(it=this.config.continuing_subword_prefix+it),this.tokens_to_ids.has(it)){ht=it;break}--yt}if(ht===null){Pe=!0;break}ct.push(ht),He=yt}Pe?q.push(this.unk_token):q.push(...ct)}return q}}class fe extends le{constructor(P,q){super(P);const ae=P.vocab.length;this.vocab=new Array(ae),this.scores=new Array(ae);for(let Me=0;Me[Me,Pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,J.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new w.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(P){const q=P.chars,ae=1;let Me=0;for(;Me{const xe=[...Array.from({length:94},(Me,Pe)=>Pe+33),...Array.from({length:12},(Me,Pe)=>Pe+161),...Array.from({length:82},(Me,Pe)=>Pe+174)],P=xe.slice();let q=0;for(let Me=0;Me<256;++Me)xe.includes(Me)||(xe.push(Me),P.push(256+q),q+=1);const ae=P.map(Me=>String.fromCharCode(Me));return Object.fromEntries(xe.map((Me,Pe)=>[Me,ae[Pe]]))})(),Te=(0,L.reverseDictionary)(Ce);class Le extends le{constructor(P){super(P),this.tokens_to_ids=H(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ae,Me]of this.tokens_to_ids)this.vocab[Me]=ae;const q=Array.isArray(P.merges[0]);this.merges=q?P.merges:P.merges.map(ae=>ae.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ae,Me)=>[JSON.stringify(ae),Me])),this.end_of_word_suffix=P.end_of_word_suffix,this.continuing_subword_suffix=P.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(P){if(P.length===0)return[];const q=this.cache.get(P);if(q!==void 0)return q;const ae=Array.from(P);this.end_of_word_suffix&&(ae[ae.length-1]+=this.end_of_word_suffix);let Me=[];if(ae.length>1){const Pe=new w.PriorityQueue((yt,ht)=>yt.score`<0x${ct.toString(16).toUpperCase().padStart(2,"0")}>`);He.every(ct=>this.tokens_to_ids.has(ct))?q.push(...He):q.push(this.unk_token)}else q.push(this.unk_token)}return q}}class qe extends le{constructor(P,q){super(P),this.tokens_to_ids=H(q.target_lang?P.vocab[q.target_lang]:P.vocab),this.bos_token=q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=q.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[ae,Me]of this.tokens_to_ids)this.vocab[Me]=ae}encode(P){return P}}class Ue extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"BertNormalizer":return new Je(P);case"Precompiled":return new gs(P);case"Sequence":return new oe(P);case"Replace":return new ut(P);case"NFC":return new ue(P);case"NFKC":return new se(P);case"NFKD":return new he(P);case"Strip":return new Ee(P);case"StripAccents":return new Be(P);case"Lowercase":return new et(P);case"Prepend":return new Xe(P);default:throw new Error(`Unknown Normalizer type: ${P.type}`)}}normalize(P){throw Error("normalize should be implemented in subclass.")}_call(P){return this.normalize(P)}}class ut extends Ue{normalize(P){const q=D(this.config.pattern);return q===null?P:P.replaceAll(q,this.config.content)}}class ue extends Ue{normalize(P){return P=P.normalize("NFC"),P}}class se extends Ue{normalize(P){return P=P.normalize("NFKC"),P}}class he extends Ue{normalize(P){return P=P.normalize("NFKD"),P}}class Ee extends Ue{normalize(P){return this.config.strip_left&&this.config.strip_right?P=P.trim():(this.config.strip_left&&(P=P.trimStart()),this.config.strip_right&&(P=P.trimEnd())),P}}class Be extends Ue{normalize(P){return P=z(P),P}}class et extends Ue{normalize(P){return P=P.toLowerCase(),P}}class Xe extends Ue{normalize(P){return P=this.config.prepend+P,P}}class oe extends Ue{constructor(P){super(P),this.normalizers=P.normalizers.map(q=>Ue.fromConfig(q))}normalize(P){return this.normalizers.reduce((q,ae)=>ae.normalize(q),P)}}class Je extends Ue{_tokenize_chinese_chars(P){const q=[];for(let ae=0;aethis.pre_tokenize_text(ae,q)):this.pre_tokenize_text(P,q)).flat()}_call(P,q){return this.pre_tokenize(P,q)}}class ce extends Fe{constructor(P){super(),this.pattern=new RegExp(`[^\\s${g}]+|[${g}]`,"gu")}pre_tokenize_text(P,q){return P.trim().match(this.pattern)||[]}}class ve extends Fe{constructor(P){super(),this.config=P,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Ce,this.text_encoder=new TextEncoder}pre_tokenize_text(P,q){return this.add_prefix_space&&!P.startsWith(" ")&&(P=" "+P),(this.use_regex?P.match(this.pattern)||[]:[P]).map(Me=>Array.from(this.text_encoder.encode(Me),Pe=>this.byte_encoder[Pe]).join(""))}}class Re extends Fe{constructor(P){super(),this.config=P,this.pattern=D(this.config.pattern,this.config.invert)}pre_tokenize_text(P,q){var ae;return this.pattern===null?[]:this.config.invert?P.match(this.pattern)||[]:((ae=this.config.behavior)==null?void 0:ae.toLowerCase())==="removed"?P.split(this.pattern).filter(Me=>Me):b(P,this.pattern)}}class je extends Fe{constructor(P){super(),this.config=P,this.pattern=new RegExp(`[^${g}]+|[${g}]+`,"gu")}pre_tokenize_text(P,q){return P.match(this.pattern)||[]}}class Ve extends Fe{constructor(P){super(),this.config=P;const q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(q,"gu")}pre_tokenize_text(P,q){return P.match(this.pattern)||[]}}class Ne extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"TemplateProcessing":return new ft(P);case"ByteLevel":return new dt(P);case"RobertaProcessing":return new at(P);case"BertProcessing":return new Ze(P);case"Sequence":return new gt(P);default:throw new Error(`Unknown PostProcessor type: ${P.type}`)}}post_process(P,...q){throw Error("post_process should be implemented in subclass.")}_call(P,...q){return this.post_process(P,...q)}}class Ze extends Ne{constructor(P){super(P),this.cls=P.cls[0],this.sep=P.sep[0]}post_process(P,q=null,{add_special_tokens:ae=!0}={}){ae&&(P=(0,L.mergeArrays)([this.cls],P,[this.sep]));let Me=new Array(P.length).fill(0);if(q!==null){const Pe=ae&&this instanceof at?[this.sep]:[],He=ae?[this.sep]:[];P=(0,L.mergeArrays)(P,Pe,q,He),Me=(0,L.mergeArrays)(Me,new Array(q.length+Pe.length+He.length).fill(1))}return{tokens:P,token_type_ids:Me}}}class at extends Ze{}class ft extends Ne{constructor(P){super(P),this.single=P.single,this.pair=P.pair}post_process(P,q=null,{add_special_tokens:ae=!0}={}){const Me=q===null?this.single:this.pair;let Pe=[],He=[];for(const ct of Me)"SpecialToken"in ct?ae&&(Pe.push(ct.SpecialToken.id),He.push(ct.SpecialToken.type_id)):"Sequence"in ct&&(ct.Sequence.id==="A"?(Pe=(0,L.mergeArrays)(Pe,P),He=(0,L.mergeArrays)(He,new Array(P.length).fill(ct.Sequence.type_id))):ct.Sequence.id==="B"&&(Pe=(0,L.mergeArrays)(Pe,q),He=(0,L.mergeArrays)(He,new Array(q.length).fill(ct.Sequence.type_id))));return{tokens:Pe,token_type_ids:He}}}class dt extends Ne{post_process(P,q=null){return q&&(P=(0,L.mergeArrays)(P,q)),{tokens:P}}}class gt extends Ne{constructor(P){super(P),this.processors=P.processors.map(q=>Ne.fromConfig(q))}post_process(P,q=null,ae={}){let Me;for(const Pe of this.processors)if(Pe instanceof dt)P=Pe.post_process(P).tokens,q&&(q=Pe.post_process(q).tokens);else{const He=Pe.post_process(P,q,ae);P=He.tokens,Me=He.token_type_ids}return{tokens:P,token_type_ids:Me}}}class O extends f.Callable{constructor(P){super(),this.config=P,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=P.trim_offsets}static fromConfig(P){if(P===null)return null;switch(P.type){case"WordPiece":return new Qe(P);case"Metaspace":return new ns(P);case"ByteLevel":return new rt(P);case"Replace":return new ne(P);case"ByteFallback":return new K(P);case"Fuse":return new pe(P);case"Strip":return new Oe(P);case"Sequence":return new It(P);case"CTC":return new pt(P);case"BPEDecoder":return new St(P);default:throw new Error(`Unknown Decoder type: ${P.type}`)}}_call(P){return this.decode(P)}decode(P){return this.decode_chain(P).join("")}decode_chain(P){throw Error("`decode_chain` should be implemented in subclass.")}}class ne extends O{decode_chain(P){const q=D(this.config.pattern);return q===null?P:P.map(ae=>ae.replaceAll(q,this.config.content))}}class K extends O{constructor(P){super(P),this.text_decoder=new TextDecoder}decode_chain(P){const q=[];let ae=[];for(const Me of P){let Pe=null;if(Me.length===6&&Me.startsWith("<0x")&&Me.endsWith(">")){const He=parseInt(Me.slice(3,5),16);isNaN(He)||(Pe=He)}if(Pe!==null)ae.push(Pe);else{if(ae.length>0){const He=this.text_decoder.decode(Uint8Array.from(ae));q.push(He),ae=[]}q.push(Me)}}if(ae.length>0){const Me=this.text_decoder.decode(Uint8Array.from(ae));q.push(Me),ae=[]}return q}}class pe extends O{decode_chain(P){return[P.join("")]}}class Oe extends O{constructor(P){super(P),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(P){return P.map(q=>{let ae=0;for(let Pe=0;Pe(ae!==0&&(q.startsWith(this.config.prefix)?q=q.replace(this.config.prefix,""):q=" "+q),this.cleanup&&(q=ie(q)),q))}}class rt extends O{constructor(P){super(P),this.byte_decoder=Te,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(P){const q=P.join(""),ae=new Uint8Array([...q].map(Pe=>this.byte_decoder[Pe]));return this.text_decoder.decode(ae)}decode_chain(P){const q=[];let ae=[];for(const Me of P)this.added_tokens.find(Pe=>Pe.content===Me)!==void 0?(ae.length>0&&(q.push(this.convert_tokens_to_string(ae)),ae=[]),q.push(Me)):ae.push(Me);return ae.length>0&&q.push(this.convert_tokens_to_string(ae)),q}}class pt extends O{constructor(P){super(P),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(P){if(P.length===0)return"";const q=[P[0]];for(let Pe=1;PePe!==this.pad_token).join("");return this.cleanup&&(Me=ie(Me).replaceAll(this.word_delimiter_token," ").trim()),Me}decode_chain(P){return[this.convert_tokens_to_string(P)]}}class It extends O{constructor(P){super(P),this.decoders=P.decoders.map(q=>O.fromConfig(q))}decode_chain(P){return this.decoders.reduce((q,ae)=>ae.decode_chain(q),P)}}class St extends O{constructor(P){super(P),this.suffix=this.config.suffix}decode_chain(P){return P.map((q,ae)=>q.replaceAll(this.suffix,ae===P.length-1?"":" "))}}class Ft extends O{decode_chain(P){let q="";for(let ae=1;aeae.normalize("NFKC")).join("~"):P=P.normalize("NFKC"),P}}class ks extends Fe{constructor(P){super(),this.tokenizers=P.pretokenizers.map(q=>Fe.fromConfig(q))}pre_tokenize_text(P,q){return this.tokenizers.reduce((ae,Me)=>Me.pre_tokenize(ae,q),[P])}}class As extends Fe{constructor(P){super()}pre_tokenize_text(P,q){return P.match(/\w+|[^\w\s]+/g)||[]}}class Qs extends Fe{constructor(P){super()}pre_tokenize_text(P,q){return $(P)}}class ir extends Fe{constructor(P){super(),this.config=P,this.pattern=D(this.config.pattern),this.content=this.config.content}pre_tokenize_text(P,q){return this.pattern===null?[P]:[P.replaceAll(this.pattern,this.config.content)]}}const Yr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Br(xe,P,q,ae){for(const Me of Object.keys(xe)){const Pe=P-xe[Me].length,He=q(Me),ct=new Array(Pe).fill(He);xe[Me]=ae==="right"?(0,L.mergeArrays)(xe[Me],ct):(0,L.mergeArrays)(ct,xe[Me])}}function br(xe,P){for(const q of Object.keys(xe))xe[q].length=P}class Nt extends f.Callable{constructor(q,ae){super();ge(this,"return_token_type_ids",!1);ge(this,"padding_side","right");this._tokenizer_config=ae,this.normalizer=Ue.fromConfig(q.normalizer),this.pre_tokenizer=Fe.fromConfig(q.pre_tokenizer),this.model=le.fromConfig(q.model,ae),this.post_processor=Ne.fromConfig(q.post_processor),this.decoder=O.fromConfig(q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Me of q.added_tokens){const Pe=new Y(Me);this.added_tokens.push(Pe),this.model.tokens_to_ids.set(Pe.content,Pe.id),this.model.vocab[Pe.id]=Pe.content,Pe.special&&(this.special_tokens.push(Pe.content),this.all_special_ids.push(Pe.id))}if(this.additional_special_tokens=ae.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((Me,Pe)=>Pe.content.length-Me.content.length).map(Me=>`${Me.lstrip?"\\s*":""}(${(0,L.escapeRegExp)(Me.content)})${Me.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=ae.model_max_length,this.remove_space=ae.remove_space,this.clean_up_tokenization_spaces=ae.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ae.do_lowercase_and_remove_accent??!1,ae.padding_side&&(this.padding_side=ae.padding_side),this.legacy=!1,this.chat_template=ae.chat_template??null,Array.isArray(this.chat_template)){const Me=Object.create(null);for(const{name:Pe,template:He}of this.chat_template){if(typeof Pe!="string"||typeof He!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Me[Pe]=He}this.chat_template=Me}this._compiled_template_cache=new Map}getToken(...q){for(const ae of q){const Me=this._tokenizer_config[ae];if(Me)if(typeof Me=="object"){if(Me.__type==="AddedToken")return Me.content;throw Error(`Unknown token: ${Me}`)}else return Me}return null}static async from_pretrained(q,{progress_callback:ae=null,config:Me=null,cache_dir:Pe=null,local_files_only:He=!1,revision:ct="main",legacy:yt=null}={}){const ht=await M(q,{progress_callback:ae,config:Me,cache_dir:Pe,local_files_only:He,revision:ct,legacy:yt});return new this(...ht)}_call(q,{text_pair:ae=null,add_special_tokens:Me=!0,padding:Pe=!1,truncation:He=null,max_length:ct=null,return_tensor:yt=!0,return_token_type_ids:ht=null}={}){const it=Array.isArray(q);let Pt;if(it){if(q.length===0)throw Error("text array must be non-empty");if(ae!==null){if(Array.isArray(ae)){if(q.length!==ae.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Pt=q.map((ss,Se)=>this._encode_plus(ss,{text_pair:ae[Se],add_special_tokens:Me,return_token_type_ids:ht}))}else Pt=q.map(ss=>this._encode_plus(ss,{add_special_tokens:Me,return_token_type_ids:ht}))}else{if(q==null)throw Error("text may not be null or undefined");if(Array.isArray(ae))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Pt=[this._encode_plus(q,{text_pair:ae,add_special_tokens:Me,return_token_type_ids:ht})]}if(ct===null?Pe==="max_length"?ct=this.model_max_length:ct=(0,J.max)(Pt.map(ss=>ss.input_ids.length))[0]:He||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),ct=Math.min(ct,this.model_max_length??1/0),Pe||He)for(let ss=0;ssct?He&&br(Pt[ss],ct):Pe&&Br(Pt[ss],ct,Se=>Se==="input_ids"?this.pad_token_id:0,this.padding_side));const hs={};if(yt){if(!(Pe&&He)&&Pt.some(Se=>{var ws;for(const Rs of Object.keys(Se))if(Se[Rs].length!==((ws=Pt[0][Rs])==null?void 0:ws.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const ss=[Pt.length,Pt[0].input_ids.length];for(const Se of Object.keys(Pt[0]))hs[Se]=new U.Tensor("int64",BigInt64Array.from(Pt.flatMap(ws=>ws[Se]).map(BigInt)),ss)}else{for(const ss of Object.keys(Pt[0]))hs[ss]=Pt.map(Se=>Se[ss]);if(!it)for(const ss of Object.keys(hs))hs[ss]=hs[ss][0]}return hs}_encode_text(q){return q===null?null:(this.added_tokens_regex?q.split(this.added_tokens_regex).filter(Pe=>Pe):[q]).map((Pe,He)=>{if(this.added_tokens.find(yt=>yt.content===Pe)!==void 0)return Pe;{if(this.remove_space===!0&&(Pe=Pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Pe=V(Pe)),this.normalizer!==null&&(Pe=this.normalizer(Pe)),Pe.length===0)return[];const yt=this.pre_tokenizer!==null?this.pre_tokenizer(Pe,{section_index:He}):[Pe];return this.model(yt)}}).flat()}_encode_plus(q,{text_pair:ae=null,add_special_tokens:Me=!0,return_token_type_ids:Pe=null}={}){const{tokens:He,token_type_ids:ct}=this._tokenize_helper(q,{pair:ae,add_special_tokens:Me}),yt=this.model.convert_tokens_to_ids(He),ht={input_ids:yt,attention_mask:new Array(yt.length).fill(1)};return(Pe??this.return_token_type_ids)&&ct&&(ht.token_type_ids=ct),ht}_tokenize_helper(q,{pair:ae=null,add_special_tokens:Me=!1}={}){const Pe=this._encode_text(q),He=this._encode_text(ae);return this.post_processor?this.post_processor(Pe,He,{add_special_tokens:Me}):{tokens:(0,L.mergeArrays)(Pe??[],He??[])}}tokenize(q,{pair:ae=null,add_special_tokens:Me=!1}={}){return this._tokenize_helper(q,{pair:ae,add_special_tokens:Me}).tokens}encode(q,{text_pair:ae=null,add_special_tokens:Me=!0,return_token_type_ids:Pe=null}={}){return this._encode_plus(q,{text_pair:ae,add_special_tokens:Me,return_token_type_ids:Pe}).input_ids}batch_decode(q,ae={}){return q instanceof U.Tensor&&(q=q.tolist()),q.map(Me=>this.decode(Me,ae))}decode(q,ae={}){if(q instanceof U.Tensor&&(q=re(q)),!Array.isArray(q)||q.length===0||!(0,L.isIntegralNumber)(q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(q,ae)}decode_single(q,{skip_special_tokens:ae=!1,clean_up_tokenization_spaces:Me=null}){let Pe=this.model.convert_ids_to_tokens(q);ae&&(Pe=Pe.filter(ct=>!this.special_tokens.includes(ct)));let He=this.decoder?this.decoder(Pe):Pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(He=He.replaceAll(this.decoder.end_of_word_suffix," "),ae&&(He=He.trim())),(Me??this.clean_up_tokenization_spaces)&&(He=ie(He)),He}get_chat_template({chat_template:q=null,tools:ae=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const Me=this.chat_template;if(q!==null&&Object.hasOwn(Me,q))q=Me[q];else if(q===null)if(ae!==null&&"tool_use"in Me)q=Me.tool_use;else if("default"in Me)q=Me.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(Me).sort()}.`)}else if(q===null)if(this.chat_template)q=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return q}apply_chat_template(q,{tools:ae=null,documents:Me=null,chat_template:Pe=null,add_generation_prompt:He=!1,tokenize:ct=!0,padding:yt=!1,truncation:ht=!1,max_length:it=null,return_tensor:Pt=!0,return_dict:hs=!1,tokenizer_kwargs:ss={},...Se}={}){if(Pe=this.get_chat_template({chat_template:Pe,tools:ae}),typeof Pe!="string")throw Error(`chat_template must be a string, but got ${typeof Pe}`);let ws=this._compiled_template_cache.get(Pe);ws===void 0&&(ws=new v.Template(Pe),this._compiled_template_cache.set(Pe,ws));const Rs=Object.create(null);for(const Zs of Yr){const Bt=this.getToken(Zs);Bt&&(Rs[Zs]=Bt)}const Js=ws.render({messages:q,add_generation_prompt:He,tools:ae,documents:Me,...Rs,...Se});if(ct){const Zs=this._call(Js,{add_special_tokens:!1,padding:yt,truncation:ht,max_length:it,return_tensor:Pt,...ss});return hs?Zs:Zs.input_ids}return Js}}class Jr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Sr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Rr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class $r extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class ar extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Ar extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class pr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Ir extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Zr extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class lr extends Nt{}class nt extends Nt{}class _t extends Nt{constructor(q,ae){super(q,ae);ge(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ot extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class ls extends Nt{}class vr extends Nt{}class ts extends Nt{}class tr extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(P,q,ae){return sn(this,P,q,ae)}}class Nr extends tr{}class en extends Nt{}class jr extends Nt{}const Tr="▁";class kn extends Nt{constructor(q,ae){super(q,ae);ge(this,"padding_side","left");this.legacy=ae.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:Tr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(q){if(q===null)return null;if(this.legacy||q.length===0)return super._encode_text(q);let ae=super._encode_text(Tr+q.replaceAll(Tr," "));return ae.length>1&&ae[0]===Tr&&this.special_tokens.includes(ae[1])&&(ae=ae.slice(1)),ae}}class Ur extends Nt{}class Sn extends Nt{}class Jn extends Nt{}class Wr extends Nt{}class xr extends Nt{}class ur extends Nt{}class fn extends Nt{}class tn extends Nt{}class gn extends Nt{}function sn(xe,P,q,ae){if(!("language_codes"in xe)||!Array.isArray(xe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in xe)||!(xe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in xe)||typeof xe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Me=ae.src_lang,Pe=ae.tgt_lang;if(!xe.language_codes.includes(Pe))throw new Error(`Target language code "${Pe}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);if(Me!==void 0){if(!xe.language_codes.includes(Me))throw new Error(`Source language code "${Me}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);for(const He of xe.post_processor.config.single)if("SpecialToken"in He&&xe.languageRegex.test(He.SpecialToken.id)){He.SpecialToken.id=xe.lang_to_token(Me);break}}return ae.forced_bos_token_id=xe.model.convert_tokens_to_ids([xe.lang_to_token(Pe)])[0],xe._call(P,q)}class Er extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(P,q,ae){return sn(this,P,q,ae)}}class zt extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)).map(ae=>ae.slice(2,-2)),this.lang_to_token=ae=>`__${ae}__`}_build_translation_inputs(P,q,ae){return sn(this,P,q,ae)}}class wn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(P,{return_timestamps:q=!1,return_language:ae=!1,time_precision:Me=null,force_full_sequences:Pe=!0}={}){if(Me===null)throw Error("Must specify time_precision");let He=null;const ct=q==="word";function yt(){return{language:He,timestamp:[null,null],text:""}}const ht=[];let it=yt(),Pt=0;const hs=this.timestamp_begin,Se=hs+1500;let ws=[],Rs=[],Js=!1,Zs=null;const Bt=new Set(this.all_special_ids);for(const es of P){const _s=es.tokens,vt=ct?es.token_timestamps:null;let ys=null,Pr=hs;if("stride"in es){const[Mt,bs,ze]=es.stride;if(Pt-=bs,Zs=Mt-ze,bs&&(Pr=bs/Me+hs),ze)for(let wt=_s.length-1;wt>=0;--wt){const sr=Number(_s[wt]);if(sr>=hs){if(ys!==null&&(sr-hs)*Me=hs&&bs<=Se){const ze=(bs-hs)*Me+Pt,wt=(0,J.round)(ze,2);if(ys!==null&&bs>=ys)Js=!0;else if(Js||ws.length>0&&bs0?(ws.push(Fs),ct&&Rs.push(qs)):ws.every(Mt=>Mt.length===0)&&(it=yt(),ws=[],Fs=[],Rs=[],qs=[])}if(ws.length>0){if(Pe&&q)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[es,_s]=this.findLongestCommonSequence(ws,Rs),vt=this.decode(es);it.text=vt,ct&&(it.words=this.collateWordTimestamps(es,_s,He)),ht.push(it)}let Ns=Object.create(null);const hr=ht.map(es=>es.text).join("");if(q||ae){for(let es=0;es0;let ct=He?[]:null,yt=He?q[0]:null;for(let ht=1;htbs===Pr[ze]&&yt[hr+ze]<=q[ht][vt+ze]).length:Fs=_s.filter((bs,ze)=>bs===Pr[ze]).length;const qs=Ns/1e4,Mt=Fs/Ns+qs;Fs>1&&Mt>Pt&&(Pt=Mt,hs=[hr,es,vt,ys])}const[Se,ws,Rs,Js]=hs,Zs=Math.floor((ws+Se)/2),Bt=Math.floor((Js+Rs)/2);Pe.push(...ae.slice(0,Zs)),ae=it.slice(Bt),Me=ae.length,He&&(ct.push(...yt.slice(0,Zs)),yt=q[ht].slice(Bt))}return Pe.push(...ae),He?(ct.push(...yt),[Pe,ct]):[Pe,[]]}collateWordTimestamps(P,q,ae){const[Me,Pe,He]=this.combineTokensIntoWords(P,ae),ct=[];for(let yt=0;yt=Me){const ct=((He-Me)*ae).toFixed(2);Pe.push(`<|${ct}|>`),Pe.push([])}else Pe[Pe.length-1].push(He);return Pe=Pe.map(He=>typeof He=="string"?He:super.decode(He,q)),Pe.join("")}splitTokensOnUnicode(P){const q=this.decode(P,{decode_with_timestamps:!0}),ae="�",Me=[],Pe=[],He=[];let ct=[],yt=[],ht=0;for(let it=0;it=this.model.tokens_to_ids.get("<|endoftext|>"),Se=it.startsWith(" "),ws=it.trim(),Rs=yt.test(ws);if(ss||Se||Rs||Pe.length===0)Pe.push(it),He.push(Pt),ct.push(hs);else{const Js=Pe.length-1;Pe[Js]+=it,He[Js].push(...Pt),ct[Js].push(...hs)}}return[Pe,He,ct]}mergePunctuations(P,q,ae,Me,Pe){const He=structuredClone(P),ct=structuredClone(q),yt=structuredClone(ae);let ht=He.length-2,it=He.length-1;for(;ht>=0;)He[ht].startsWith(" ")&&Me.includes(He[ht].trim())?(He[it]=He[ht]+He[it],ct[it]=(0,L.mergeArrays)(ct[ht],ct[it]),yt[it]=(0,L.mergeArrays)(yt[ht],yt[it]),He[ht]="",ct[ht]=[],yt[ht]=[]):it=ht,--ht;for(ht=0,it=1;itPt),ct.filter(Pt=>Pt.length>0),yt.filter(Pt=>Pt.length>0)]}}class $n extends Nt{}class An extends Nt{}class In extends Nt{}class Vr extends Nt{constructor(P,q){super(P,q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ae=>this.languageRegex.test(ae)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(P){if(P===null)return null;const[q,...ae]=P.trim().split(this.languageRegex);if(ae.length===0)return super._encode_text(q);if(ae.length===2){const[Me,Pe]=ae;return this.supported_language_codes.includes(Me)||console.warn(`Unsupported language code "${Me}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,L.mergeArrays)([Me],super._encode_text(Pe))}}}class On extends Nt{}class yn extends Nt{}class Fn extends Nt{}class is extends Nt{}class Ys extends Nt{}class Mn extends Nt{constructor(P,q){super(P,q),this.decoder=new Ft({})}}class Dn extends Nt{}class bn extends Nt{}class vn{static async from_pretrained(P,{progress_callback:q=null,config:ae=null,cache_dir:Me=null,local_files_only:Pe=!1,revision:He="main",legacy:ct=null}={}){var hs;const[yt,ht]=await M(P,{progress_callback:q,config:ae,cache_dir:Me,local_files_only:Pe,revision:He,legacy:ct}),it=((hs=ht.tokenizer_class)==null?void 0:hs.replace(/Fast$/,""))??"PreTrainedTokenizer";let Pt=this.TOKENIZER_CLASS_MAPPING[it];return Pt||(console.warn(`Unknown tokenizer class "${it}", attempting to construct from base class.`),Pt=Nt),new Pt(yt,ht)}}ge(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:ls,DistilBertTokenizer:lr,CamembertTokenizer:nt,DebertaTokenizer:ar,DebertaV2Tokenizer:Ar,BertTokenizer:Jr,HerbertTokenizer:pr,ConvBertTokenizer:Ir,RoFormerTokenizer:Zr,XLMTokenizer:_t,ElectraTokenizer:Ot,MobileBertTokenizer:Rr,SqueezeBertTokenizer:$r,AlbertTokenizer:Sr,GPT2Tokenizer:vr,BartTokenizer:ts,MBartTokenizer:tr,MBart50Tokenizer:Nr,RobertaTokenizer:en,WhisperTokenizer:wn,CodeGenTokenizer:$n,CLIPTokenizer:An,SiglipTokenizer:In,MarianTokenizer:Vr,BloomTokenizer:jr,NllbTokenizer:Er,M2M100Tokenizer:zt,LlamaTokenizer:kn,CodeLlamaTokenizer:Ur,XLMRobertaTokenizer:Sn,MPNetTokenizer:Jn,FalconTokenizer:Wr,GPTNeoXTokenizer:xr,EsmTokenizer:ur,Wav2Vec2CTCTokenizer:On,BlenderbotTokenizer:yn,BlenderbotSmallTokenizer:Fn,SpeechT5Tokenizer:is,NougatTokenizer:Ys,VitsTokenizer:Mn,Qwen2Tokenizer:fn,GemmaTokenizer:tn,Grok1Tokenizer:gn,CohereTokenizer:Dn,MgpstrTokenizer:bn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(De,A,r)=>{r.r(A),r.d(A,{hamming:()=>y,hanning:()=>v,mel_filter_bank:()=>z,read_audio:()=>U,spectrogram:()=>g,window_function:()=>C});var f=r("./src/utils/hub.js"),L=r("./src/utils/maths.js"),N=r("./src/utils/core.js"),J=r("./src/utils/tensor.js");async function U(T,ee){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const Y=await(await(0,f.getFile)(T)).arrayBuffer(),le=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${le.sampleRate}Hz.`);const de=await le.decodeAudioData(Y);let fe;if(de.numberOfChannels===2){const Ce=Math.sqrt(2),Te=de.getChannelData(0),Le=de.getChannelData(1);fe=new Float32Array(Te.length);for(let qe=0;qe2595*Math.log10(1+T/700),kaldi:T=>1127*Math.log(1+T/700),slaney:(T,ee=1e3,Y=15,le=27/Math.log(6.4))=>T>=ee?Y+Math.log(T/ee)*le:3*T/200};function b(T,ee="htk"){const Y=M[ee];if(!Y)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?Y(T):T.map(le=>Y(le))}const D={htk:T=>700*(10**(T/2595)-1),kaldi:T=>700*(Math.exp(T/1127)-1),slaney:(T,ee=1e3,Y=15,le=Math.log(6.4)/27)=>T>=Y?ee*Math.exp(le*(T-Y)):200*T/3};function H(T,ee="htk"){const Y=D[ee];if(!Y)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?Y(T):T.map(le=>Y(le))}function re(T,ee){const Y=Float64Array.from({length:ee.length-1},(Ce,Te)=>ee[Te+1]-ee[Te]),le=Array.from({length:T.length},()=>new Array(ee.length));for(let Ce=0;Cenew Array(T.length));for(let Ce=0;CeT+le*fe)}function z(T,ee,Y,le,de,fe=null,Ce="htk",Te=!1){if(fe!==null&&fe!=="slaney")throw new Error('norm must be one of null or "slaney"');const Le=b(Y,Ce),qe=b(le,Ce),Ue=ie(Le,qe,ee+2);let ut=H(Ue,Ce),ue;if(Te){const he=de/(T*2);ue=b(Float64Array.from({length:T},(Ee,Be)=>Be*he),Ce),ut=Ue}else ue=ie(0,Math.floor(de/2),T);const se=re(ue,ut);if(fe!==null&&fe==="slaney")for(let he=0;hede)throw Error(`frame_length (${Y}) may not be larger than fft_length (${de})`);if(Fe!==Y)throw new Error(`Length of the window (${Fe}) must equal frame_length (${Y})`);if(le<=0)throw new Error("hop_length must be greater than zero");if(fe===null&&Ue!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(Ce){if(Te!=="reflect")throw new Error(`pad_mode="${Te}" not implemented yet.`);const O=Math.floor((de-1)/2)+1;T=V(T,O,O)}let ce=Math.floor(1+Math.floor((T.length-Y)/le));et!==null&&cece?oe&&(je=Xe):je=Re=Xe);const Ve=new L.FFT(de),Ne=new Float64Array(de),Ze=new Float64Array(Ve.outputBufferSize),at=new Float32Array(ve*je);for(let O=0;O=1;--pe)Ne[pe]-=qe*Ne[pe-1];Ne[0]*=1-qe}for(let pe=0;peMath.pow(Te,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(Y&&(Ce=Ce.subarray(0,T)),le===null)return Ce;if(T>le)throw new Error(`Length of the window (${T}) may not be larger than frame_length (${le})`);return Ce}},"./src/utils/constants.js":(De,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>w,CONFIG_NAME:()=>L,FEATURE_EXTRACTOR_NAME:()=>N,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>f,IMAGE_PROCESSOR_NAME:()=>J,PROCESSOR_NAME:()=>U});const f="https://github.com/huggingface/transformers.js/issues/new/choose",L="config.json",N="preprocessor_config.json",J=N,U="processor_config.json",w="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(De,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>v,calculateReflectOffset:()=>D,count:()=>ie,dispatchCallback:()=>f,escapeRegExp:()=>N,isIntegralNumber:()=>U,isNullishDimension:()=>w,isTypedArray:()=>J,len:()=>re,mergeArrays:()=>M,pick:()=>H,pop:()=>y,product:()=>b,reverseDictionary:()=>L});function f(z,V){z&&z(V)}function L(z){return Object.fromEntries(Object.entries(z).map(([V,Q])=>[Q,V]))}function N(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(z){var V,Q,F;return((F=(Q=(V=z==null?void 0:z.prototype)==null?void 0:V.__proto__)==null?void 0:Q.constructor)==null?void 0:F.name)==="TypedArray"}function U(z){return Number.isInteger(z)||typeof z=="bigint"}function w(z){return z==null||z===-1}function v(z){const V=[];let Q=z;for(;Array.isArray(Q);)V.push(Q.length),Q=Q[0];return V}function y(z,V,Q=void 0){const F=z[V];if(F!==void 0)return delete z[V],F;if(Q===void 0)throw Error(`Key ${V} does not exist in object.`);return Q}function M(...z){return Array.prototype.concat.apply([],z)}function b(...z){return z.reduce((V,Q)=>V.flatMap(F=>Q.map($=>[F,$])))}function D(z,V){return Math.abs((z+V)%(2*V)-V)}function H(z,V){return Object.assign({},...V.map(Q=>{if(z[Q]!==void 0)return{[Q]:z[Q]}}))}function re(z){let V=0;for(const Q of z)++V;return V}function ie(z,V){let Q=0;for(const F of z)F===V&&++Q;return Q}},"./src/utils/data-structures.js":(De,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>L,PriorityQueue:()=>f,TokenLattice:()=>J});class f{constructor(v=(M,b)=>M>b,y=1/0){this._heap=[],this._comparator=v,this._maxSize=y}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...v){return this.extend(v)}extend(v){for(const y of v)if(this.size0&&this._swap(0,y),this._heap.pop(),this._siftDown(),v}replace(v){const y=this.peek();return this._heap[0]=v,this._siftDown(),y}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,y){return this._comparator(this._heap[v],this._heap[y])}_swap(v,y){const M=this._heap[v];this._heap[v]=this._heap[y],this._heap[y]=M}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(v){for(;v>0&&this._greater(v,this._parent(v));)this._swap(v,this._parent(v)),v=this._parent(v)}_siftDown(){let v=0;for(;this._left(v)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const b=new U(this.bosTokenId,0,0,0,0),D=new U(this.eosTokenId,1,this.len,0,0);this.nodes.push(b.clone()),this.nodes.push(D.clone()),this.beginNodes[this.len].push(D),this.endNodes[0].push(b)}insert(v,y,M,b){const D=this.nodes.length,H=new U(b,D,v,y,M);this.beginNodes[v].push(H),this.endNodes[v+y].push(H),this.nodes.push(H)}viterbi(){const v=this.len;let y=0;for(;y<=v;){if(this.beginNodes[y].length==0)return[];for(let re of this.beginNodes[y]){re.prev=null;let ie=0,z=null;for(let V of this.endNodes[y]){const Q=V.backtraceScore+re.score;(z===null||Q>ie)&&(z=V.clone(),ie=Q)}if(z!==null)re.prev=z,re.backtraceScore=ie;else return[]}++y}const M=[],D=this.beginNodes[v][0].prev;if(D===null)return[];let H=D.clone();for(;H.prev!==null;)M.push(H.clone()),H=H.clone().prev.clone();return M.reverse(),M}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(y=>this.piece(y))}tokenIds(){return this.viterbi().map(y=>y.tokenId)}}class U{constructor(v,y,M,b,D){this.tokenId=v,this.nodeId=y,this.pos=M,this.length=b,this.score=D,this.prev=null,this.backtraceScore=0}clone(){const v=new U(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(De,A,r)=>{r.r(A),r.d(A,{DEVICE_TYPES:()=>f});const f=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(De,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>J,DEFAULT_DEVICE_DTYPE_MAPPING:()=>U,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>w,isWebGpuFp16Supported:()=>N});var f=r("./src/env.js"),L=r("./src/utils/devices.js");const N=function(){let v;return async function(){if(v===void 0)if(!f.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),J=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),U=Object.freeze({[L.DEVICE_TYPES.wasm]:J.q8}),w=Object.freeze({[J.fp32]:"",[J.fp16]:"_fp16",[J.int8]:"_int8",[J.uint8]:"_uint8",[J.q8]:"_quantized",[J.q4]:"_q4",[J.q4f16]:"_q4f16",[J.bnb4]:"_bnb4"})},"./src/utils/generic.js":(De,A,r)=>{r.r(A),r.d(A,{Callable:()=>f});const f=class{constructor(){let L=function(...N){return L._call(...N)};return Object.setPrototypeOf(L,new.target.prototype)}_call(...L){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(De,A,r)=>{r.r(A),r.d(A,{getFile:()=>y,getModelFile:()=>re,getModelJSON:()=>ie});var f=r("?7a2c"),L=r("?a42a"),N=r("./src/env.js"),J=r("./src/utils/core.js");const U={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class w{constructor(F){if(this.filePath=F,this.headers=new Headers,this.exists=f.existsSync(F),this.exists){this.status=200,this.statusText="OK";let $=f.statSync(F);this.headers.set("content-length",$.size.toString()),this.updateContentType();let g=this;this.body=new ReadableStream({start(C){g.arrayBuffer().then(T=>{C.enqueue(new Uint8Array(T)),C.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const F=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",U[F]??"application/octet-stream")}clone(){let F=new w(this.filePath);return F.exists=this.exists,F.status=this.status,F.statusText=this.statusText,F.headers=new Headers(this.headers),F}async arrayBuffer(){return(await f.promises.readFile(this.filePath)).buffer}async blob(){const F=await f.promises.readFile(this.filePath);return new Blob([F],{type:this.headers.get("content-type")})}async text(){return await f.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(Q,F=null,$=null){let g;try{g=new URL(Q)}catch{return!1}return!(F&&!F.includes(g.protocol)||$&&!$.includes(g.hostname))}async function y(Q){var F;if(N.env.useFS&&!v(Q,["http:","https:","blob:"]))return new w(Q);if(typeof process<"u"&&((F=process==null?void 0:process.release)==null?void 0:F.name)==="node"){const $=!!(or!=null&&or.TESTING_REMOTELY),g=N.env.version,C=new Headers;if(C.set("User-Agent",`transformers.js/${g}; is_ci/${$};`),v(Q,["http:","https:"],["huggingface.co","hf.co"])){const ee=(or==null?void 0:or.HF_TOKEN)??(or==null?void 0:or.HF_ACCESS_TOKEN);ee&&C.set("Authorization",`Bearer ${ee}`)}return fetch(Q,{headers:C})}else return fetch(Q)}const M={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function b(Q,F,$){if(!$)return null;const g=M[Q]??`Error (${Q}) occurred while trying to load file`;throw Error(`${g}: "${F}".`)}class D{constructor(F){this.path=F}async match(F){let $=L.join(this.path,F),g=new w($);if(g.exists)return g}async put(F,$){const g=Buffer.from(await $.arrayBuffer());let C=L.join(this.path,F);try{await f.promises.mkdir(L.dirname(C),{recursive:!0}),await f.promises.writeFile(C,g)}catch(T){console.warn("An error occurred while writing the file to cache:",T)}}}async function H(Q,...F){for(let $ of F)try{let g=await Q.match($);if(g)return g}catch{continue}}async function re(Q,F,$=!0,g={}){if(!N.env.allowLocalModels){if(g.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!N.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,J.dispatchCallback)(g.progress_callback,{status:"initiate",name:Q,file:F});let C;if(!C&&N.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{C=await caches.open("transformers-cache")}catch(ut){console.warn("An error occurred while opening the browser cache:",ut)}}if(!C&&N.env.useFSCache&&(C=new D(g.cache_dir??N.env.cacheDir)),!C&&N.env.useCustomCache){if(!N.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!N.env.customCache.match||!N.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");C=N.env.customCache}const T=g.revision??"main";let ee=V(Q,F),Y=V(N.env.localModelPath,ee),le=V(N.env.remoteHost,N.env.remotePathTemplate.replaceAll("{model}",Q).replaceAll("{revision}",encodeURIComponent(T)),F),de=T==="main"?ee:V(Q,T,F),fe,Ce=C instanceof D?de:le,Te=!1,Le;C&&(Le=await H(C,Y,Ce));const qe=Le!==void 0;if(Le===void 0){if(N.env.allowLocalModels)if(v(ee,["http:","https:"])){if(g.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ee}.`);if(!N.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ee}.`)}else try{Le=await y(Y),fe=Y}catch(ue){console.warn(`Unable to load from local path "${Y}": "${ue}"`)}if(Le===void 0||Le.status===404){if(g.local_files_only||!N.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Y}".`);return null}if(Le=await y(le),Le.status!==200)return b(Le.status,le,$);fe=Ce}Te=C&&typeof Response<"u"&&Le instanceof Response&&Le.status===200}(0,J.dispatchCallback)(g.progress_callback,{status:"download",name:Q,file:F});let Ue;return g.progress_callback?qe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ue=new Uint8Array(await Le.arrayBuffer()),(0,J.dispatchCallback)(g.progress_callback,{status:"progress",name:Q,file:F,progress:100,loaded:Ue.length,total:Ue.length})):Ue=await z(Le,ut=>{(0,J.dispatchCallback)(g.progress_callback,{status:"progress",name:Q,file:F,...ut})}):Ue=new Uint8Array(await Le.arrayBuffer()),Te&&fe&&await C.match(fe)===void 0&&await C.put(fe,new Response(Ue,{headers:Le.headers})).catch(ut=>{console.warn(`Unable to add response to browser cache: ${ut}.`)}),(0,J.dispatchCallback)(g.progress_callback,{status:"done",name:Q,file:F}),Ue}async function ie(Q,F,$=!0,g={}){let C=await re(Q,F,$,g);if(C===null)return{};let ee=new TextDecoder("utf-8").decode(C);return JSON.parse(ee)}async function z(Q,F){const $=Q.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let g=parseInt($??"0"),C=new Uint8Array(g),T=0;const ee=Q.body.getReader();async function Y(){const{done:le,value:de}=await ee.read();if(le)return;let fe=T+de.length;if(fe>g){g=fe;let Te=new Uint8Array(g);Te.set(C),C=Te}C.set(de,T),T=fe;const Ce=T/g*100;return F({progress:Ce,loaded:T,total:g}),Y()}return await Y(),C}function V(...Q){return Q=Q.map((F,$)=>($&&(F=F.replace(new RegExp("^/"),"")),$!==Q.length-1&&(F=F.replace(new RegExp("/$"),"")),F)),Q.join("/")}},"./src/utils/image.js":(De,A,r)=>{r.r(A),r.d(A,{RawImage:()=>H,load_image:()=>re});var f=r("./src/utils/core.js"),L=r("./src/utils/hub.js"),N=r("./src/env.js"),J=r("./src/utils/tensor.js"),U=r("?2b25");let w,v,y;const M=N.apis.IS_BROWSER_ENV||N.apis.IS_WEBWORKER_ENV;if(M)w=(ie,z)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ie,z)},y=self.createImageBitmap,v=self.ImageData;else if(U)y=async ie=>{const V=(await ie.metadata()).channels,{data:Q,info:F}=await ie.rotate().raw().toBuffer({resolveWithObject:!0}),$=new H(new Uint8ClampedArray(Q),F.width,F.height,F.channels);return V!==void 0&&V!==F.channels&&$.convert(V),$};else throw new Error("Unable to load image processing library.");const b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},D=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class H{constructor(z,V,Q,F){this.data=z,this.width=V,this.height=Q,this.channels=F}get size(){return[this.width,this.height]}static async read(z){if(z instanceof H)return z;if(typeof z=="string"||z instanceof URL)return await this.fromURL(z);throw new Error(`Unsupported input type: ${typeof z}`)}static fromCanvas(z){if(!M)throw new Error("fromCanvas() is only supported in browser environments.");const Q=z.getContext("2d").getImageData(0,0,z.width,z.height).data;return new H(Q,z.width,z.height,4)}static async fromURL(z){const V=await(0,L.getFile)(z);if(V.status!==200)throw new Error(`Unable to read image from "${z}" (${V.status} ${V.statusText})`);const Q=await V.blob();return this.fromBlob(Q)}static async fromBlob(z){if(M){const V=await y(z),Q=w(V.width,V.height).getContext("2d");return Q.drawImage(V,0,0),new this(Q.getImageData(0,0,V.width,V.height).data,V.width,V.height,4)}else{const V=U(await z.arrayBuffer());return await y(V)}}static fromTensor(z,V="CHW"){if(z.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${z.dims.length} dimensions.`);if(V==="CHW")z=z.transpose(1,2,0);else if(V!=="HWC")throw new Error(`Unsupported channel format: ${V}`);if(!(z.data instanceof Uint8ClampedArray||z.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${z.type}`);switch(z.dims[2]){case 1:case 2:case 3:case 4:return new H(z.data,z.dims[1],z.dims[0],z.dims[2]);default:throw new Error(`Unsupported number of channels: ${z.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const z=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let V=0,Q=0;V=0?T=Q:Y=-Q,F>=0?ee=F:le=-F,C.drawImage(g,T,ee,z,V,Y,le,z,V),new H(C.getImageData(0,0,z,V).data,z,V,4).convert($)}else{let $=this.toSharp();if(Q>=0&&F>=0)$=$.extract({left:Math.floor(Q),top:Math.floor(F),width:z,height:V});else if(Q<=0&&F<=0){const g=Math.floor(-F),C=Math.floor(-Q);$=$.extend({top:g,left:C,right:z-this.width-C,bottom:V-this.height-g})}else{let g=[0,0],C=0;F<0?(g[0]=Math.floor(-F),g[1]=V-this.height-g[0]):C=Math.floor(F);let T=[0,0],ee=0;Q<0?(T[0]=Math.floor(-Q),T[1]=z-this.width-T[0]):ee=Math.floor(Q),$=$.extend({top:g[0],bottom:g[1],left:T[0],right:T[1]}).extract({left:ee,top:C,width:z,height:V})}return await y($)}}async toBlob(z="image/png",V=1){if(!M)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:z,quality:V})}toTensor(z="CHW"){let V=new J.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(z!=="HWC")if(z==="CHW")V=V.permute(2,0,1);else throw new Error(`Unsupported channel format: ${z}`);return V}toCanvas(){if(!M)throw new Error("toCanvas() is only supported in browser environments.");const z=this.clone().rgba(),V=w(z.width,z.height),Q=new v(z.data,z.width,z.height);return V.getContext("2d").putImageData(Q,0,0),V}split(){const{data:z,width:V,height:Q,channels:F}=this,$=z.constructor,g=z.length/F,C=Array.from({length:F},()=>new $(g));for(let T=0;Tnew H(T,V,Q,1))}_update(z,V,Q,F=null){return this.data=z,this.width=V,this.height=Q,F!==null&&(this.channels=F),this}clone(){return new H(this.data.slice(),this.width,this.height,this.channels)}convert(z){if(this.channels===z)return this;switch(z){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(z){if(M){if(N.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const V=z.split(".").pop().toLowerCase(),Q=D.get(V)??"image/png",F=await this.toBlob(Q),$=URL.createObjectURL(F),g=document.createElement("a");g.href=$,g.download=z,g.click(),g.remove()}else{if(N.env.useFS)return await this.toSharp().toFile(z);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(M)throw new Error("toSharp() is only supported in server-side environments.");return U(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const re=H.read.bind(H)},"./src/utils/maths.js":(De,A,r)=>{r.r(A),r.d(A,{FFT:()=>re,bankers_round:()=>V,cos_sim:()=>w,dot:()=>U,dynamic_time_warping:()=>Q,interpolate_data:()=>f,log_softmax:()=>J,magnitude:()=>v,max:()=>M,medianFilter:()=>ie,min:()=>y,permute_data:()=>L,round:()=>z,softmax:()=>N});function f(F,[$,g,C],[T,ee],Y="bilinear",le=!1){const de=ee/C,fe=T/g,Ce=new F.constructor(T*ee*$),Te=g*C,Le=T*ee;for(let qe=0;qe=0;--le)T[le]=de,C[le]=$[g[le]],de*=C[le];const ee=g.map((le,de)=>T[g.indexOf(de)]),Y=new F.constructor(F.length);for(let le=0;le=0;--fe)de+=Ce%$[fe]*ee[fe],Ce=Math.floor(Ce/$[fe]);Y[de]=F[le]}return[Y,C]}function N(F){const $=M(F)[0],g=F.map(ee=>Math.exp(ee-$)),C=g.reduce((ee,Y)=>ee+Y,0);return g.map(ee=>ee/C)}function J(F){const $=M(F)[0];let g=0;for(let ee=0;eeee-$-C)}function U(F,$){let g=0;for(let C=0;C$+g*g,0))}function y(F){if(F.length===0)throw Error("Array must not be empty");let $=F[0],g=0;for(let C=1;C$&&($=F[C],g=C);return[Number($),g]}function b(F){return F>0&&(F&F-1)===0}class D{constructor($){if(this.size=$|0,this.size<=1||!b(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=$<<1,this.table=new Float64Array(this.size*2);for(let C=0;CC;C<<=1)++g;this._width=g%2===0?g-1:g,this._bitrev=new Int32Array(1<>>T&3)<>>1);for(let T=0;T<$.length;T+=2)C[T>>>1]=$[T];return C}toComplexArray($,g){const C=g||this.createComplexArray();for(let T=0;T>>1],C[T+1]=0;return C}transform($,g){if($===g)throw new Error("Input and output buffers must be different");this._transform4($,g,1)}realTransform($,g){if($===g)throw new Error("Input and output buffers must be different");this._realTransform4($,g,1)}inverseTransform($,g){if($===g)throw new Error("Input and output buffers must be different");this._transform4($,g,-1);for(let C=0;C<$.length;++C)$[C]/=this.size}_transform4($,g,C){const T=this._csize;let Y=1<>=2;Y>=2;Y>>=2){le=T/Y<<1;const Le=le>>>2;for(de=0;de>>1,Y>>>1)}else for(de=0,fe=0;de>>1,Y>>>1,C)}const Te=this.table;for(Y>>=2;Y>=2;Y>>=2){le=T/Y<<1;const qe=le>>>1,Ue=qe>>>1,ut=Ue>>>1;for(de=0;de>>1;for(let qe=2;qe>1;++Ce){const Te=(Ce+1-$)**2/2,Le=Math.sqrt(de**2+fe**2)**Te,qe=Te*Math.atan2(fe,de),Ue=2*Ce;ee[Ue]=Le*Math.cos(qe),ee[Ue+1]=Le*Math.sin(qe),Y[Ue]=ee[Ue],Y[Ue+1]=-ee[Ue+1]}this._slicedChirpBuffer=ee.subarray(g,C),this._f=new D(T>>1),this._f.transform(this._chirpBuffer,Y)}_transform($,g,C){const T=this._buffer1,ee=this._buffer2,Y=this._outBuffer1,le=this._outBuffer2,de=this._chirpBuffer,fe=this._slicedChirpBuffer,Ce=this._a;if(C)for(let Te=0;Te>1,Ue=g[qe];T[Te]=Ue*fe[Te],T[Le]=Ue*fe[Le]}else for(let Te=0;Te=F.length&&(de=2*(F.length-1)-de),C[Y++]=F[de]}C.sort(),g[ee]=C[T]}return g}function z(F,$){const g=Math.pow(10,$);return Math.round(F*g)/g}function V(F){const $=Math.round(F);return Math.abs(F)%1===.5?$%2===0?$:$-1:$}function Q(F){const $=F.length,g=F[0].length,C=[$+1,g+1],T=Array.from({length:C[0]},()=>Array(C[1]).fill(1/0));T[0][0]=0;const ee=Array.from({length:C[0]},()=>Array(C[1]).fill(-1));for(let Ce=1;Ce0||le>0;)switch(de.push(Y-1),fe.push(le-1),ee[Y][le]){case 0:--Y,--le;break;case 1:--Y;break;case 2:--le;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${Y}, ${le}]. Please file a bug report.`)}return de.reverse(),fe.reverse(),[de,fe]}},"./src/utils/tensor.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>U,cat:()=>g,full:()=>de,full_like:()=>fe,interpolate:()=>y,interpolate_4d:()=>M,layer_norm:()=>V,matmul:()=>b,mean:()=>ee,mean_pooling:()=>z,ones:()=>Ce,ones_like:()=>Te,permute:()=>v,quantize_embeddings:()=>ut,rand:()=>Ue,rfft:()=>D,slice:()=>ie,stack:()=>C,std_mean:()=>T,topk:()=>H,zeros:()=>Le,zeros_like:()=>qe});var f=r("./src/utils/maths.js"),L=r("./src/backends/onnx.js"),N=r("./src/ops/registry.js");const J=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class U{constructor(...se){ge(this,"ort_tensor");return(0,L.isONNXTensor)(se[0])?this.ort_tensor=se[0]:this.ort_tensor=new L.Tensor(se[0],se[1],se[2]),new Proxy(this,{get:(he,Ee)=>{if(typeof Ee=="string"){let Be=Number(Ee);if(Number.isInteger(Be))return he._getitem(Be)}return he[Ee]},set:(he,Ee,Be)=>he[Ee]=Be})}get dims(){return this.ort_tensor.dims}set dims(se){this.ort_tensor.dims=se}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[se,...he]=this.dims;if(he.length>0){const Ee=he.reduce((Be,et)=>Be*et);for(let Be=0;Be0){const Be=Ee.reduce((et,Xe)=>et*Xe);return this._subarray(se,Be,Ee)}else return new U(this.type,[this.data[se]],Ee)}indexOf(se){const he=this.data;for(let Ee=0;EeRe)throw new Error(`Invalid slice: ${ce}`);const je=[Math.max(ve,0),Math.min(Re,this.dims[Fe])];Ee.push(je),he.push(je[1]-je[0])}else throw new Error(`Invalid slice: ${ce}`)}const Be=Ee.map(([Fe,ce])=>ce-Fe),et=Be.reduce((Fe,ce)=>Fe*ce),Xe=this.data,oe=new Xe.constructor(et),Je=this.stride();for(let Fe=0;Fe=0;--ve){const je=Be[ve];ce+=(Re%je+Ee[ve][0])*Je[ve],Re=Math.floor(Re/je)}oe[Fe]=Xe[ce]}return new U(this.type,oe,he)}permute(...se){return v(this,se)}transpose(...se){return this.permute(...se)}sum(se=null,he=!1){return this.norm(1,se,he)}norm(se="fro",he=null,Ee=!1){if(se==="fro")se=2;else if(typeof se=="string")throw Error(`Unsupported norm: ${se}`);const Be=this.data;if(he===null){let oe=Be.reduce((Je,Fe)=>Je+Fe**se,0)**(1/se);return new U(this.type,[oe],[])}he=$(he,this.dims.length);const et=this.dims.slice();et[he]=1;const Xe=new Be.constructor(Be.length/this.dims[he]);for(let oe=0;oe=0;--Fe){const Re=this.dims[Fe];if(Fe!==he){const je=ce%Re;Je+=je*ve,ve*=et[Fe]}ce=Math.floor(ce/Re)}Xe[Je]+=Be[oe]**se}if(se!==1)for(let oe=0;oe=0;--Je){const ve=this.dims[Je];if(Je!==he){const Re=Fe%ve;oe+=Re*ce,ce*=this.dims[Je]}Fe=Math.floor(Fe/ve)}Be[Xe]/=et[oe]}return this}normalize(se=2,he=1){return this.clone().normalize_(se,he)}stride(){return Y(this.dims)}squeeze(se=null){return new U(this.type,this.data,Q(this.dims,se))}squeeze_(se=null){return this.dims=Q(this.dims,se),this}unsqueeze(se=null){return new U(this.type,this.data,F(this.dims,se))}unsqueeze_(se=null){return this.dims=F(this.dims,se),this}flatten_(se=0,he=-1){he=(he+this.dims.length)%this.dims.length;let Ee=this.dims.slice(0,se),Be=this.dims.slice(se,he+1),et=this.dims.slice(he+1);return this.dims=[...Ee,Be.reduce((Xe,oe)=>Xe*oe,1),...et],this}flatten(se=0,he=-1){return this.clone().flatten_(se,he)}view(...se){let he=-1;for(let Be=0;Beoe!==he?et*Xe:et,1);se[he]=Ee.length/Be}return new U(this.type,Ee,se)}neg_(){const se=this.data;for(let he=0;heet*Xe);if(he!==Ee)throw Error(`cannot reshape array of size ${he} into shape (${se})`);let Be=ue;for(let et=se.length-1;et>=0;et--)Be=Be.reduce((Xe,oe)=>{let Je=Xe[Xe.length-1];return Je.lengthnew U("int64",ue,[ue.length]);async function ie(ue,se,he,Ee,Be){return await(await N.TensorOpRegistry.slice)({x:ue,s:re(se),e:re(he),a:re(Ee),t:re(Be??new Array(Ee.length).fill(1))})}function z(ue,se){const he=ue.data,Ee=se.data,Be=[ue.dims[0],ue.dims[2]],et=new he.constructor(Be[0]*Be[1]),[Xe,oe,Je]=ue.dims;let Fe=0;for(let ce=0;cehe!==1):typeof se=="number"?ue[se]===1&&ue.splice(se,1):Array.isArray(se)&&(ue=ue.filter((he,Ee)=>he!==1||!se.includes(Ee))),ue}function F(ue,se){return se=$(se,ue.length+1),ue=ue.slice(),ue.splice(se,0,1),ue}function $(ue,se,he=null,Ee=!0){if(Ee&&(ue<-se||ue>=se))throw new Error(`IndexError: index ${ue} is out of bounds for dimension${he===null?"":" "+he} with size ${se}`);return ue<0&&(ue=(ue%se+se)%se),ue}function g(ue,se=0){se=$(se,ue[0].dims.length);const he=ue[0].dims.slice();he[se]=ue.reduce((Xe,oe)=>Xe+oe.dims[se],0);const Ee=he.reduce((Xe,oe)=>Xe*oe,1),Be=new ue[0].data.constructor(Ee),et=ue[0].type;if(se===0){let Xe=0;for(const oe of ue){const Je=oe.data;Be.set(Je,Xe),Xe+=Je.length}}else{let Xe=0;for(let oe=0;oe=0;--Re){const Ne=Fe[Re];let Ze=je%Ne;Re===se&&(Ze+=Xe),ve+=Ze*Ve,Ve*=he[Re],je=Math.floor(je/Ne)}Be[ve]=Je[ce]}Xe+=Fe[se]}}return new U(et,Be,he)}function C(ue,se=0){return g(ue.map(he=>he.unsqueeze(se)),se)}function T(ue,se=null,he=1,Ee=!1){const Be=ue.data,et=ue.dims;if(se===null){const Re=Be.reduce((Ze,at)=>Ze+at,0)/Be.length,je=Math.sqrt(Be.reduce((Ze,at)=>Ze+(at-Re)**2,0)/(Be.length-he)),Ve=new U(ue.type,[Re],[]);return[new U(ue.type,[je],[]),Ve]}se=$(se,et.length);const Xe=ee(ue,se,Ee),oe=Xe.data,Je=et.slice();Je[se]=1;const Fe=new Be.constructor(Be.length/et[se]);for(let ve=0;ve=0;--je){const Ze=et[je];if(je!==se){const at=Ve%Ze;Re+=at*Ne,Ne*=Je[je]}Ve=Math.floor(Ve/Ze)}Fe[Re]+=(Be[ve]-oe[Re])**2}for(let ve=0;veJe+Fe,0);return new U(ue.type,[oe/Ee.length],[])}const Be=ue.dims;se=$(se,Be.length);const et=Be.slice();et[se]=1;const Xe=new Ee.constructor(Ee.length/Be[se]);for(let oe=0;oe=0;--Fe){const Re=Be[Fe];if(Fe!==se){const je=ce%Re;Je+=je*ve,ve*=et[Fe]}ce=Math.floor(ce/Re)}Xe[Je]+=Ee[oe]}if(Be[se]!==1)for(let oe=0;oe=0;--he)se[he]=Ee,Ee*=ue[he];return se}function le(ue,se,he,Ee){const Be=ue.reduce((et,Xe)=>et*Xe,1);return new U(he,new Ee(Be).fill(se),ue)}function de(ue,se){let he,Ee;if(typeof se=="number")he="float32",Ee=Float32Array;else if(typeof se=="bigint")he="int64",Ee=BigInt64Array;else if(typeof se=="boolean")he="bool",Ee=Uint8Array;else throw new Error(`Unsupported data type: ${typeof se}`);return le(ue,se,he,Ee)}function fe(ue,se){return de(ue.dims,se)}function Ce(ue){return le(ue,1n,"int64",BigInt64Array)}function Te(ue){return Ce(ue.dims)}function Le(ue){return le(ue,0n,"int64",BigInt64Array)}function qe(ue){return Le(ue.dims)}function Ue(ue){const se=ue.reduce((he,Ee)=>he*Ee,1);return new U("float32",Float32Array.from({length:se},()=>Math.random()),ue)}function ut(ue,se){if(ue.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ue.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(se))throw new Error("The precision must be either 'binary' or 'ubinary'");const he=se==="binary",Ee=he?"int8":"uint8",Be=he?Int8Array:Uint8Array,et=ue.data,Xe=new Be(et.length/8);for(let oe=0;oe0?1:0,Fe=Math.floor(oe/8),ce=oe%8;Xe[Fe]|=Je<<7-ce,he&&ce===0&&(Xe[Fe]-=128)}return new U(Ee,Xe,[ue.dims[0],ue.dims[1]/8])}}},Yn={};function ms(De){var A=Yn[De];if(A!==void 0)return A.exports;var r=Yn[De]={exports:{}};return Qr[De](r,r.exports,ms),r.exports}ms.m=Qr,(()=>{var De=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;ms.t=function(r,f){if(f&1&&(r=this(r)),f&8||typeof r=="object"&&r&&(f&4&&r.__esModule||f&16&&typeof r.then=="function"))return r;var L=Object.create(null);ms.r(L);var N={};A=A||[null,De({}),De([]),De(De)];for(var J=f&2&&r;typeof J=="object"&&!~A.indexOf(J);J=De(J))Object.getOwnPropertyNames(J).forEach(U=>N[U]=()=>r[U]);return N.default=()=>r,ms.d(L,N),L}})(),ms.d=(De,A)=>{for(var r in A)ms.o(A,r)&&!ms.o(De,r)&&Object.defineProperty(De,r,{enumerable:!0,get:A[r]})},ms.o=(De,A)=>Object.prototype.hasOwnProperty.call(De,A),ms.r=De=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(De,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(De,"__esModule",{value:!0})},(()=>{var De;if(typeof self.location.href=="string"&&(De=self.location.href),!De)throw new Error("Automatic publicPath is not supported in this browser");De=De.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),ms.p=De})(),ms.b=new URL("./",self.location.href);var c={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/ms.r(c),ms.d(c,{ASTFeatureExtractor:()=>y.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>f.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>L.AutoConfig,AutoFeatureExtractor:()=>M.AutoFeatureExtractor,AutoImageProcessor:()=>H.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>z.AutoProcessor,AutoTokenizer:()=>f.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>f.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>V.BaseStreamer,BeitFeatureExtractor:()=>D.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>f.BertTokenizer,BitImageProcessor:()=>D.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>f.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>f.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>f.BloomTokenizer,CLIPFeatureExtractor:()=>D.CLIPFeatureExtractor,CLIPImageProcessor:()=>D.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>f.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>f.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>D.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>y.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>F.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>f.CodeGenTokenizer,CodeLlamaTokenizer:()=>f.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>f.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>f.ConvBertTokenizer,ConvNextFeatureExtractor:()=>D.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>D.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>D.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>D.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>f.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>f.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>D.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>D.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>D.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>D.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>f.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>D.DonutFeatureExtractor,DonutImageProcessor:()=>D.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>D.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>f.ElectraTokenizer,EosTokenCriteria:()=>Q.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>f.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>w.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>f.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ie.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>F.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>F.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>D.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>f.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>f.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>f.GemmaTokenizer,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>f.Grok1Tokenizer,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HerbertTokenizer:()=>f.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>D.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ie.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>y.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>b.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Q.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>D.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ie.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>f.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>D.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>F.LogitsProcessor,LogitsProcessorList:()=>F.LogitsProcessorList,LogitsWarper:()=>F.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>f.M2M100Tokenizer,MBart50Tokenizer:()=>f.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>f.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>f.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>f.MarianTokenizer,Mask2FormerImageProcessor:()=>D.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>D.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>D.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>Q.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ie.MgpstrProcessor,MgpstrTokenizer:()=>f.MgpstrTokenizer,MinLengthLogitsProcessor:()=>F.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>F.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>f.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>D.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>D.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>D.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>D.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>D.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>D.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>D.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>D.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>D.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>D.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>y.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>ie.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>f.NllbTokenizer,NoBadWordsLogitsProcessor:()=>F.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>F.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>D.NougatImageProcessor,NougatTokenizer:()=>f.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>D.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>D.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ie.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>D.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ie.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>D.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ie.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>f.PreTrainedTokenizer,PretrainedConfig:()=>L.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>re.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>D.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>y.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ie.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>f.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>D.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ie.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>D.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>J.RawImage,RepetitionPenaltyLogitsProcessor:()=>F.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>f.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>f.RobertaTokenizer,SamImageProcessor:()=>D.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ie.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>y.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>D.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>D.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>D.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>f.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ie.SpeechT5Processor,SpeechT5Tokenizer:()=>f.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>f.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>Q.StoppingCriteria,StoppingCriteriaList:()=>Q.StoppingCriteriaList,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>F.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>D.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>f.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>F.TemperatureLogitsWarper,Tensor:()=>U.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>V.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>f.TokenizerModel,TopKLogitsWarper:()=>F.TopKLogitsWarper,TopPLogitsWarper:()=>F.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ie.VLChatProcessor,VLMImageProcessor:()=>D.VLMImageProcessor,ViTFeatureExtractor:()=>D.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>D.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>D.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>D.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>f.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>f.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>y.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>ie.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>ie.WhisperProcessor,WhisperTextStreamer:()=>V.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>F.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>f.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>f.XLMRobertaTokenizer,XLMTokenizer:()=>f.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>D.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>D.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>w.bankers_round,cat:()=>U.cat,cos_sim:()=>w.cos_sim,dot:()=>w.dot,dynamic_time_warping:()=>w.dynamic_time_warping,env:()=>De.env,full:()=>U.full,full_like:()=>U.full_like,getKeyValueShapes:()=>L.getKeyValueShapes,hamming:()=>N.hamming,hanning:()=>N.hanning,interpolate:()=>U.interpolate,interpolate_4d:()=>U.interpolate_4d,interpolate_data:()=>w.interpolate_data,is_chinese_char:()=>f.is_chinese_char,layer_norm:()=>U.layer_norm,load_image:()=>J.load_image,log_softmax:()=>w.log_softmax,magnitude:()=>w.magnitude,matmul:()=>U.matmul,max:()=>w.max,mean:()=>U.mean,mean_pooling:()=>U.mean_pooling,medianFilter:()=>w.medianFilter,mel_filter_bank:()=>N.mel_filter_bank,min:()=>w.min,ones:()=>U.ones,ones_like:()=>U.ones_like,permute:()=>U.permute,permute_data:()=>w.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>U.quantize_embeddings,rand:()=>U.rand,read_audio:()=>N.read_audio,rfft:()=>U.rfft,round:()=>w.round,slice:()=>U.slice,softmax:()=>w.softmax,spectrogram:()=>N.spectrogram,stack:()=>U.stack,std_mean:()=>U.std_mean,topk:()=>U.topk,window_function:()=>N.window_function,zeros:()=>U.zeros,zeros_like:()=>U.zeros_like});var De=ms("./src/env.js"),A=ms("./src/pipelines.js"),r=ms("./src/models.js"),f=ms("./src/tokenizers.js"),L=ms("./src/configs.js"),N=ms("./src/utils/audio.js"),J=ms("./src/utils/image.js"),U=ms("./src/utils/tensor.js"),w=ms("./src/utils/maths.js"),v=ms("./src/base/feature_extraction_utils.js"),y=ms("./src/models/feature_extractors.js"),M=ms("./src/models/auto/feature_extraction_auto.js"),b=ms("./src/base/image_processors_utils.js"),D=ms("./src/models/image_processors.js"),H=ms("./src/models/auto/image_processing_auto.js"),re=ms("./src/base/processing_utils.js"),ie=ms("./src/models/processors.js"),z=ms("./src/models/auto/processing_auto.js"),V=ms("./src/generation/streamers.js"),Q=ms("./src/generation/stopping_criteria.js"),F=ms("./src/generation/logits_process.js")})(),c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoFeatureExtractor,c.AutoImageProcessor,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC,c.AutoModelForCausalLM,c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForPoseEstimation,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection;var Zm=c.AutoProcessor,e_=c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.ClassifierFreeGuidanceLogitsProcessor,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTImageProcessor,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DepthProForDepthEstimation,c.DepthProPreTrainedModel,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrImageProcessor,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutImageProcessor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.ExaoneForCausalLM,c.ExaoneModel,c.ExaonePreTrainedModel,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline;var t_=c.Florence2ForConditionalGeneration;c.Florence2PreTrainedModel,c.Florence2Processor,c.ForcedBOSTokenLogitsProcessor,c.ForcedEOSTokenLogitsProcessor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.GraniteForCausalLM,c.GraniteModel,c.GranitePreTrainedModel,c.Grok1Tokenizer,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.IJepaForImageClassification,c.IJepaModel,c.IJepaPreTrainedModel,c.Idefics3ForConditionalGeneration,c.Idefics3ImageProcessor,c.Idefics3PreTrainedModel,c.Idefics3Processor,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageProcessor,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline,c.InterruptableStoppingCriteria,c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.JinaCLIPImageProcessor,c.JinaCLIPModel,c.JinaCLIPPreTrainedModel,c.JinaCLIPProcessor,c.JinaCLIPTextModel,c.JinaCLIPVisionModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaOnevisionForConditionalGeneration,c.LlavaOnevisionImageProcessor,c.LlavaPreTrainedModel,c.LogitsProcessor,c.LogitsProcessorList,c.LogitsWarper,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.Mask2FormerImageProcessor,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerImageProcessor,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MgpstrForSceneTextRecognition,c.MgpstrModelOutput,c.MgpstrPreTrainedModel,c.MgpstrProcessor,c.MgpstrTokenizer,c.MinLengthLogitsProcessor,c.MinNewTokensLengthLogitsProcessor,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileLLMForCausalLM,c.MobileLLMModel,c.MobileLLMPreTrainedModel,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1ImageProcessor,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2ImageProcessor,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3ImageProcessor,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4ImageProcessor,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.ModernBertForMaskedLM,c.ModernBertForSequenceClassification,c.ModernBertForTokenClassification,c.ModernBertModel,c.ModernBertPreTrainedModel,c.Moondream1ForConditionalGeneration,c.MoonshineFeatureExtractor,c.MoonshineForConditionalGeneration,c.MoonshineModel,c.MoonshinePreTrainedModel,c.MoonshineProcessor,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MultiModalityCausalLM,c.MultiModalityPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NoBadWordsLogitsProcessor,c.NoRepeatNGramLogitsProcessor,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.Olmo2ForCausalLM,c.Olmo2Model,c.Olmo2PreTrainedModel,c.OlmoForCausalLM,c.OlmoModel,c.OlmoPreTrainedModel,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTImageProcessor,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.PaliGemmaForConditionalGeneration,c.PaliGemmaPreTrainedModel,c.PaliGemmaProcessor,c.PatchTSMixerForPrediction,c.PatchTSMixerModel,c.PatchTSMixerPreTrainedModel,c.PatchTSTForPrediction,c.PatchTSTModel,c.PatchTSTPreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.Phi3VForCausalLM,c.Phi3VImageProcessor,c.Phi3VPreTrainedModel,c.Phi3VProcessor,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.Qwen2VLForConditionalGeneration,c.Qwen2VLImageProcessor,c.Qwen2VLPreTrainedModel,c.Qwen2VLProcessor,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel;var s_=c.RawImage;c.RepetitionPenaltyLogitsProcessor,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerImageProcessor,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.SummarizationPipeline,c.SuppressTokensAtBeginLogitsProcessor,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.TemperatureLogitsWarper,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline,c.TextStreamer,c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TopKLogitsWarper,c.TopPLogitsWarper,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.VLChatProcessor,c.VLMImageProcessor,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitPoseForPoseEstimation,c.VitPoseImageProcessor,c.VitPosePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor,c.WhisperForConditionalGeneration,c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTimeStampLogitsProcessor,c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosImageProcessor,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env;var r_=c.full;c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.load_image,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data,c.pipeline,c.quantize_embeddings,c.rand,c.read_audio,c.rfft,c.round,c.slice,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;async function n_(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}class Ip{static async getInstance(A=null){return this.processor??(this.processor=Zm.from_pretrained(this.model_id)),this.tokenizer??(this.tokenizer=e_.from_pretrained(this.model_id)),this.supports_fp16??(this.supports_fp16=await n_()),this.model??(this.model=t_.from_pretrained(this.model_id,{dtype:{embed_tokens:this.supports_fp16?"fp16":"fp32",vision_encoder:this.supports_fp16?"fp16":"fp32",encoder_model:"q4",decoder_model_merged:"q4"},device:"webgpu",progress_callback:A})),Promise.all([this.model,this.tokenizer,this.processor])}}ge(Ip,"model_id","onnx-community/Florence-2-base-ft");async function o_(){self.postMessage({status:"loading",data:"Loading model..."});const[De,A,r]=await Ip.getInstance(N=>{self.postMessage(N)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const f=A("a"),L=r_([1,3,768,768],0);await De.generate({...f,pixel_values:L,max_new_tokens:1}),self.postMessage({status:"ready"})}const i_=[""];let kc,Op;async function a_({text:De,url:A,task:r}){const[f,L,N]=await Ip.getInstance(),J=performance.now();if(!kc){const H=await s_.fromURL(A);Op=H.size,kc=await N(H)}let U=r;i_.includes(r)&&De&&(U+=De);const w=N.construct_prompts(U),v=L(w),y=await f.generate({...v,...kc,max_new_tokens:128,num_beams:1,do_sample:!1}),M=L.batch_decode(y,{skip_special_tokens:!1})[0],b=N.post_process_generation(M,r,Op),D=performance.now();self.postMessage({status:"complete",result:b,time:D-J})}self.addEventListener("message",async De=>{const{type:A,data:r}=De.data;switch(A){case"load":o_();break;case"run":a_(r);break;case"reset":kc=Op=null;break}})})();