(function(){const Me=document.createElement("link").relList;if(Me&&Me.supports&&Me.supports("modulepreload"))return;for(const ae of document.querySelectorAll('link[rel="modulepreload"]'))I(ae);new MutationObserver(ae=>{for(const he of ae)if(he.type==="childList")for(const xe of he.addedNodes)xe.tagName==="LINK"&&xe.rel==="modulepreload"&&I(xe)}).observe(document,{childList:!0,subtree:!0});function N(ae){const he={};return ae.integrity&&(he.integrity=ae.integrity),ae.referrerPolicy&&(he.referrerPolicy=ae.referrerPolicy),ae.crossOrigin==="use-credentials"?he.credentials="include":ae.crossOrigin==="anonymous"?he.credentials="omit":he.credentials="same-origin",he}function I(ae){if(ae.ep)return;ae.ep=!0;const he=N(ae);fetch(ae.href,he)}})();var Ic={},$f={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(_t,Me,N)=>{_t.exports=N.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{Environment:()=>Ge,Interpreter:()=>ut,Template:()=>St,parse:()=>$e,tokenize:()=>P});var I=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",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"}),ae=Object.freeze({set:I.Set,for:I.For,in:I.In,is:I.Is,if:I.If,else:I.Else,endif:I.EndIf,elif:I.ElseIf,endfor:I.EndFor,and:I.And,or:I.Or,not:I.Not,"not in":I.NotIn,macro:I.Macro,endmacro:I.EndMacro,true:I.BooleanLiteral,false:I.BooleanLiteral,True:I.BooleanLiteral,False:I.BooleanLiteral}),he=class{constructor(M,W){this.value=M,this.type=W}};function xe(M){return/\w/.test(M)}function be(M){return/[0-9]/.test(M)}var R=[["{%",I.OpenStatement],["%}",I.CloseStatement],["{{",I.OpenExpression],["}}",I.CloseExpression],["(",I.OpenParen],[")",I.CloseParen],["{",I.OpenCurlyBracket],["}",I.CloseCurlyBracket],["[",I.OpenSquareBracket],["]",I.CloseSquareBracket],[",",I.Comma],[".",I.Dot],[":",I.Colon],["|",I.Pipe],["<=",I.ComparisonBinaryOperator],[">=",I.ComparisonBinaryOperator],["==",I.ComparisonBinaryOperator],["!=",I.ComparisonBinaryOperator],["<",I.ComparisonBinaryOperator],[">",I.ComparisonBinaryOperator],["+",I.AdditiveBinaryOperator],["-",I.AdditiveBinaryOperator],["*",I.MultiplicativeBinaryOperator],["/",I.MultiplicativeBinaryOperator],["%",I.MultiplicativeBinaryOperator],["=",I.Equals]],$=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(M,W={}){return M.endsWith(` `)&&(M=M.slice(0,-1)),M=M.replace(/{#.*?#}/gs,"{##}"),W.lstrip_blocks&&(M=M.replace(/^[ \t]*({[#%])/gm,"$1")),W.trim_blocks&&(M=M.replace(/([#%]})\n/g,"$1")),M.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function P(M,W={}){const E=[],te=V(M,W);let pe=0;const Je=He=>{let Mt="";for(;He(te[pe]);){if(te[pe]==="\\"){if(++pe,pe>=te.length)throw new SyntaxError("Unexpected end of input");const nt=te[pe++],pt=$.get(nt);if(pt===void 0)throw new SyntaxError(`Unexpected escaped character: ${nt}`);Mt+=pt;continue}if(Mt+=te[pe++],pe>=te.length)throw new SyntaxError("Unexpected end of input")}return Mt};e:for(;pe0){E.push(new he(nt,I.Text));continue}}Je(nt=>/\s/.test(nt));const Mt=te[pe];if(Mt==="-"||Mt==="+"){const nt=E.at(-1)?.type;if(nt===I.Text||nt===void 0)throw new SyntaxError(`Unexpected character: ${Mt}`);switch(nt){case I.Identifier:case I.NumericLiteral:case I.BooleanLiteral:case I.StringLiteral:case I.CloseParen:case I.CloseSquareBracket:break;default:{++pe;const pt=Je(be);E.push(new he(`${Mt}${pt}`,pt.length>0?I.NumericLiteral:I.UnaryOperator));continue}}}for(const[nt,pt]of R)if(te.slice(pe,pe+nt.length)===nt){E.push(new he(nt,pt)),pe+=nt.length;continue e}if(Mt==="'"||Mt==='"'){++pe;const nt=Je(pt=>pt!==Mt);E.push(new he(nt,I.StringLiteral)),++pe;continue}if(be(Mt)){const nt=Je(be);E.push(new he(nt,I.NumericLiteral));continue}if(xe(Mt)){const nt=Je(xe),pt=Object.hasOwn(ae,nt)?ae[nt]:I.Identifier;pt===I.In&&E.at(-1)?.type===I.Not?(E.pop(),E.push(new he("not in",I.NotIn))):E.push(new he(nt,pt));continue}throw new SyntaxError(`Unexpected character: ${Mt}`)}return E}var K=class{type="Statement"},ne=class extends K{constructor(M){super(),this.body=M}type="Program"},oe=class extends K{constructor(M,W,E){super(),this.test=M,this.body=W,this.alternate=E}type="If"},_e=class extends K{constructor(M,W,E,te){super(),this.loopvar=M,this.iterable=W,this.body=E,this.defaultBlock=te}type="For"},F=class extends K{constructor(M,W){super(),this.assignee=M,this.value=W}type="Set"},Q=class extends K{constructor(M,W,E){super(),this.name=M,this.args=W,this.body=E}type="Macro"},se=class extends K{type="Expression"},le=class extends se{constructor(M,W,E){super(),this.object=M,this.property=W,this.computed=E}type="MemberExpression"},ie=class extends se{constructor(M,W){super(),this.callee=M,this.args=W}type="CallExpression"},j=class extends se{constructor(M){super(),this.value=M}type="Identifier"},A=class extends se{constructor(M){super(),this.value=M}type="Literal"},L=class extends A{type="NumericLiteral"},C=class extends A{type="StringLiteral"},me=class extends A{type="BooleanLiteral"},ye=class extends A{type="ArrayLiteral"},Se=class extends A{type="TupleLiteral"},Pe=class extends A{type="ObjectLiteral"},Ce=class extends se{constructor(M,W,E){super(),this.operator=M,this.left=W,this.right=E}type="BinaryExpression"},rt=class extends se{constructor(M,W){super(),this.operand=M,this.filter=W}type="FilterExpression"},Xe=class extends se{constructor(M,W){super(),this.iterable=M,this.test=W}type="SelectExpression"},dt=class extends se{constructor(M,W,E){super(),this.operand=M,this.negate=W,this.test=E}type="TestExpression"},ge=class extends se{constructor(M,W){super(),this.operator=M,this.argument=W}type="UnaryExpression"},U=class extends se{constructor(M=void 0,W=void 0,E=void 0){super(),this.start=M,this.stop=W,this.step=E}type="SliceExpression"},de=class extends se{constructor(M,W){super(),this.key=M,this.value=W}type="KeywordArgumentExpression"};function $e(M){const W=new ne([]);let E=0;function te(Qe,yt){const Ft=M[E++];if(!Ft||Ft.type!==Qe)throw new Error(`Parser Error: ${yt}. ${Ft.type} !== ${Qe}.`);return Ft}function pe(){switch(M[E].type){case I.Text:return Mt();case I.OpenStatement:return nt();case I.OpenExpression:return pt();default:throw new SyntaxError(`Unexpected token type: ${M[E].type}`)}}function Je(...Qe){return E+Qe.length<=M.length&&Qe.some((yt,Ft)=>yt!==M[E+Ft].type)}function He(...Qe){return E+Qe.length<=M.length&&Qe.every((yt,Ft)=>yt===M[E+Ft].type)}function Mt(){return new C(te(I.Text,"Expected text token").value)}function nt(){te(I.OpenStatement,"Expected opening statement token");let Qe;switch(M[E].type){case I.Set:++E,Qe=Bt(),te(I.CloseStatement,"Expected closing statement token");break;case I.If:++E,Qe=et(),te(I.OpenStatement,"Expected {% token"),te(I.EndIf,"Expected endif token"),te(I.CloseStatement,"Expected %} token");break;case I.Macro:++E,Qe=B(),te(I.OpenStatement,"Expected {% token"),te(I.EndMacro,"Expected endmacro token"),te(I.CloseStatement,"Expected %} token");break;case I.For:++E,Qe=Te(),te(I.OpenStatement,"Expected {% token"),te(I.EndFor,"Expected endfor token"),te(I.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${M[E].type}`)}return Qe}function pt(){te(I.OpenExpression,"Expected opening expression token");const Qe=Re();return te(I.CloseExpression,"Expected closing expression token"),Qe}function Bt(){const Qe=Re();if(He(I.Equals)){++E;const yt=Bt();return new F(Qe,yt)}return Qe}function et(){const Qe=Re();te(I.CloseStatement,"Expected closing statement token");const yt=[],Ft=[];for(;!(M[E]?.type===I.OpenStatement&&(M[E+1]?.type===I.ElseIf||M[E+1]?.type===I.Else||M[E+1]?.type===I.EndIf));)yt.push(pe());if(M[E]?.type===I.OpenStatement&&M[E+1]?.type!==I.EndIf)if(++E,He(I.ElseIf))te(I.ElseIf,"Expected elseif token"),Ft.push(et());else for(te(I.Else,"Expected else token"),te(I.CloseStatement,"Expected closing statement token");!(M[E]?.type===I.OpenStatement&&M[E+1]?.type===I.EndIf);)Ft.push(pe());return new oe(Qe,yt,Ft)}function B(){const Qe=wr();if(Qe.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const yt=Ot();te(I.CloseStatement,"Expected closing statement token");const Ft=[];for(;Je(I.OpenStatement,I.EndMacro);)Ft.push(pe());return new Q(Qe,yt,Ft)}function ce(Qe=!1){const yt=Qe?wr:Re,Ft=[yt()],Zr=He(I.Comma);for(;Zr&&(++E,Ft.push(yt()),!!He(I.Comma)););return Zr?new Se(Ft):Ft[0]}function Te(){const Qe=ce(!0);if(!(Qe instanceof j||Qe instanceof Se))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Qe.type} instead`);te(I.In,"Expected `in` keyword following loop variable");const yt=Re();te(I.CloseStatement,"Expected closing statement token");const Ft=[];for(;Je(I.OpenStatement,I.EndFor)&&Je(I.OpenStatement,I.Else);)Ft.push(pe());const Zr=[];if(He(I.OpenStatement,I.Else))for(++E,++E,te(I.CloseStatement,"Expected closing statement token");Je(I.OpenStatement,I.EndFor);)Zr.push(pe());return new _e(Qe,yt,Ft,Zr)}function Re(){return ke()}function ke(){const Qe=tt();if(He(I.If)){++E;const yt=tt();if(He(I.Else)){++E;const Ft=tt();return new oe(yt,[Qe],[Ft])}else return new Xe(Qe,yt)}return Qe}function tt(){let Qe=ft();for(;He(I.Or);){const yt=M[E];++E;const Ft=ft();Qe=new Ce(yt,Qe,Ft)}return Qe}function ft(){let Qe=lt();for(;He(I.And);){const yt=M[E];++E;const Ft=lt();Qe=new Ce(yt,Qe,Ft)}return Qe}function lt(){let Qe;for(;He(I.Not);){const yt=M[E];++E;const Ft=lt();Qe=new ge(yt,Ft)}return Qe??Ct()}function Ct(){let Qe=gt();for(;He(I.ComparisonBinaryOperator)||He(I.In)||He(I.NotIn);){const yt=M[E];++E;const Ft=gt();Qe=new Ce(yt,Qe,Ft)}return Qe}function gt(){let Qe=Ht();for(;He(I.AdditiveBinaryOperator);){const yt=M[E];++E;const Ft=Ht();Qe=new Ce(yt,Qe,Ft)}return Qe}function ze(){const Qe=Ut();return He(I.OpenParen)?Rt(Qe):Qe}function Rt(Qe){let yt=new ie(Qe,Ot());return He(I.OpenParen)&&(yt=Rt(yt)),yt}function Ot(){te(I.OpenParen,"Expected opening parenthesis for arguments list");const Qe=Wt();return te(I.CloseParen,"Expected closing parenthesis for arguments list"),Qe}function Wt(){const Qe=[];for(;!He(I.CloseParen);){let yt=Re();if(He(I.Equals)){if(++E,!(yt instanceof j))throw new SyntaxError("Expected identifier for keyword argument");const Ft=Re();yt=new de(yt,Ft)}Qe.push(yt),He(I.Comma)&&++E}return Qe}function zt(){const Qe=[];let yt=!1;for(;!He(I.CloseSquareBracket);)He(I.Colon)?(Qe.push(void 0),++E,yt=!0):(Qe.push(Re()),He(I.Colon)&&(++E,yt=!0));if(Qe.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(yt){if(Qe.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new U(...Qe)}return Qe[0]}function Ut(){let Qe=wr();for(;He(I.Dot)||He(I.OpenSquareBracket);){const yt=M[E];++E;let Ft;const Zr=yt.type!==I.Dot;if(Zr)Ft=zt(),te(I.CloseSquareBracket,"Expected closing square bracket");else if(Ft=wr(),Ft.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Qe=new le(Qe,Ft,Zr)}return Qe}function Ht(){let Qe=ur();for(;He(I.MultiplicativeBinaryOperator);){const yt=M[E];++E;const Ft=ur();Qe=new Ce(yt,Qe,Ft)}return Qe}function ur(){let Qe=rr();for(;He(I.Is);){++E;const yt=He(I.Not);yt&&++E;let Ft=wr();if(Ft instanceof me&&(Ft=new j(Ft.value.toString())),!(Ft instanceof j))throw new SyntaxError("Expected identifier for the test");Qe=new dt(Qe,yt,Ft)}return Qe}function rr(){let Qe=ze();for(;He(I.Pipe);){++E;let yt=wr();if(!(yt instanceof j))throw new SyntaxError("Expected identifier for the filter");He(I.OpenParen)&&(yt=Rt(yt)),Qe=new rt(Qe,yt)}return Qe}function wr(){const Qe=M[E];switch(Qe.type){case I.NumericLiteral:return++E,new L(Number(Qe.value));case I.StringLiteral:return++E,new C(Qe.value);case I.BooleanLiteral:return++E,new me(Qe.value.toLowerCase()==="true");case I.Identifier:return++E,new j(Qe.value);case I.OpenParen:{++E;const yt=ce();if(M[E].type!==I.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${M[E].type} instead`);return++E,yt}case I.OpenSquareBracket:{++E;const yt=[];for(;!He(I.CloseSquareBracket);)yt.push(Re()),He(I.Comma)&&++E;return++E,new ye(yt)}case I.OpenCurlyBracket:{++E;const yt=new Map;for(;!He(I.CloseCurlyBracket);){const Ft=Re();te(I.Colon,"Expected colon between key and value in object literal");const Zr=Re();yt.set(Ft,Zr),He(I.Comma)&&++E}return++E,new Pe(yt)}default:throw new SyntaxError(`Unexpected token: ${Qe.type}`)}}for(;E=0?(W=(W??=0)<0?Math.max(M.length+W,0):Math.min(W,M.length),E=(E??=M.length)<0?Math.max(M.length+E,0):Math.min(E,M.length)):(W=(W??=M.length-1)<0?Math.max(M.length+W,-1):Math.min(W,M.length-1),E=(E??=-1)<-1?Math.max(M.length+E,-1):Math.min(E,M.length-1));const Je=[];for(let He=W;pe*HeW.toUpperCase())}var st=class{type="RuntimeValue";value;builtins=new Map;constructor(M=void 0){this.value=M}__bool__(){return new at(!!this.value)}},ot=class extends st{type="NumericValue"},De=class extends st{type="StringValue";builtins=new Map([["upper",new qe(()=>new De(this.value.toUpperCase()))],["lower",new qe(()=>new De(this.value.toLowerCase()))],["strip",new qe(()=>new De(this.value.trim()))],["title",new qe(()=>new De(ct(this.value)))],["length",new ot(this.value.length)]])},at=class extends st{type="BooleanValue"},Et=class extends st{type="ObjectValue";__bool__(){return new at(this.value.size>0)}builtins=new Map([["get",new qe(([M,W])=>{if(!(M instanceof De))throw new Error(`Object key must be a string: got ${M.type}`);return this.value.get(M.value)??W??new je})],["items",new qe(()=>new H(Array.from(this.value.entries()).map(([M,W])=>new H([new De(M),W]))))]])},Fe=class extends Et{type="KeywordArgumentsValue"},H=class extends st{type="ArrayValue";builtins=new Map([["length",new ot(this.value.length)]]);__bool__(){return new at(this.value.length>0)}},Ee=class extends H{type="TupleValue"},qe=class extends st{type="FunctionValue"},je=class extends st{type="NullValue"},Ve=class extends st{type="UndefinedValue"},Ge=class{constructor(M){this.parent=M}variables=new Map([["namespace",new qe(M=>{if(M.length===0)return new Et(new Map);if(M.length!==1||!(M[0]instanceof Et))throw new Error("`namespace` expects either zero arguments or a single object argument");return M[0]})]]);tests=new Map([["boolean",M=>M.type==="BooleanValue"],["callable",M=>M instanceof qe],["odd",M=>{if(M.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${M.type}`);return M.value%2!==0}],["even",M=>{if(M.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${M.type}`);return M.value%2===0}],["false",M=>M.type==="BooleanValue"&&!M.value],["true",M=>M.type==="BooleanValue"&&M.value],["string",M=>M.type==="StringValue"],["number",M=>M.type==="NumericValue"],["integer",M=>M.type==="NumericValue"&&Number.isInteger(M.value)],["iterable",M=>M instanceof H||M instanceof De],["lower",M=>{const W=M.value;return M.type==="StringValue"&&W===W.toLowerCase()}],["upper",M=>{const W=M.value;return M.type==="StringValue"&&W===W.toUpperCase()}],["none",M=>M.type==="NullValue"],["defined",M=>M.type!=="UndefinedValue"],["undefined",M=>M.type==="UndefinedValue"],["equalto",(M,W)=>M.value===W.value],["eq",(M,W)=>M.value===W.value]]);set(M,W){return this.declareVariable(M,ht(W))}declareVariable(M,W){if(this.variables.has(M))throw new SyntaxError(`Variable already declared: ${M}`);return this.variables.set(M,W),W}setVariable(M,W){return this.variables.set(M,W),W}resolve(M){if(this.variables.has(M))return this;if(this.parent)return this.parent.resolve(M);throw new Error(`Unknown variable: ${M}`)}lookupVariable(M){try{return this.resolve(M).variables.get(M)??new Ve}catch{return new Ve}}},ut=class{global;constructor(M){this.global=M??new Ge}run(M){return this.evaluate(M,this.global)}evaluateBinaryExpression(M,W){const E=this.evaluate(M.left,W);switch(M.operator.value){case"and":return E.__bool__().value?this.evaluate(M.right,W):E;case"or":return E.__bool__().value?E:this.evaluate(M.right,W)}const te=this.evaluate(M.right,W);switch(M.operator.value){case"==":return new at(E.value==te.value);case"!=":return new at(E.value!=te.value)}if(E instanceof Ve||te instanceof Ve)throw new Error("Cannot perform operation on undefined values");if(E instanceof je||te instanceof je)throw new Error("Cannot perform operation on null values");if(E instanceof ot&&te instanceof ot)switch(M.operator.value){case"+":return new ot(E.value+te.value);case"-":return new ot(E.value-te.value);case"*":return new ot(E.value*te.value);case"/":return new ot(E.value/te.value);case"%":return new ot(E.value%te.value);case"<":return new at(E.value":return new at(E.value>te.value);case">=":return new at(E.value>=te.value);case"<=":return new at(E.value<=te.value)}else if(E instanceof H&&te instanceof H)switch(M.operator.value){case"+":return new H(E.value.concat(te.value))}else if(te instanceof H){const pe=te.value.find(Je=>Je.value===E.value)!==void 0;switch(M.operator.value){case"in":return new at(pe);case"not in":return new at(!pe)}}if(E instanceof De||te instanceof De)switch(M.operator.value){case"+":return new De(E.value.toString()+te.value.toString())}if(E instanceof De&&te instanceof De)switch(M.operator.value){case"in":return new at(te.value.includes(E.value));case"not in":return new at(!te.value.includes(E.value))}if(E instanceof De&&te instanceof Et)switch(M.operator.value){case"in":return new at(te.value.has(E.value));case"not in":return new at(!te.value.has(E.value))}throw new SyntaxError(`Unknown operator "${M.operator.value}" between ${E.type} and ${te.type}`)}evaluateArguments(M,W){const E=[],te=new Map;for(const pe of M)if(pe.type==="KeywordArgumentExpression"){const Je=pe;te.set(Je.key.value,this.evaluate(Je.value,W))}else{if(te.size>0)throw new Error("Positional arguments must come before keyword arguments");E.push(this.evaluate(pe,W))}return[E,te]}evaluateFilterExpression(M,W){const E=this.evaluate(M.operand,W);if(M.filter.type==="Identifier"){const te=M.filter;if(te.value==="tojson")return new De(Tt(E));if(E instanceof H)switch(te.value){case"list":return E;case"first":return E.value[0];case"last":return E.value[E.value.length-1];case"length":return new ot(E.value.length);case"reverse":return new H(E.value.reverse());case"sort":return new H(E.value.sort((pe,Je)=>{if(pe.type!==Je.type)throw new Error(`Cannot compare different types: ${pe.type} and ${Je.type}`);switch(pe.type){case"NumericValue":return pe.value-Je.value;case"StringValue":return pe.value.localeCompare(Je.value);default:throw new Error(`Cannot compare type: ${pe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${te.value}`)}else if(E instanceof De)switch(te.value){case"length":return new ot(E.value.length);case"upper":return new De(E.value.toUpperCase());case"lower":return new De(E.value.toLowerCase());case"title":return new De(ct(E.value));case"capitalize":return new De(E.value.charAt(0).toUpperCase()+E.value.slice(1));case"trim":return new De(E.value.trim());case"indent":return new De(E.value.split(` `).map((pe,Je)=>Je===0||pe.length===0?pe:" "+pe).join(` `));case"string":return E;default:throw new Error(`Unknown StringValue filter: ${te.value}`)}else if(E instanceof ot)switch(te.value){case"abs":return new ot(Math.abs(E.value));default:throw new Error(`Unknown NumericValue filter: ${te.value}`)}else if(E instanceof Et)switch(te.value){case"items":return new H(Array.from(E.value.entries()).map(([pe,Je])=>new H([new De(pe),Je])));case"length":return new ot(E.value.size);default:throw new Error(`Unknown ObjectValue filter: ${te.value}`)}throw new Error(`Cannot apply filter "${te.value}" to type: ${E.type}`)}else if(M.filter.type==="CallExpression"){const te=M.filter;if(te.callee.type!=="Identifier")throw new Error(`Unknown filter: ${te.callee.type}`);const pe=te.callee.value;if(pe==="tojson"){const[,Je]=this.evaluateArguments(te.args,W),He=Je.get("indent")??new je;if(!(He instanceof ot||He instanceof je))throw new Error("If set, indent must be a number");return new De(Tt(E,He.value))}if(E instanceof H){switch(pe){case"selectattr":{if(E.value.some(Bt=>!(Bt instanceof Et)))throw new Error("`selectattr` can only be applied to array of objects");if(te.args.some(Bt=>Bt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Je,He,Mt]=te.args.map(Bt=>this.evaluate(Bt,W));let nt;if(He){const Bt=W.tests.get(He.value);if(!Bt)throw new Error(`Unknown test: ${He.value}`);nt=Bt}else nt=(...Bt)=>Bt[0].__bool__().value;const pt=E.value.filter(Bt=>{const et=Bt.value.get(Je.value);return et?nt(et,Mt):!1});return new H(pt)}case"map":{const[,Je]=this.evaluateArguments(te.args,W);if(Je.has("attribute")){const He=Je.get("attribute");if(!(He instanceof De))throw new Error("attribute must be a string");const Mt=Je.get("default"),nt=E.value.map(pt=>{if(!(pt instanceof Et))throw new Error("items in map must be an object");return pt.value.get(He.value)??Mt??new Ve});return new H(nt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${pe}`)}else if(E instanceof De){switch(pe){case"indent":{const[Je,He]=this.evaluateArguments(te.args,W),Mt=Je.at(0)??He.get("width")??new ot(4);if(!(Mt instanceof ot))throw new Error("width must be a number");const nt=Je.at(1)??He.get("first")??new at(!1),pt=Je.at(2)??He.get("blank")??new at(!1),Bt=E.value.split(` `),et=" ".repeat(Mt.value),B=Bt.map((ce,Te)=>!nt.value&&Te===0||!pt.value&&ce.length===0?ce:et+ce);return new De(B.join(` `))}}throw new Error(`Unknown StringValue filter: ${pe}`)}else throw new Error(`Cannot apply filter "${pe}" to type: ${E.type}`)}throw new Error(`Unknown filter: ${M.filter.type}`)}evaluateTestExpression(M,W){const E=this.evaluate(M.operand,W),te=W.tests.get(M.test.value);if(!te)throw new Error(`Unknown test: ${M.test.value}`);const pe=te(E);return new at(M.negate?!pe:pe)}evaluateUnaryExpression(M,W){const E=this.evaluate(M.argument,W);switch(M.operator.value){case"not":return new at(!E.value);default:throw new SyntaxError(`Unknown operator: ${M.operator.value}`)}}evalProgram(M,W){return this.evaluateBlock(M.body,W)}evaluateBlock(M,W){let E="";for(const te of M){const pe=this.evaluate(te,W);pe.type!=="NullValue"&&pe.type!=="UndefinedValue"&&(E+=pe.value)}return new De(E)}evaluateIdentifier(M,W){return W.lookupVariable(M.value)}evaluateCallExpression(M,W){const[E,te]=this.evaluateArguments(M.args,W);te.size>0&&E.push(new Fe(te));const pe=this.evaluate(M.callee,W);if(pe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${pe.type}`);return pe.value(E,W)}evaluateSliceExpression(M,W,E){if(!(M instanceof H||M instanceof De))throw new Error("Slice object must be an array or string");const te=this.evaluate(W.start,E),pe=this.evaluate(W.stop,E),Je=this.evaluate(W.step,E);if(!(te instanceof ot||te instanceof Ve))throw new Error("Slice start must be numeric or undefined");if(!(pe instanceof ot||pe instanceof Ve))throw new Error("Slice stop must be numeric or undefined");if(!(Je instanceof ot||Je instanceof Ve))throw new Error("Slice step must be numeric or undefined");return M instanceof H?new H(Ue(M.value,te.value,pe.value,Je.value)):new De(Ue(Array.from(M.value),te.value,pe.value,Je.value).join(""))}evaluateMemberExpression(M,W){const E=this.evaluate(M.object,W);let te;if(M.computed){if(M.property.type==="SliceExpression")return this.evaluateSliceExpression(E,M.property,W);te=this.evaluate(M.property,W)}else te=new De(M.property.value);let pe;if(E instanceof Et){if(!(te instanceof De))throw new Error(`Cannot access property with non-string: got ${te.type}`);pe=E.value.get(te.value)??E.builtins.get(te.value)}else if(E instanceof H||E instanceof De)if(te instanceof ot)pe=E.value.at(te.value),E instanceof De&&(pe=new De(E.value.at(te.value)));else if(te instanceof De)pe=E.builtins.get(te.value);else throw new Error(`Cannot access property with non-string/non-number: got ${te.type}`);else{if(!(te instanceof De))throw new Error(`Cannot access property with non-string: got ${te.type}`);pe=E.builtins.get(te.value)}return pe instanceof st?pe:new Ve}evaluateSet(M,W){const E=this.evaluate(M.value,W);if(M.assignee.type==="Identifier"){const te=M.assignee.value;W.setVariable(te,E)}else if(M.assignee.type==="MemberExpression"){const te=M.assignee,pe=this.evaluate(te.object,W);if(!(pe instanceof Et))throw new Error("Cannot assign to member of non-object");if(te.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");pe.value.set(te.property.value,E)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(M.assignee)}`);return new je}evaluateIf(M,W){const E=this.evaluate(M.test,W);return this.evaluateBlock(E.__bool__().value?M.body:M.alternate,W)}evaluateFor(M,W){const E=new Ge(W);let te,pe;if(M.iterable.type==="SelectExpression"){const pt=M.iterable;pe=this.evaluate(pt.iterable,E),te=pt.test}else pe=this.evaluate(M.iterable,E);if(!(pe instanceof H))throw new Error(`Expected iterable type in for loop: got ${pe.type}`);const Je=[],He=[];for(let pt=0;ptce.setVariable(M.loopvar.value,et);else if(M.loopvar.type==="TupleLiteral"){const ce=M.loopvar;if(et.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${et.type}`);const Te=et;if(ce.value.length!==Te.value.length)throw new Error(`Too ${ce.value.length>Te.value.length?"few":"many"} items to unpack`);B=Re=>{for(let ke=0;ke0?Je[pt-1]:new Ve],["nextitem",pt{const pe=new Ge(te);E=E.slice();let Je;E.at(-1)?.type==="KeywordArgumentsValue"&&(Je=E.pop());for(let He=0;Hethis.evaluate(E,W)));case"TupleLiteral":return new Ee(M.value.map(E=>this.evaluate(E,W)));case"ObjectLiteral":{const E=new Map;for(const[te,pe]of M.value){const Je=this.evaluate(te,W);if(!(Je instanceof De))throw new Error(`Object keys must be strings: got ${Je.type}`);E.set(Je.value,this.evaluate(pe,W))}return new Et(E)}case"Identifier":return this.evaluateIdentifier(M,W);case"CallExpression":return this.evaluateCallExpression(M,W);case"MemberExpression":return this.evaluateMemberExpression(M,W);case"UnaryExpression":return this.evaluateUnaryExpression(M,W);case"BinaryExpression":return this.evaluateBinaryExpression(M,W);case"FilterExpression":return this.evaluateFilterExpression(M,W);case"TestExpression":return this.evaluateTestExpression(M,W);default:throw new SyntaxError(`Unknown node type: ${M.type}`)}}};function ht(M){switch(typeof M){case"number":return new ot(M);case"string":return new De(M);case"boolean":return new at(M);case"undefined":return new Ve;case"object":return M===null?new je:Array.isArray(M)?new H(M.map(ht)):new Et(new Map(Object.entries(M).map(([W,E])=>[W,ht(E)])));case"function":return new qe((W,E)=>{const te=M(...W.map(pe=>pe.value))??null;return ht(te)});default:throw new Error(`Cannot convert to runtime value: ${M}`)}}function Tt(M,W,E){const te=E??0;switch(M.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(M.value);case"ArrayValue":case"ObjectValue":{const pe=W?" ".repeat(W):"",Je=` `+pe.repeat(te),He=Je+pe;if(M.type==="ArrayValue"){const Mt=M.value.map(nt=>Tt(nt,W,te+1));return W?`[${He}${Mt.join(`,${He}`)}${Je}]`:`[${Mt.join(", ")}]`}else{const Mt=Array.from(M.value.entries()).map(([nt,pt])=>{const Bt=`"${nt}": ${Tt(pt,W,te+1)}`;return W?`${He}${Bt}`:Bt});return W?`{${Mt.join(",")}${Je}}`:`{${Mt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${M.type}`)}}var St=class{parsed;constructor(M){const W=P(M,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=$e(W)}render(M){const W=new Ge;W.set("false",!1),W.set("true",!0),W.set("raise_exception",pe=>{throw new Error(pe)}),W.set("range",X);for(const[pe,Je]of Object.entries(M))W.set(pe,Je);return new ut(W).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{registerBackend:()=>he,resolveBackendAndExecutionProviders:()=>be});const I=new Map,ae=[],he=(R,$,V)=>{if($&&typeof $.init=="function"&&typeof $.createInferenceSessionHandler=="function"){const P=I.get(R);if(P===void 0)I.set(R,{backend:$,priority:V});else{if(P.priority>V)return;if(P.priority===V&&P.backend!==$)throw new Error(`cannot register backend "${R}" using priority ${V}`)}if(V>=0){const K=ae.indexOf(R);K!==-1&&ae.splice(K,1);for(let ne=0;ne{const $=I.get(R);if(!$)return"backend not found.";if($.initialized)return $.backend;if($.aborted)return $.error;{const V=!!$.initPromise;try{return V||($.initPromise=$.backend.init(R)),await $.initPromise,$.initialized=!0,$.backend}catch(P){return V||($.error=`${P}`,$.aborted=!0),$.error}finally{delete $.initPromise}}},be=async R=>{const $=R.executionProviders||[],V=$.map(F=>typeof F=="string"?F:F.name),P=V.length===0?ae:V;let K;const ne=[],oe=new Set;for(const F of P){const Q=await xe(F);typeof Q=="string"?ne.push({name:F,err:Q}):(K||(K=Q),K===Q&&oe.add(F))}if(!K)throw new Error(`no available backend found. ERR: ${ne.map(F=>`[${F.name}] ${F.err}`).join(", ")}`);for(const{name:F,err:Q}of ne)V.includes(F)&&console.warn(`removing requested execution provider "${F}" from session options because it is not available: ${Q}`);const _e=$.filter(F=>oe.has(typeof F=="string"?F:F.name));return[K,new Proxy(R,{get:(F,Q)=>Q==="executionProviders"?_e:Reflect.get(F,Q)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{registerBackend:()=>I.registerBackend});var I=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{env:()=>he});var I=N("./node_modules/onnxruntime-common/dist/esm/version.js");let ae="warning";const he={wasm:{},webgl:{},webgpu:{},versions:{common:I.version},set logLevel(xe){if(xe!==void 0){if(typeof xe!="string"||["verbose","info","warning","error","fatal"].indexOf(xe)===-1)throw new Error(`Unsupported logging level: ${xe}`);ae=xe}},get logLevel(){return ae}};Object.defineProperty(he,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{env:()=>ae});var I=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const ae=I.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{InferenceSession:()=>he.InferenceSession,TRACE:()=>be.TRACE,TRACE_FUNC_BEGIN:()=>be.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>be.TRACE_FUNC_END,Tensor:()=>xe.Tensor,TrainingSession:()=>R.TrainingSession,env:()=>ae.env,registerBackend:()=>I.registerBackend});var I=N("./node_modules/onnxruntime-common/dist/esm/backend.js"),ae=N("./node_modules/onnxruntime-common/dist/esm/env.js"),he=N("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),xe=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),N("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var be=N("./node_modules/onnxruntime-common/dist/esm/trace.js");N("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),N("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var R=N("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{InferenceSession:()=>xe});var I=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),ae=N("./node_modules/onnxruntime-common/dist/esm/tensor.js"),he=N("./node_modules/onnxruntime-common/dist/esm/trace.js");class xe{constructor(R){this.handler=R}async run(R,$,V){(0,he.TRACE_FUNC_BEGIN)();const P={};let K={};if(typeof R!="object"||R===null||R instanceof ae.Tensor||Array.isArray(R))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof $=="object"){if($===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if($ instanceof ae.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray($)){if($.length===0)throw new TypeError("'fetches' cannot be an empty array.");ne=!1;for(const F of $){if(typeof F!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(F)===-1)throw new RangeError(`'fetches' contains invalid output name: ${F}.`);P[F]=null}if(typeof V=="object"&&V!==null)K=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else{let F=!1;const Q=Object.getOwnPropertyNames($);for(const se of this.outputNames)if(Q.indexOf(se)!==-1){const le=$[se];(le===null||le instanceof ae.Tensor)&&(F=!0,ne=!1,P[se]=le)}if(F){if(typeof V=="object"&&V!==null)K=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else K=$}}else if(typeof $<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const F of this.inputNames)if(typeof R[F]>"u")throw new Error(`input '${F}' is missing in 'feeds'.`);if(ne)for(const F of this.outputNames)P[F]=null;const oe=await this.handler.run(R,P,K),_e={};for(const F in oe)if(Object.hasOwnProperty.call(oe,F)){const Q=oe[F];Q instanceof ae.Tensor?_e[F]=Q:_e[F]=new ae.Tensor(Q.type,Q.data,Q.dims)}return(0,he.TRACE_FUNC_END)(),_e}async release(){return this.handler.dispose()}static async create(R,$,V,P){(0,he.TRACE_FUNC_BEGIN)();let K,ne={};if(typeof R=="string"){if(K=R,typeof $=="object"&&$!==null)ne=$;else if(typeof $<"u")throw new TypeError("'options' must be an object.")}else if(R instanceof Uint8Array){if(K=R,typeof $=="object"&&$!==null)ne=$;else if(typeof $<"u")throw new TypeError("'options' must be an object.")}else if(R instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&R instanceof SharedArrayBuffer){const Q=R;let se=0,le=R.byteLength;if(typeof $=="object"&&$!==null)ne=$;else if(typeof $=="number"){if(se=$,!Number.isSafeInteger(se))throw new RangeError("'byteOffset' must be an integer.");if(se<0||se>=Q.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Q.byteLength}).`);if(le=R.byteLength-se,typeof V=="number"){if(le=V,!Number.isSafeInteger(le))throw new RangeError("'byteLength' must be an integer.");if(le<=0||se+le>Q.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Q.byteLength-se}].`);if(typeof P=="object"&&P!==null)ne=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof V<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof $<"u")throw new TypeError("'options' must be an object.");K=new Uint8Array(Q,se,le)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[oe,_e]=await(0,I.resolveBackendAndExecutionProviders)(ne),F=await oe.createInferenceSessionHandler(K,_e);return(0,he.TRACE_FUNC_END)(),new xe(F)}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":(_t,Me,N)=>{N.r(Me),N.d(Me,{InferenceSession:()=>ae});var I=N("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const ae=I.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(_t,Me,N)=>{N.r(Me)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(_t,Me,N)=>{N.r(Me)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{tensorToDataURL:()=>I,tensorToImageData:()=>ae});const I=(he,xe)=>{const be=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);be.width=he.dims[3],be.height=he.dims[2];const R=be.getContext("2d");if(R!=null){let $,V;xe?.tensorLayout!==void 0&&xe.tensorLayout==="NHWC"?($=he.dims[2],V=he.dims[3]):($=he.dims[3],V=he.dims[2]);const P=xe?.format!==void 0?xe.format:"RGB",K=xe?.norm;let ne,oe;K===void 0||K.mean===void 0?ne=[255,255,255,255]:typeof K.mean=="number"?ne=[K.mean,K.mean,K.mean,K.mean]:(ne=[K.mean[0],K.mean[1],K.mean[2],0],K.mean[3]!==void 0&&(ne[3]=K.mean[3])),K===void 0||K.bias===void 0?oe=[0,0,0,0]:typeof K.bias=="number"?oe=[K.bias,K.bias,K.bias,K.bias]:(oe=[K.bias[0],K.bias[1],K.bias[2],0],K.bias[3]!==void 0&&(oe[3]=K.bias[3]));const _e=V*$;let F=0,Q=_e,se=_e*2,le=-1;P==="RGBA"?(F=0,Q=_e,se=_e*2,le=_e*3):P==="RGB"?(F=0,Q=_e,se=_e*2):P==="RBG"&&(F=0,se=_e,Q=_e*2);for(let ie=0;ie{const be=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let R;if(be!=null){let $,V,P;xe?.tensorLayout!==void 0&&xe.tensorLayout==="NHWC"?($=he.dims[2],V=he.dims[1],P=he.dims[3]):($=he.dims[3],V=he.dims[2],P=he.dims[1]);const K=xe!==void 0&&xe.format!==void 0?xe.format:"RGB",ne=xe?.norm;let oe,_e;ne===void 0||ne.mean===void 0?oe=[255,255,255,255]:typeof ne.mean=="number"?oe=[ne.mean,ne.mean,ne.mean,ne.mean]:(oe=[ne.mean[0],ne.mean[1],ne.mean[2],255],ne.mean[3]!==void 0&&(oe[3]=ne.mean[3])),ne===void 0||ne.bias===void 0?_e=[0,0,0,0]:typeof ne.bias=="number"?_e=[ne.bias,ne.bias,ne.bias,ne.bias]:(_e=[ne.bias[0],ne.bias[1],ne.bias[2],0],ne.bias[3]!==void 0&&(_e[3]=ne.bias[3]));const F=V*$;if(xe!==void 0&&(xe.format!==void 0&&P===4&&xe.format!=="RGBA"||P===3&&xe.format!=="RGB"&&xe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const Q=4;let se=0,le=1,ie=2,j=3,A=0,L=F,C=F*2,me=-1;K==="RGBA"?(A=0,L=F,C=F*2,me=F*3):K==="RGB"?(A=0,L=F,C=F*2):K==="RBG"&&(A=0,C=F,L=F*2),R=be.createImageData($,V);for(let ye=0;ye{N.r(Me)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{bufferToTensor:()=>ae,tensorFromGpuBuffer:()=>be,tensorFromImage:()=>he,tensorFromPinnedBuffer:()=>R,tensorFromTexture:()=>xe});var I=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const ae=($,V)=>{if($===void 0)throw new Error("Image buffer must be defined");if(V.height===void 0||V.width===void 0)throw new Error("Image height and width must be defined");if(V.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:K}=V,ne=V.norm??{mean:255,bias:0};let oe,_e;typeof ne.mean=="number"?oe=[ne.mean,ne.mean,ne.mean,ne.mean]:oe=[ne.mean[0],ne.mean[1],ne.mean[2],ne.mean[3]??255],typeof ne.bias=="number"?_e=[ne.bias,ne.bias,ne.bias,ne.bias]:_e=[ne.bias[0],ne.bias[1],ne.bias[2],ne.bias[3]??0];const F=V.format!==void 0?V.format:"RGBA",Q=V.tensorFormat!==void 0&&V.tensorFormat!==void 0?V.tensorFormat:"RGB",se=P*K,le=Q==="RGBA"?new Float32Array(se*4):new Float32Array(se*3);let ie=4,j=0,A=1,L=2,C=3,me=0,ye=se,Se=se*2,Pe=-1;F==="RGB"&&(ie=3,j=0,A=1,L=2,C=-1),Q==="RGBA"?Pe=se*3:Q==="RBG"?(me=0,Se=se,ye=se*2):Q==="BGR"&&(Se=0,ye=se,me=se*2);for(let rt=0;rt{const P=typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement,K=typeof ImageData<"u"&&$ instanceof ImageData,ne=typeof ImageBitmap<"u"&&$ instanceof ImageBitmap,oe=typeof $=="string";let _e,F=V??{};const Q=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},se=le=>le instanceof HTMLCanvasElement||le instanceof OffscreenCanvas?le.getContext("2d"):null;if(P){const le=Q();le.width=$.width,le.height=$.height;const ie=se(le);if(ie!=null){let j=$.height,A=$.width;if(V!==void 0&&V.resizedHeight!==void 0&&V.resizedWidth!==void 0&&(j=V.resizedHeight,A=V.resizedWidth),V!==void 0){if(F=V,V.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");F.tensorFormat="RGBA",F.height=j,F.width=A}else F.tensorFormat="RGBA",F.height=j,F.width=A;ie.drawImage($,0,0),_e=ie.getImageData(0,0,A,j).data}else throw new Error("Can not access image data")}else if(K){let le,ie;if(V!==void 0&&V.resizedWidth!==void 0&&V.resizedHeight!==void 0?(le=V.resizedHeight,ie=V.resizedWidth):(le=$.height,ie=$.width),V!==void 0&&(F=V),F.format="RGBA",F.height=le,F.width=ie,V!==void 0){const j=Q();j.width=ie,j.height=le;const A=se(j);if(A!=null)A.putImageData($,0,0),_e=A.getImageData(0,0,ie,le).data;else throw new Error("Can not access image data")}else _e=$.data}else if(ne){if(V===void 0)throw new Error("Please provide image config with format for Imagebitmap");const le=Q();le.width=$.width,le.height=$.height;const ie=se(le);if(ie!=null){const j=$.height,A=$.width;return ie.drawImage($,0,0,A,j),_e=ie.getImageData(0,0,A,j).data,F.height=j,F.width=A,ae(_e,F)}else throw new Error("Can not access image data")}else{if(oe)return new Promise((le,ie)=>{const j=Q(),A=se(j);if(!$||!A)return ie();const L=new Image;L.crossOrigin="Anonymous",L.src=$,L.onload=()=>{j.width=L.width,j.height=L.height,A.drawImage(L,0,0,j.width,j.height);const C=A.getImageData(0,0,j.width,j.height);F.height=j.height,F.width=j.width,le(ae(C.data,F))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(_e!==void 0)return ae(_e,F);throw new Error("Input data provided is not supported - aborted tensor creation")},xe=($,V)=>{const{width:P,height:K,download:ne,dispose:oe}=V,_e=[1,K,P,4];return new I.Tensor({location:"texture",type:"float32",texture:$,dims:_e,download:ne,dispose:oe})},be=($,V)=>{const{dataType:P,dims:K,download:ne,dispose:oe}=V;return new I.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:$,dims:K,download:ne,dispose:oe})},R=($,V,P)=>new I.Tensor({location:"cpu-pinned",type:$,data:V,dims:P??[V.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(_t,Me,N)=>{N.r(Me)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>ae,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>I,checkTypedArray:()=>xe});const I=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),ae=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let he=!1;const xe=()=>{if(!he){he=!0;const be=typeof BigInt64Array<"u"&&BigInt64Array.from,R=typeof BigUint64Array<"u"&&BigUint64Array.from,$=typeof Float16Array<"u"&&Float16Array.from;be&&(I.set("int64",BigInt64Array),ae.set(BigInt64Array,"int64")),R&&(I.set("uint64",BigUint64Array),ae.set(BigUint64Array,"uint64")),$?(I.set("float16",Float16Array),ae.set(Float16Array,"float16")):I.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{Tensor:()=>be});var I=N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),ae=N("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),he=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),xe=N("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class be{constructor($,V,P){(0,he.checkTypedArray)();let K,ne;if(typeof $=="object"&&"location"in $)switch(this.dataLocation=$.location,K=$.type,ne=$.dims,$.location){case"cpu-pinned":{const _e=he.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(K);if(!_e)throw new TypeError(`unsupported type "${K}" to create tensor from pinned buffer`);if(!($.data instanceof _e))throw new TypeError(`buffer should be of type ${_e.name}`);this.cpuData=$.data;break}case"texture":{if(K!=="float32")throw new TypeError(`unsupported type "${K}" to create tensor from texture`);this.gpuTextureData=$.texture,this.downloader=$.download,this.disposer=$.dispose;break}case"gpu-buffer":{if(K!=="float32"&&K!=="float16"&&K!=="int32"&&K!=="int64"&&K!=="uint32"&&K!=="uint8"&&K!=="bool")throw new TypeError(`unsupported type "${K}" to create tensor from gpu buffer`);this.gpuBufferData=$.gpuBuffer,this.downloader=$.download,this.disposer=$.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let _e,F;if(typeof $=="string")if(K=$,F=P,$==="string"){if(!Array.isArray(V))throw new TypeError("A string tensor's data must be a string array.");_e=V}else{const Q=he.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get($);if(Q===void 0)throw new TypeError(`Unsupported tensor type: ${$}.`);if(Array.isArray(V)){if($==="float16"&&Q===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");$==="uint64"||$==="int64"?_e=Q.from(V,BigInt):_e=Q.from(V)}else if(V instanceof Q)_e=V;else throw new TypeError(`A ${K} tensor's data must be type of ${Q}`)}else if(F=V,Array.isArray($)){if($.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const Q=typeof $[0];if(Q==="string")K="string",_e=$;else if(Q==="boolean")K="bool",_e=Uint8Array.from($);else throw new TypeError(`Invalid element type of data array: ${Q}.`)}else{const Q=he.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get($.constructor);if(Q===void 0)throw new TypeError(`Unsupported type for tensor data: ${$.constructor}.`);K=Q,_e=$}if(F===void 0)F=[_e.length];else if(!Array.isArray(F))throw new TypeError("A tensor's dims must be a number array");ne=F,this.cpuData=_e,this.dataLocation="cpu"}const oe=(0,xe.calculateSize)(ne);if(this.cpuData&&oe!==this.cpuData.length)throw new Error(`Tensor's size(${oe}) does not match data length(${this.cpuData.length}).`);this.type=K,this.dims=ne,this.size=oe}static async fromImage($,V){return(0,ae.tensorFromImage)($,V)}static fromTexture($,V){return(0,ae.tensorFromTexture)($,V)}static fromGpuBuffer($,V){return(0,ae.tensorFromGpuBuffer)($,V)}static fromPinnedBuffer($,V,P){return(0,ae.tensorFromPinnedBuffer)($,V,P)}toDataURL($){return(0,I.tensorToDataURL)(this,$)}toImageData($){return(0,I.tensorToImageData)(this,$)}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}async getData($){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{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 V=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=V,$&&this.disposer&&(this.disposer(),this.disposer=void 0),V}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.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape($){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,xe.tensorReshape)(this,$)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{calculateSize:()=>ae,tensorReshape:()=>he});var I=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const ae=xe=>{let be=1;for(let R=0;R{switch(xe.location){case"cpu":return new I.Tensor(xe.type,xe.data,be);case"cpu-pinned":return new I.Tensor({location:"cpu-pinned",data:xe.data,type:xe.type,dims:be});case"texture":return new I.Tensor({location:"texture",texture:xe.texture,type:xe.type,dims:be});case"gpu-buffer":return new I.Tensor({location:"gpu-buffer",gpuBuffer:xe.gpuBuffer,type:xe.type,dims:be});default:throw new Error(`tensorReshape: tensor location ${xe.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{Tensor:()=>ae});var I=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const ae=I.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{TRACE:()=>ae,TRACE_FUNC_BEGIN:()=>xe,TRACE_FUNC_END:()=>be});var I=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const ae=(R,$)=>{(typeof I.env.trace>"u"?!I.env.wasm.trace:!I.env.trace)||console.timeStamp(`${R}::ORT::${$}`)},he=(R,$)=>{const V=new Error().stack?.split(/\r\n|\r|\n/g)||[];let P=!1;for(let K=0;K{(typeof I.env.trace>"u"?!I.env.wasm.trace:!I.env.trace)||he("BEGIN",R)},be=R=>{(typeof I.env.trace>"u"?!I.env.wasm.trace:!I.env.trace)||he("END",R)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{TrainingSession:()=>xe});var I=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),ae=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");const he="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class xe{constructor(R,$,V){this.handler=R,this.hasOptimizerModel=$,this.hasEvalModel=V}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(R,$){const V=R.evalModel||"",P=R.optimizerModel||"",K=$||{},[ne,oe]=await(0,I.resolveBackendAndExecutionProviders)(K);if(ne.createTrainingSessionHandler){const _e=await ne.createTrainingSessionHandler(R.checkpointState,R.trainModel,V,P,oe);return new xe(_e,!!R.optimizerModel,!!R.evalModel)}else throw new Error(he)}typeNarrowingForRunStep(R,$,V,P,K){const ne={};let oe={};if(typeof V!="object"||V===null||V instanceof ae.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let _e=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof ae.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(P)){if(P.length===0)throw new TypeError("'fetches' cannot be an empty array.");_e=!1;for(const F of P){if(typeof F!="string")throw new TypeError("'fetches' must be a string array or an object.");if($.indexOf(F)===-1)throw new RangeError(`'fetches' contains invalid output name: ${F}.`);ne[F]=null}if(typeof K=="object"&&K!==null)oe=K;else if(typeof K<"u")throw new TypeError("'options' must be an object.")}else{let F=!1;const Q=Object.getOwnPropertyNames(P);for(const se of $)if(Q.indexOf(se)!==-1){const le=P[se];(le===null||le instanceof ae.Tensor)&&(F=!0,_e=!1,ne[se]=le)}if(F){if(typeof K=="object"&&K!==null)oe=K;else if(typeof K<"u")throw new TypeError("'options' must be an object.")}else oe=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const F of R)if(typeof V[F]>"u")throw new Error(`input '${F}' is missing in 'feeds'.`);if(_e)for(const F of $)ne[F]=null;return[ne,oe]}convertHandlerReturnTypeToMapOfTensors(R){const $={};for(const V in R)if(Object.hasOwnProperty.call(R,V)){const P=R[V];P instanceof ae.Tensor?$[V]=P:$[V]=new ae.Tensor(P.type,P.data,P.dims)}return $}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(R,$,V){const[P,K]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,R,$,V),ne=await this.handler.runTrainStep(R,P,K);return this.convertHandlerReturnTypeToMapOfTensors(ne)}async runOptimizerStep(R){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(R||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(R,$,V){if(this.hasEvalModel){const[P,K]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,R,$,V),ne=await this.handler.runEvalStep(R,P,K);return this.convertHandlerReturnTypeToMapOfTensors(ne)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(R=!0){return this.handler.getParametersSize(R)}async loadParametersBuffer(R,$=!0){const V=await this.getParametersSize($);if(R.length!==4*V)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(R,$)}async getContiguousParameters(R=!0){return this.handler.getContiguousParameters(R)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{TrainingSession:()=>ae});var I=N("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const ae=I.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{version:()=>I});const I="1.19.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(_t,Me,N)=>{N.r(Me),N.d(Me,{InferenceSession:()=>Tt,TRACE:()=>Ee,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Fe,TrainingSession:()=>Mt,default:()=>Qf,env:()=>C,registerBackend:()=>oe});/*! * ONNX Runtime Web v1.20.0-dev.20240827-1d059b8702 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var I=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,he=Object.getOwnPropertyNames,xe=Object.prototype.hasOwnProperty,be=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),R=(e,t)=>()=>(e&&(t=e(e=0)),t),$=(e,t)=>{for(var r in t)I(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of he(t))!xe.call(e,s)&&s!==r&&I(e,s,{get:()=>t[s],enumerable:!(n=ae(t,s))||n.enumerable});return e},P=e=>V(I({},"__esModule",{value:!0}),e),K,ne,oe,_e,F,Q=R(()=>{K=new Map,ne=[],oe=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=K.get(e);if(n===void 0)K.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=ne.indexOf(e);s!==-1&&ne.splice(s,1);for(let i=0;i{let t=K.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},F=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?ne:r,s,i=[],a=new Set;for(let d of n){let c=await _e(d);typeof c=="string"?i.push({name:d,err:c}):(s||(s=c),s===c&&a.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:c}of i)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`);let u=t.filter(d=>a.has(typeof d=="string"?d:d.name));return[s,new Proxy(e,{get:(d,c)=>c==="executionProviders"?u:Reflect.get(d,c)})]}}),se=R(()=>{Q()}),le,ie=R(()=>{le="1.20.0-dev.20240827-5d54dc1462"}),j,A,L=R(()=>{ie(),j="warning",A={wasm:{},webgl:{},webgpu:{},versions:{common:le},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}`);j=e}},get logLevel(){return j}},Object.defineProperty(A,"logLevel",{enumerable:!0})}),C,me=R(()=>{L(),C=A}),ye,Se,Pe=R(()=>{ye=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],i=e.dims[3]):(s=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:"RGB",u=t?.norm,d,c;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?c=[0,0,0,0]:typeof u.bias=="number"?c=[u.bias,u.bias,u.bias,u.bias]:(c=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(c[3]=u.bias[3]));let g=i*s,l=0,y=g,v=g*2,S=-1;a==="RGBA"?(l=0,y=g,v=g*2,S=g*3):a==="RGB"?(l=0,y=g,v=g*2):a==="RBG"&&(l=0,v=g,y=g*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,i,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],i=e.dims[1],a=e.dims[3]):(s=e.dims[3],i=e.dims[2],a=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t?.norm,c,g;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?g=[0,0,0,0]:typeof d.bias=="number"?g=[d.bias,d.bias,d.bias,d.bias]:(g=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(g[3]=d.bias[3]));let l=i*s;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let y=4,v=0,S=1,x=2,G=3,q=0,k=l,Z=l*2,ee=-1;u==="RGBA"?(q=0,k=l,Z=l*2,ee=l*3):u==="RGB"?(q=0,k=l,Z=l*2):u==="RBG"&&(q=0,Z=l,k=l*2),n=r.createImageData(s,i);for(let fe=0;fe{Et(),Ce=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},i,a;typeof s.mean=="number"?i=[s.mean,s.mean,s.mean,s.mean]:i=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?a=[s.bias,s.bias,s.bias,s.bias]:a=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,g=d==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),l=4,y=0,v=1,S=2,x=3,G=0,q=c,k=c*2,Z=-1;u==="RGB"&&(l=3,y=0,v=1,S=2,x=-1),d==="RGBA"?Z=c*3:d==="RBG"?(G=0,k=c,q=c*2):d==="BGR"&&(k=0,q=c,G=c*2);for(let ee=0;ee{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",a,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=g=>g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(r){let g=d();g.width=e.width,g.height=e.height;let l=c(g);if(l!=null){let y=e.height,v=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(y=t.resizedHeight,v=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=y,u.width=v}else u.tensorFormat="RGBA",u.height=y,u.width=v;l.drawImage(e,0,0),a=l.getImageData(0,0,v,y).data}else throw new Error("Can not access image data")}else if(n){let g,l;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,l=t.resizedWidth):(g=e.height,l=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=g,u.width=l,t!==void 0){let y=d();y.width=l,y.height=g;let v=c(y);if(v!=null)v.putImageData(e,0,0),a=v.getImageData(0,0,l,g).data;else throw new Error("Can not access image data")}else a=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=d();g.width=e.width,g.height=e.height;let l=c(g);if(l!=null){let y=e.height,v=e.width;return l.drawImage(e,0,0,v,y),a=l.getImageData(0,0,v,y).data,u.height=y,u.width=v,Ce(a,u)}else throw new Error("Can not access image data")}else{if(i)return new Promise((g,l)=>{let y=d(),v=c(y);if(!e||!v)return l();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{y.width=S.width,y.height=S.height,v.drawImage(S,0,0,y.width,y.height);let x=v.getImageData(0,0,y.width,y.height);u.height=y.height,u.width=y.width,g(Ce(x.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Ce(a,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Xe=(e,t)=>{let{width:r,height:n,download:s,dispose:i}=t,a=[1,n,r,4];return new at({location:"texture",type:"float32",texture:e,dims:a,download:s,dispose:i})},dt=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:i}=t;return new at({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:i})},ge=(e,t,r)=>new at({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),de,$e,X,Ue,ct=R(()=>{de=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),$e=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),X=!1,Ue=()=>{if(!X){X=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(de.set("int64",BigInt64Array),$e.set(BigInt64Array,"int64")),t&&(de.set("uint64",BigUint64Array),$e.set(BigUint64Array,"uint64")),r?(de.set("float16",Float16Array),$e.set(Float16Array,"float16")):de.set("float16",Uint16Array)}}}),st,ot,De=R(()=>{Et(),st=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new at(e.type,e.data,t);case"cpu-pinned":return new at({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new at({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new at({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),at,Et=R(()=>{Pe(),U(),ct(),De(),at=class{constructor(e,t,r){Ue();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let a=de.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.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}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let d=de.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?a=d.from(t,BigInt):a=d.from(t)}else if(t instanceof d)a=t;else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",a=e;else if(d==="boolean")n="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{let d=$e.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,a=e}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=a,this.dataLocation="cpu"}let i=st(s);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=i}static async fromImage(e,t){return rt(e,t)}static fromTexture(e,t){return Xe(e,t)}static fromGpuBuffer(e,t){return dt(e,t)}static fromPinnedBuffer(e,t,r){return ge(e,t,r)}toDataURL(e){return ye(this,e)}toImageData(e){return Se(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}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{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.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 ot(this,e)}}}),Fe,H=R(()=>{Et(),Fe=at}),Ee,qe,je,Ve,Ge=R(()=>{L(),Ee=(e,t)=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeStamp(`${e}::ORT::${t}`)},qe=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||qe("BEGIN",e)},Ve=e=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||qe("END",e)}}),ut,ht=R(()=>{Q(),H(),Ge(),ut=class Ef{constructor(t){this.handler=t}async run(t,r,n){je();let s={},i={};if(typeof t!="object"||t===null||t instanceof Fe||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Fe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,g=Object.getOwnPropertyNames(r);for(let l of this.outputNames)if(g.indexOf(l)!==-1){let y=r[l];(y===null||y instanceof Fe)&&(c=!0,a=!1,s[l]=y)}if(c){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)s[c]=null;let u=await this.handler.run(t,s,i),d={};for(let c in u)if(Object.hasOwnProperty.call(u,c)){let g=u[c];g instanceof Fe?d[c]=g:d[c]=new Fe(g.type,g.data,g.dims)}return Ve(),d}async release(){return this.handler.dispose()}static async create(t,r,n,s){je();let i,a={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,l=0,y=t.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(l=r,!Number.isSafeInteger(l))throw new RangeError("'byteOffset' must be an integer.");if(l<0||l>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(y=t.byteLength-l,typeof n=="number"){if(y=n,!Number.isSafeInteger(y))throw new RangeError("'byteLength' must be an integer.");if(y<=0||l+y>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-l}].`);if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(g,l,y)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await F(a),c=await u.createInferenceSessionHandler(i,d);return Ve(),new Ef(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Tt,St=R(()=>{ht(),Tt=ut}),M=R(()=>{}),W=R(()=>{}),E=R(()=>{}),te=R(()=>{}),pe,Je,He=R(()=>{Q(),H(),pe="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class Cf{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}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(t,r){let n=t.evalModel||"",s=t.optimizerModel||"",i=r||{},[a,u]=await F(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,u);return new Cf(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(pe)}typeNarrowingForRunStep(t,r,n,s,i){let a={},u={};if(typeof n!="object"||n===null||n instanceof Fe||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof Fe)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.");d=!1;for(let c of s){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);a[c]=null}if(typeof i=="object"&&i!==null)u=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,g=Object.getOwnPropertyNames(s);for(let l of r)if(g.indexOf(l)!==-1){let y=s[l];(y===null||y instanceof Fe)&&(c=!0,d=!1,a[l]=y)}if(c){if(typeof i=="object"&&i!==null)u=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else u=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of t)if(typeof n[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)a[c]=null;return[a,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof Fe?r[n]=s:r[n]=new Fe(s.type,s.data,s.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[s,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,s,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[s,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,s,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)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(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),Mt,nt=R(()=>{He(),Mt=Je}),pt={};$(pt,{InferenceSession:()=>Tt,TRACE:()=>Ee,TRACE_FUNC_BEGIN:()=>je,TRACE_FUNC_END:()=>Ve,Tensor:()=>Fe,TrainingSession:()=>Mt,env:()=>C,registerBackend:()=>oe});var Bt=R(()=>{se(),me(),St(),H(),M(),W(),Ge(),E(),te(),nt()}),et=R(()=>{}),B={};$(B,{default:()=>Re});var ce,Te,Re,ke=R(()=>{jp(),pn(),rr(),ce="ort-wasm-proxy-worker",Te=globalThis.self?.name===ce,Te&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":is(r.wasm).then(()=>{Jd(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:s}=r;ec(s,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=r,s=xd(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;tc(n,s).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":rc(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:i,outputIndices:a,options:u}=r;sc(n,s,i,a,new Array(a.length).fill(null),u).then(d=>{d.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},ac([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":ic(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),Re=Te?null:e=>new Worker(e??ze,{type:"module",name:ce})}),tt={};$(tt,{default:()=>Ct});var ft,lt,Ct,gt=R(()=>{lt=(ft=import.meta.url,async function(e={}){function t(){return hr.buffer!=Br.buffer&&$n(),Br}function r(){return hr.buffer!=Br.buffer&&$n(),tr}function n(){return hr.buffer!=Br.buffer&&$n(),gr}function s(){return hr.buffer!=Br.buffer&&$n(),Ke}function i(){return hr.buffer!=Br.buffer&&$n(),$t}function a(){return hr.buffer!=Br.buffer&&$n(),cr}function u(){return hr.buffer!=Br.buffer&&$n(),Vr}function d(){return hr.buffer!=Br.buffer&&$n(),Kn}var c,g,l=Object.assign({},e),y=new Promise((o,f)=>{c=o,g=f}),v=typeof window=="object",S=typeof importScripts=="function",x=S&&self.name=="em-pthread";l.mountExternalData=(o,f)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Fb||(l.Fb=new Map)).set(o,f)},l.unmountExternalData=()=>{delete l.Fb};var G=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let q=()=>{let o=(w,T,O)=>(...ue)=>{let Le=ns,it=T?.();ue=w(...ue);let It=T?.();return it!==It&&(w=It,O(it),T=O=null),ns!=Le?new Promise((Dt,Qt)=>{Tc={resolve:Dt,reject:Qt}}):ue},f=w=>async(...T)=>{try{if(l.Eb)throw Error("Session already started");let O=l.Eb={bc:T[0],errors:[]},ue=await w(...T);if(l.Eb!==O)throw Error("Session mismatch");l.Mb?.flush();let Le=O.errors;if(0It),0l._OrtCreateSession,w=>l._OrtCreateSession=w),l._OrtRun=f(o(l._OrtRun,()=>l._OrtRun,w=>l._OrtRun=w)),l._OrtRunWithBinding=f(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,w=>l._OrtRunWithBinding=w)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,w=>l._OrtBindInput=w),q=void 0};l.jsepInit=(o,f)=>{if(q?.(),o==="webgpu"){[l.Mb,l.Tb,l.Xb,l.Nb,l.Wb,l.jb,l.Yb,l.$b,l.Ub,l.Vb,l.Zb]=f;let w=l.Mb;l.jsepRegisterBuffer=(T,O,ue,Le)=>w.registerBuffer(T,O,ue,Le),l.jsepGetBuffer=T=>w.getBuffer(T),l.jsepCreateDownloader=(T,O,ue)=>w.createDownloader(T,O,ue),l.jsepOnReleaseSession=T=>{w.onReleaseSession(T)},l.jsepOnRunStart=T=>w.onRunStart(T)}};var k,Z,ee=Object.assign({},l),fe="./this.program",We=(o,f)=>{throw f},Ne="";(v||S)&&(S?Ne=self.location.href:typeof document<"u"&&document.currentScript&&(Ne=document.currentScript.src),ft&&(Ne=ft),Ne=Ne.startsWith("blob:")?"":Ne.substr(0,Ne.replace(/[?#].*/,"").lastIndexOf("/")+1),S&&(Z=o=>{var f=new XMLHttpRequest;return f.open("GET",o,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),k=(o,f,w)=>{var T=new XMLHttpRequest;T.open("GET",o,!0),T.responseType="arraybuffer",T.onload=()=>{T.status==200||T.status==0&&T.response?f(T.response):w()},T.onerror=w,T.send(null)});var mt,jt=console.log.bind(console),Lt=console.error.bind(console),dr=jt,ar=Lt;if(Object.assign(l,ee),ee=null,x){let o=function(f){try{var w=f.data,T=w.cmd;if(T==="load"){let O=[];self.onmessage=ue=>O.push(ue),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ue of O)o(ue);self.onmessage=o};for(let ue of w.handlers)l[ue]&&!l[ue].proxy||(l[ue]=(...Le)=>{postMessage({Lb:"callHandler",kc:ue,args:Le})},ue=="print"&&(dr=l[ue]),ue=="printErr"&&(ar=l[ue]));hr=w.wasmMemory,$n(),_r(w.wasmModule)}else if(T==="run"){Cc(w.pthread_ptr,0,0,1,0,0),Mc(w.pthread_ptr),Jf(),hh(),Pr||(cf(),Pr=!0);try{em(w.start_routine,w.arg)}catch(O){if(O!="unwind")throw O}}else T==="cancel"?Aa()&&Dd(-1):w.target!=="setimmediate"&&(T==="checkMailbox"?Pr&&Ed():T&&(ar(`worker: received unknown command ${T}`),ar(w)))}catch(O){throw pf(),O}};var _r,Pr=!1;ar=function(...f){f=f.join(" "),console.error(f)},self.alert=function(...f){postMessage({Lb:"alert",text:f.join(" "),mc:Aa()})},l.instantiateWasm=(f,w)=>new Promise(T=>{_r=O=>{O=new WebAssembly.Instance(O,lh()),w(O),T()}}),self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=o}l.wasmBinary&&(mt=l.wasmBinary);var hr,Yt,Ar,Br,tr,gr,Ke,$t,cr,Vr,Ur,Rn,Kn,An=!1;function $n(){var o=hr.buffer;l.HEAP8=Br=new Int8Array(o),l.HEAP16=gr=new Int16Array(o),l.HEAPU8=tr=new Uint8Array(o),l.HEAPU16=Ke=new Uint16Array(o),l.HEAP32=$t=new Int32Array(o),l.HEAPU32=cr=new Uint32Array(o),l.HEAPF32=Vr=new Float32Array(o),l.HEAPF64=Kn=new Float64Array(o),l.HEAP64=Ur=new BigInt64Array(o),l.HEAPU64=Rn=new BigUint64Array(o)}if(!x){if(!((hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof G))throw ar("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");$n()}var gn=[],cn=[],Bs=[],Ls=0,hi=null;function nh(){if(--Ls==0&&hi){var o=hi;hi=null,o()}}function Ca(o){throw ar(o="Aborted("+o+")"),An=!0,Ar=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),g(o),o}var uc,sh=o=>o.startsWith("data:application/octet-stream;base64,"),ih=o=>o.startsWith("file://");function ah(o){if(o==uc&&mt)return new Uint8Array(mt);if(Z)return Z(o);throw"both async and sync fetching of the wasm failed"}function oh(o,f,w){return function(T){if(!mt&&(v||S)){if(typeof fetch=="function"&&!ih(T))return fetch(T,{credentials:"same-origin"}).then(O=>{if(!O.ok)throw`failed to load wasm binary file at '${T}'`;return O.arrayBuffer()}).catch(()=>ah(T));if(k)return new Promise((O,ue)=>{k(T,Le=>O(new Uint8Array(Le)),ue)})}return Promise.resolve().then(()=>ah(T))}(o).then(T=>WebAssembly.instantiate(T,f)).then(w,T=>{ar(`failed to asynchronously prepare wasm: ${T}`),Ca(T)})}function lh(){return{a:{M:Zf,za:Yf,b:rm,$:gh,z:bh,pa:Mh,X:xh,Z:Th,qa:Sh,na:$h,ga:Eh,ma:Ch,J:kh,Y:Ph,V:Ah,oa:Ih,W:Fh,va:nm,D:sm,P:im,O:om,C:um,s:dm,p:cm,E:pm,y:ym,Q:bm,ta:Mm,ja:vm,T:xm,aa:Tm,F:Sm,ia:Mc,sa:$m,u:Em,B:Pm,o:Am,m:Fm,c:yc,n:Om,k:Bm,Aa:Lm,r:Rm,g:Nm,v:jm,l:Vm,f:Um,i:Wm,j:Gm,h:qm,e:Hm,da:Km,ea:Xm,fa:Qm,ba:Hh,ca:Kh,S:Ym,d:Zm,N:Jm,G:e_,K:t_,w:r_,ra:n_,U:s_,t:Qh,x:i_,L:a_,R:o_,ya:l_,xa:u_,ka:Jh,la:ef,_:fc,A:tf,I:rf,ha:nf,H:sf,a:hr,wa:hc,ua:lf,q:p_}}}var dc={858916:(o,f,w,T)=>{if(l===void 0||!l.Fb)return 1;if((o=un(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Fb.get(o)))return 2;if(T>>>=0,(f>>>=0)+(w>>>=0)>o.byteLength)return 3;try{return r().set(o.subarray(f,f+w),T>>>0),0}catch{return 4}},859417:()=>{l.Ub()},859448:()=>{l.Vb()},859477:()=>{l.Zb()},859502:o=>l.Tb(o),859535:o=>l.Xb(o),859567:(o,f,w)=>{l.Nb(o,f,w,!0)},859606:(o,f,w)=>{l.Nb(o,f,w)},859639:()=>typeof wasmOffsetConverter<"u",859696:o=>{l.jb("Abs",o,void 0)},859747:o=>{l.jb("Neg",o,void 0)},859798:o=>{l.jb("Floor",o,void 0)},859851:o=>{l.jb("Ceil",o,void 0)},859903:o=>{l.jb("Reciprocal",o,void 0)},859961:o=>{l.jb("Sqrt",o,void 0)},860013:o=>{l.jb("Exp",o,void 0)},860064:o=>{l.jb("Erf",o,void 0)},860115:o=>{l.jb("Sigmoid",o,void 0)},860170:(o,f,w)=>{l.jb("HardSigmoid",o,{alpha:f,beta:w})},860249:o=>{l.jb("Log",o,void 0)},860300:o=>{l.jb("Sin",o,void 0)},860351:o=>{l.jb("Cos",o,void 0)},860402:o=>{l.jb("Tan",o,void 0)},860453:o=>{l.jb("Asin",o,void 0)},860505:o=>{l.jb("Acos",o,void 0)},860557:o=>{l.jb("Atan",o,void 0)},860609:o=>{l.jb("Sinh",o,void 0)},860661:o=>{l.jb("Cosh",o,void 0)},860713:o=>{l.jb("Asinh",o,void 0)},860766:o=>{l.jb("Acosh",o,void 0)},860819:o=>{l.jb("Atanh",o,void 0)},860872:o=>{l.jb("Tanh",o,void 0)},860924:o=>{l.jb("Not",o,void 0)},860975:(o,f,w)=>{l.jb("Clip",o,{min:f,max:w})},861044:o=>{l.jb("Clip",o,void 0)},861096:(o,f)=>{l.jb("Elu",o,{alpha:f})},861154:o=>{l.jb("Gelu",o,void 0)},861206:o=>{l.jb("Relu",o,void 0)},861258:(o,f)=>{l.jb("LeakyRelu",o,{alpha:f})},861322:(o,f)=>{l.jb("ThresholdedRelu",o,{alpha:f})},861392:(o,f)=>{l.jb("Cast",o,{to:f})},861450:o=>{l.jb("Add",o,void 0)},861501:o=>{l.jb("Sub",o,void 0)},861552:o=>{l.jb("Mul",o,void 0)},861603:o=>{l.jb("Div",o,void 0)},861654:o=>{l.jb("Pow",o,void 0)},861705:o=>{l.jb("Equal",o,void 0)},861758:o=>{l.jb("Greater",o,void 0)},861813:o=>{l.jb("GreaterOrEqual",o,void 0)},861875:o=>{l.jb("Less",o,void 0)},861927:o=>{l.jb("LessOrEqual",o,void 0)},861986:(o,f,w,T,O)=>{l.jb("ReduceMean",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},862145:(o,f,w,T,O)=>{l.jb("ReduceMax",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},862303:(o,f,w,T,O)=>{l.jb("ReduceMin",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},862461:(o,f,w,T,O)=>{l.jb("ReduceProd",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},862620:(o,f,w,T,O)=>{l.jb("ReduceSum",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},862778:(o,f,w,T,O)=>{l.jb("ReduceL1",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},862935:(o,f,w,T,O)=>{l.jb("ReduceL2",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},863092:(o,f,w,T,O)=>{l.jb("ReduceLogSum",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},863253:(o,f,w,T,O)=>{l.jb("ReduceSumSquare",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},863417:(o,f,w,T,O)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!f,noopWithEmptyAxes:!!w,axes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},863581:o=>{l.jb("Where",o,void 0)},863634:(o,f,w)=>{l.jb("Transpose",o,{perm:f?Array.from(i().subarray(f>>>0,w>>>0)):[]})},863742:(o,f,w,T)=>{l.jb("DepthToSpace",o,{blocksize:f,mode:un(w),format:T?"NHWC":"NCHW"})},863875:(o,f,w,T)=>{l.jb("DepthToSpace",o,{blocksize:f,mode:un(w),format:T?"NHWC":"NCHW"})},864008:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae,vr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:f,dilations:[w],group:T,kernelShape:[O],pads:[ue,Le],strides:[it],wIsConst:()=>!!t()[Dt>>>0],outputPadding:Qt?Array.from(i().subarray(Qt>>>0,$r>>>0)):[],outputShape:zr?Array.from(i().subarray(zr>>>0,Ae>>>0)):[],activation:un(vr)})},864409:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(w>>>0,2+(w>>>0)>>>0)),group:T,kernelShape:Array.from(i().subarray(O>>>0,2+(O>>>0)>>>0)),pads:Array.from(i().subarray(ue>>>0,4+(ue>>>0)>>>0)),strides:Array.from(i().subarray(Le>>>0,2+(Le>>>0)>>>0)),wIsConst:()=>!!t()[It>>>0],outputPadding:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],outputShape:$r?Array.from(i().subarray($r>>>0,zr>>>0)):[],activation:un(Ae)})},864974:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae,vr)=>{l.jb("ConvTranspose",o,{format:It?"NHWC":"NCHW",autoPad:f,dilations:[w],group:T,kernelShape:[O],pads:[ue,Le],strides:[it],wIsConst:()=>!!t()[Dt>>>0],outputPadding:Qt?Array.from(i().subarray(Qt>>>0,$r>>>0)):[],outputShape:zr?Array.from(i().subarray(zr>>>0,Ae>>>0)):[],activation:un(vr)})},865375:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(w>>>0,2+(w>>>0)>>>0)),group:T,kernelShape:Array.from(i().subarray(O>>>0,2+(O>>>0)>>>0)),pads:Array.from(i().subarray(ue>>>0,4+(ue>>>0)>>>0)),strides:Array.from(i().subarray(Le>>>0,2+(Le>>>0)>>>0)),wIsConst:()=>!!t()[It>>>0],outputPadding:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],outputShape:$r?Array.from(i().subarray($r>>>0,zr>>>0)):[],activation:un(Ae)})},865940:(o,f)=>{l.jb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},866031:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae)=>{l.jb("AveragePool",o,{format:Ae?"NHWC":"NCHW",auto_pad:f,ceil_mode:w,count_include_pad:T,storage_order:O,dilations:ue?Array.from(i().subarray(ue>>>0,Le>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],strides:$r?Array.from(i().subarray($r>>>0,zr>>>0)):[]})},866446:(o,f)=>{l.jb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},866537:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae)=>{l.jb("AveragePool",o,{format:Ae?"NHWC":"NCHW",auto_pad:f,ceil_mode:w,count_include_pad:T,storage_order:O,dilations:ue?Array.from(i().subarray(ue>>>0,Le>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],strides:$r?Array.from(i().subarray($r>>>0,zr>>>0)):[]})},866952:(o,f)=>{l.jb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},867039:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae)=>{l.jb("MaxPool",o,{format:Ae?"NHWC":"NCHW",auto_pad:f,ceil_mode:w,count_include_pad:T,storage_order:O,dilations:ue?Array.from(i().subarray(ue>>>0,Le>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],strides:$r?Array.from(i().subarray($r>>>0,zr>>>0)):[]})},867450:(o,f)=>{l.jb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},867537:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae)=>{l.jb("MaxPool",o,{format:Ae?"NHWC":"NCHW",auto_pad:f,ceil_mode:w,count_include_pad:T,storage_order:O,dilations:ue?Array.from(i().subarray(ue>>>0,Le>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,It>>>0)):[],pads:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],strides:$r?Array.from(i().subarray($r>>>0,zr>>>0)):[]})},867948:(o,f,w,T,O)=>{l.jb("Gemm",o,{alpha:f,beta:w,transA:T,transB:O})},868052:o=>{l.jb("MatMul",o,void 0)},868106:(o,f,w,T)=>{l.jb("ArgMax",o,{keepDims:!!f,selectLastIndex:!!w,axis:T})},868214:(o,f,w,T)=>{l.jb("ArgMin",o,{keepDims:!!f,selectLastIndex:!!w,axis:T})},868322:(o,f)=>{l.jb("Softmax",o,{axis:f})},868385:(o,f)=>{l.jb("Concat",o,{axis:f})},868445:(o,f,w,T,O)=>{l.jb("Split",o,{axis:f,numOutputs:w,splitSizes:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},868585:o=>{l.jb("Expand",o,void 0)},868639:(o,f)=>{l.jb("Gather",o,{axis:Number(f)})},868710:(o,f)=>{l.jb("GatherElements",o,{axis:Number(f)})},868789:(o,f,w,T,O,ue,Le,it,It,Dt,Qt)=>{l.jb("Resize",o,{antialias:f,axes:w?Array.from(i().subarray(w>>>0,T>>>0)):[],coordinateTransformMode:un(O),cubicCoeffA:ue,excludeOutside:Le,extrapolationValue:it,keepAspectRatioPolicy:un(It),mode:un(Dt),nearestMode:un(Qt)})},869135:(o,f,w,T,O,ue,Le)=>{l.jb("Slice",o,{starts:f?Array.from(i().subarray(f>>>0,w>>>0)):[],ends:T?Array.from(i().subarray(T>>>0,O>>>0)):[],axes:ue?Array.from(i().subarray(ue>>>0,Le>>>0)):[]})},869351:o=>{l.jb("Tile",o,void 0)},869403:(o,f,w)=>{l.jb("InstanceNormalization",o,{epsilon:f,format:w?"NHWC":"NCHW"})},869517:(o,f,w)=>{l.jb("InstanceNormalization",o,{epsilon:f,format:w?"NHWC":"NCHW"})},869631:o=>{l.jb("Range",o,void 0)},869684:(o,f)=>{l.jb("Einsum",o,{equation:un(f)})},869765:(o,f,w,T,O)=>{l.jb("Pad",o,{mode:f,value:w,pads:T?Array.from(i().subarray(T>>>0,O>>>0)):[]})},869892:(o,f,w,T,O,ue)=>{l.jb("BatchNormalization",o,{epsilon:f,momentum:w,spatial:!!O,trainingMode:!!T,format:ue?"NHWC":"NCHW"})},870061:(o,f,w,T,O,ue)=>{l.jb("BatchNormalization",o,{epsilon:f,momentum:w,spatial:!!O,trainingMode:!!T,format:ue?"NHWC":"NCHW"})},870230:(o,f,w)=>{l.jb("CumSum",o,{exclusive:Number(f),reverse:Number(w)})},870327:(o,f,w)=>{l.jb("DequantizeLinear",o,{axis:f,blockSize:w})},870417:(o,f,w,T,O,ue,Le,it,It)=>{l.jb("Attention",o,{numHeads:f,isUnidirectional:w,maskFilterValue:T,scale:O,doRotary:ue,qkvHiddenSizes:Le?Array.from(i().subarray(Number(it)>>>0,Number(it)+Le>>>0)):[],pastPresentShareBuffer:!!It})},870689:o=>{l.jb("BiasAdd",o,void 0)},870744:o=>{l.jb("BiasSplitGelu",o,void 0)},870805:o=>{l.jb("FastGelu",o,void 0)},870861:(o,f,w,T,O,ue,Le,it,It,Dt,Qt,$r,zr,Ae,vr,Yr)=>{l.jb("Conv",o,{format:$r?"NHWC":"NCHW",auto_pad:f,dilations:w?Array.from(i().subarray(w>>>0,T>>>0)):[],group:O,kernel_shape:ue?Array.from(i().subarray(ue>>>0,Le>>>0)):[],pads:it?Array.from(i().subarray(it>>>0,It>>>0)):[],strides:Dt?Array.from(i().subarray(Dt>>>0,Qt>>>0)):[],w_is_const:()=>!!t()[zr>>>0],activation:un(Ae),activation_params:vr?Array.from(u().subarray(vr>>>0,Yr>>>0)):[]})},871357:o=>{l.jb("Gelu",o,void 0)},871409:(o,f,w,T)=>{l.jb("GroupQueryAttention",o,{numHeads:f,kvNumHeads:w,scale:T})},871522:(o,f,w,T)=>{l.jb("LayerNormalization",o,{axis:f,epsilon:w,simplified:!!T})},871633:(o,f,w,T)=>{l.jb("LayerNormalization",o,{axis:f,epsilon:w,simplified:!!T})},871744:(o,f,w,T,O,ue)=>{l.jb("MatMulNBits",o,{k:f,n:w,accuracyLevel:T,bits:O,blockSize:ue})},871871:(o,f,w,T,O,ue)=>{l.jb("MultiHeadAttention",o,{numHeads:f,isUnidirectional:w,maskFilterValue:T,scale:O,doRotary:ue})},872030:(o,f)=>{l.jb("QuickGelu",o,{alpha:f})},872094:(o,f,w,T,O)=>{l.jb("RotaryEmbedding",o,{interleaved:!!f,numHeads:w,rotaryEmbeddingDim:T,scale:O})},872233:(o,f,w)=>{l.jb("SkipLayerNormalization",o,{epsilon:f,simplified:!!w})},872335:(o,f,w)=>{l.jb("SkipLayerNormalization",o,{epsilon:f,simplified:!!w})},872437:(o,f,w,T)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:f,quantizeAxis:w,blockSize:T})},872558:o=>{l.Yb(o)},872592:(o,f)=>l.$b(o,f,l.Eb.bc,l.Eb.errors)};function Yf(o,f,w){return Vh(async()=>{await l.Wb(o,f,w)})}function Zf(){return typeof wasmOffsetConverter<"u"}function cc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var pc=o=>{o.terminate(),o.onmessage=()=>{}},uh=o=>{Rs.length==0&&(mh(),fh(Rs[0]));var f=Rs.pop();if(!f)return 6;mi.push(f),ts[o.Ab]=f,f.Ab=o.Ab;var w={cmd:"run",start_routine:o.cc,arg:o.Pb,pthread_ptr:o.Ab};return f.postMessage(w,o.ic),0},fi=0,Kr=(o,f,...w)=>{for(var T=2*w.length,O=Ac(),ue=Pc(8*T),Le=ue>>>3,it=0;it>>0]=It)}return o=hf(o,0,T,ue,f),Bd(O),o};function hc(o){if(x)return Kr(0,1,o);if(Ar=o,!(0{if(Ar=o,x)throw dh(o),"unwind";hc(o)},Rs=[],mi=[],ch=[],ts={},ph=o=>{var f=o.Ab;delete ts[f],Rs.push(o),mi.splice(mi.indexOf(o),1),o.Ab=0,kc(f)};function hh(){ch.forEach(o=>o())}var fh=o=>new Promise(f=>{o.onmessage=O=>{var ue=(O=O.data).cmd;if(O.targetThread&&O.targetThread!=Aa()){var Le=ts[O.targetThread];Le?Le.postMessage(O,O.transferList):ar(`Internal error! Worker sent a message "${ue}" to target pthread ${O.targetThread}, but that thread no longer exists!`)}else ue==="checkMailbox"?Ed():ue==="spawnThread"?uh(O):ue==="cleanupThread"?ph(ts[O.thread]):ue==="killThread"?(O=O.thread,ue=ts[O],delete ts[O],pc(ue),kc(O),mi.splice(mi.indexOf(ue),1),ue.Ab=0):ue==="cancelThread"?ts[O.thread].postMessage({cmd:"cancel"}):ue==="loaded"?(o.loaded=!0,f(o)):ue==="alert"?alert(`Thread ${O.threadId}: ${O.text}`):O.target==="setimmediate"?o.postMessage(O):ue==="callHandler"?l[O.handler](...O.args):ue&&ar(`worker sent an unknown command ${ue}`)},o.onerror=O=>{throw ar(`worker sent an error! ${O.filename}:${O.lineno}: ${O.message}`),O};var w,T=[];for(w of[])l.hasOwnProperty(w)&&T.push(w);o.postMessage({cmd:"load",handlers:T,wasmMemory:hr,wasmModule:Yt})});function mh(){var o=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Rs.push(o)}var $d=o=>{for(;0{var o=Aa(),f=a()[o+52>>>2>>>0];o=a()[o+56>>>2>>>0],mf(f,f-o),Bd(f)},em=(o,f)=>{fi=0,o=_f(o,f),0>>=0);throw f>>>=0,w>>>=0,a()[T.Ib+16>>>2>>>0]=0,a()[T.Ib+4>>>2>>>0]=f,a()[T.Ib+8>>>2>>>0]=w,o}function _h(o,f,w,T){return x?Kr(2,1,o,f,w,T):gh(o,f,w,T)}function gh(o,f,w,T){if(o>>>=0,f>>>=0,w>>>=0,T>>>=0,G===void 0)return ar("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var O=[];return x&&O.length===0?_h(o,f,w,T):(o={cc:w,Ab:o,Pb:T,ic:O},x?(o.Lb="spawnThread",postMessage(o,O),0):uh(o))}var wh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,yh=(o,f,w)=>{var T=(f>>>=0)+w;for(w=f;o[w]&&!(w>=T);)++w;if(16(O=(240&O)==224?(15&O)<<12|ue<<6|Le:(7&O)<<18|ue<<12|Le<<6|63&o[f++])?T+=String.fromCharCode(O):(O-=65536,T+=String.fromCharCode(55296|O>>10,56320|1023&O))}}else T+=String.fromCharCode(O)}return T},un=(o,f)=>(o>>>=0)?yh(r(),o,f):"";function bh(o,f,w){return x?Kr(3,1,o,f,w):0}function Mh(o,f){if(x)return Kr(4,1,o,f)}var mc=o=>{for(var f=0,w=0;w=T?f++:2047>=T?f+=2:55296<=T&&57343>=T?(f+=4,++w):f+=3}return f},vh=(o,f,w,T)=>{if(!(0>>=0;T=w+T-1;for(var ue=0;ue=Le&&(Le=65536+((1023&Le)<<10)|1023&o.charCodeAt(++ue)),127>=Le){if(w>=T)break;f[w++>>>0]=Le}else{if(2047>=Le){if(w+1>=T)break;f[w++>>>0]=192|Le>>6}else{if(65535>=Le){if(w+2>=T)break;f[w++>>>0]=224|Le>>12}else{if(w+3>=T)break;f[w++>>>0]=240|Le>>18,f[w++>>>0]=128|Le>>12&63}f[w++>>>0]=128|Le>>6&63}f[w++>>>0]=128|63&Le}}return f[w>>>0]=0,w-O},ka=(o,f,w)=>vh(o,r(),f,w);function xh(o,f){if(x)return Kr(5,1,o,f)}function Th(o,f,w){if(x)return Kr(6,1,o,f,w)}function Sh(o,f,w){return x?Kr(7,1,o,f,w):0}function $h(o,f){if(x)return Kr(8,1,o,f)}function Eh(o,f,w){if(x)return Kr(9,1,o,f,w)}function Ch(o,f,w,T){if(x)return Kr(10,1,o,f,w,T)}function kh(o,f,w,T){if(x)return Kr(11,1,o,f,w,T)}function Ph(o,f,w,T){if(x)return Kr(12,1,o,f,w,T)}function Ah(o){if(x)return Kr(13,1,o)}function Ih(o,f){if(x)return Kr(14,1,o,f)}function Fh(o,f,w){if(x)return Kr(15,1,o,f,w)}var Oh,Ns,nm=()=>{Ca("")},rs=o=>{for(var f="";r()[o>>>0];)f+=Oh[r()[o++>>>0]];return f},_c={},gc={};function _s(o,f,w={}){if(!("argPackAdvance"in f))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(T,O,ue={}){var Le=O.name;if(!T)throw new Ns(`type "${Le}" must have a positive integer typeid pointer`);if(gc.hasOwnProperty(T)){if(ue.Rb)return;throw new Ns(`Cannot register type '${Le}' twice`)}gc[T]=O,_c.hasOwnProperty(T)&&(O=_c[T],delete _c[T],O.forEach(it=>it()))}(o,f,w)}var zh=(o,f,w)=>{switch(f){case 1:return w?T=>t()[T>>>0]:T=>r()[T>>>0];case 2:return w?T=>n()[T>>>1>>>0]:T=>s()[T>>>1>>>0];case 4:return w?T=>i()[T>>>2>>>0]:T=>a()[T>>>2>>>0];case 8:return w?T=>Ur[T>>>3]:T=>Rn[T>>>3];default:throw new TypeError(`invalid integer width (${f}): ${o}`)}};function sm(o,f,w){w>>>=0,_s(o>>>=0,{name:f=rs(f>>>0),fromWireType:T=>T,toWireType:function(T,O){if(typeof O!="bigint"&&typeof O!="number")throw O=O===null?"null":(T=typeof O)=="object"||T==="array"||T==="function"?O.toString():""+O,new TypeError(`Cannot convert "${O}" to ${this.name}`);return typeof O=="number"&&(O=BigInt(O)),O},argPackAdvance:js,readValueFromPointer:zh(f,w,f.indexOf("u")==-1),Db:null})}var js=8;function im(o,f,w,T){_s(o>>>=0,{name:f=rs(f>>>0),fromWireType:function(O){return!!O},toWireType:function(O,ue){return ue?w:T},argPackAdvance:js,readValueFromPointer:function(O){return this.fromWireType(r()[O>>>0])},Db:null})}var wc=[],gs=[];function yc(o){9<(o>>>=0)&&--gs[o+1]==0&&(gs[o]=void 0,wc.push(o))}var Nn=o=>{if(!o)throw new Ns("Cannot use deleted val. handle = "+o);return gs[o]},jn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=wc.pop()||gs.length;return gs[f]=o,gs[f+1]=1,f}};function bc(o){return this.fromWireType(a()[o>>>2>>>0])}var am={name:"emscripten::val",fromWireType:o=>{var f=Nn(o);return yc(o),f},toWireType:(o,f)=>jn(f),argPackAdvance:js,readValueFromPointer:bc,Db:null};function om(o){return _s(o>>>0,am)}var lm=(o,f)=>{switch(f){case 4:return function(w){return this.fromWireType(u()[w>>>2>>>0])};case 8:return function(w){return this.fromWireType(d()[w>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${o}`)}};function um(o,f,w){w>>>=0,_s(o>>>=0,{name:f=rs(f>>>0),fromWireType:T=>T,toWireType:(T,O)=>O,argPackAdvance:js,readValueFromPointer:lm(f,w),Db:null})}function dm(o,f,w,T,O){if(o>>>=0,w>>>=0,f=rs(f>>>0),O===-1&&(O=4294967295),O=it=>it,T===0){var ue=32-8*w;O=it=>it<>>ue}var Le=f.includes("unsigned")?function(it,It){return It>>>0}:function(it,It){return It};_s(o,{name:f,fromWireType:O,toWireType:Le,argPackAdvance:js,readValueFromPointer:zh(f,w,T!==0),Db:null})}function cm(o,f,w){function T(ue){var Le=a()[ue>>>2>>>0];return ue=a()[ue+4>>>2>>>0],new O(t().buffer,ue,Le)}var O=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];_s(o>>>=0,{name:w=rs(w>>>0),fromWireType:T,argPackAdvance:js,readValueFromPointer:T},{Rb:!0})}function pm(o,f){o>>>=0;var w=(f=rs(f>>>0))==="std::string";_s(o,{name:f,fromWireType:function(T){var O=a()[T>>>2>>>0],ue=T+4;if(w)for(var Le=ue,it=0;it<=O;++it){var It=ue+it;if(it==O||r()[It>>>0]==0){if(Le=un(Le,It-Le),Dt===void 0)var Dt=Le;else Dt+="\0",Dt+=Le;Le=It+1}}else{for(Dt=Array(O),it=0;it>>0]);Dt=Dt.join("")}return ss(T),Dt},toWireType:function(T,O){O instanceof ArrayBuffer&&(O=new Uint8Array(O));var ue=typeof O=="string";if(!(ue||O instanceof Uint8Array||O instanceof Uint8ClampedArray||O instanceof Int8Array))throw new Ns("Cannot pass non-string to std::string");var Le=w&&ue?mc(O):O.length,it=zd(4+Le+1),It=it+4;if(a()[it>>>2>>>0]=Le,w&&ue)ka(O,It,Le+1);else if(ue)for(ue=0;ue>>0]=Dt}else for(ue=0;ue>>0]=O[ue];return T!==null&&T.push(ss,it),it},argPackAdvance:js,readValueFromPointer:bc,Db(T){ss(T)}})}var Dh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,hm=(o,f)=>{for(var w=o>>1,T=w+f/2;!(w>=T)&&s()[w>>>0];)++w;if(32<(w<<=1)-o&&Dh)return Dh.decode(r().slice(o,w));for(w="",T=0;!(T>=f/2);++T){var O=n()[o+2*T>>>1>>>0];if(O==0)break;w+=String.fromCharCode(O)}return w},fm=(o,f,w)=>{if(w??=2147483647,2>w)return 0;var T=f;w=(w-=2)<2*o.length?w/2:o.length;for(var O=0;O>>1>>>0]=ue,f+=2}return n()[f>>>1>>>0]=0,f-T},mm=o=>2*o.length,_m=(o,f)=>{for(var w=0,T="";!(w>=f/4);){var O=i()[o+4*w>>>2>>>0];if(O==0)break;++w,65536<=O?(O-=65536,T+=String.fromCharCode(55296|O>>10,56320|1023&O)):T+=String.fromCharCode(O)}return T},gm=(o,f,w)=>{if(f>>>=0,w??=2147483647,4>w)return 0;var T=f;w=T+w-4;for(var O=0;O=ue&&(ue=65536+((1023&ue)<<10)|1023&o.charCodeAt(++O)),i()[f>>>2>>>0]=ue,(f+=4)+4>w)break}return i()[f>>>2>>>0]=0,f-T},wm=o=>{for(var f=0,w=0;w=T&&++w,f+=4}return f};function ym(o,f,w){if(o>>>=0,f>>>=0,w=rs(w>>>=0),f===2)var T=hm,O=fm,ue=mm,Le=it=>s()[it>>>1>>>0];else f===4&&(T=_m,O=gm,ue=wm,Le=it=>a()[it>>>2>>>0]);_s(o,{name:w,fromWireType:it=>{for(var It,Dt=a()[it>>>2>>>0],Qt=it+4,$r=0;$r<=Dt;++$r){var zr=it+4+$r*f;$r!=Dt&&Le(zr)!=0||(Qt=T(Qt,zr-Qt),It===void 0?It=Qt:(It+="\0",It+=Qt),Qt=zr+f)}return ss(it),It},toWireType:(it,It)=>{if(typeof It!="string")throw new Ns(`Cannot pass non-string to C++ string type ${w}`);var Dt=ue(It),Qt=zd(4+Dt+f);return a()[Qt>>>2>>>0]=Dt/f,O(It,Qt+4,Dt+f),it!==null&&it.push(ss,Qt),Qt},argPackAdvance:js,readValueFromPointer:bc,Db(it){ss(it)}})}function bm(o,f){_s(o>>>=0,{Sb:!0,name:f=rs(f>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Mm=()=>1;function vm(o){Cc(o>>>0,!S,1,!v,131072,!1),hh()}var Bh=o=>{if(!An)try{if(o(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(i(),o>>>2,o).value.then(Ed),o+=128,Atomics.store(i(),o>>>2,1))}var Ed=()=>{var o=Aa();o&&(Mc(o),Bh(ff))};function xm(o,f){(o>>>=0)==f>>>0?setTimeout(Ed):x?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=ts[o])&&o.postMessage({cmd:"checkMailbox"})}var vc=[];function Tm(o,f,w,T,O){for(f>>>=0,T/=2,vc.length=T,w=O>>>0>>>3,O=0;O>>0];return(f?dc[f]:h_[o])(...vc)}function Sm(o){o>>>=0,x?postMessage({cmd:"cleanupThread",thread:o}):ph(ts[o])}function $m(o){}var xc=(o,f)=>{var w=gc[o];if(w===void 0)throw o=df(o),w=rs(o),ss(o),new Ns(`${f} has unknown type ${w}`);return w},Lh=(o,f,w)=>{var T=[];return o=o.toWireType(T,w),T.length&&(a()[f>>>2>>>0]=jn(T)),o};function Em(o,f,w){return f>>>=0,w>>>=0,o=Nn(o>>>0),f=xc(f,"emval::as"),Lh(f,w,o)}var Cd=o=>{try{o()}catch(f){Ca(f)}},Vs=0,ns=null,Rh=0,kd=[],Nh={},jh={},Cm=0,Tc=null,km=[];function Vh(o){return function(f){if(!An){if(Vs===0){var w=!1,T=!1;f((O=0)=>{if(!An&&(Rh=O,w=!0,T)){Vs=2,Cd(()=>yf(ns)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),O=!1;try{var ue=function(){var It=i()[ns+8>>>2>>>0];return It=Gt[jh[It]],--fi,It()}()}catch(It){ue=It,O=!0}var Le=!1;if(!ns){var it=Tc;it&&(Tc=null,(O?it.reject:it.resolve)(ue),Le=!0)}if(O&&!Le)throw ue}}),T=!0,w||(Vs=1,ns=function(){var O=zd(65548),ue=O+12;a()[O>>>2>>>0]=ue,a()[O+4>>>2>>>0]=ue+65536,ue=kd[0];var Le=Nh[ue];return Le===void 0&&(Le=Cm++,Nh[ue]=Le,jh[Le]=ue),ue=Le,i()[O+8>>>2>>>0]=ue,O}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Cd(()=>gf(ns)))}else Vs===2?(Vs=0,Cd(bf),ss(ns),ns=null,km.forEach(Bh)):Ca(`invalid state: ${Vs}`);return Rh}}(f=>{o().then(f)})}function Pm(o){return o>>>=0,Vh(()=>(o=Nn(o)).then(jn))}var Pd=[];function Am(o,f,w,T){return w>>>=0,T>>>=0,(o=Pd[o>>>0])(null,f=Nn(f>>>0),w,T)}var Im={},Ad=o=>{var f=Im[o];return f===void 0?rs(o):f};function Fm(o,f,w,T,O){return w>>>=0,T>>>=0,O>>>=0,(o=Pd[o>>>0])(f=Nn(f>>>0),f[w=Ad(w)],T,O)}var Uh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Om(o){return(o>>>=0)==0?jn(Uh()):(o=Ad(o),jn(Uh()[o]))}var zm=o=>{var f=Pd.length;return Pd.push(o),f},Dm=(o,f)=>{for(var w=Array(o),T=0;T>>2>>>0],"parameter "+T);return w},Wh=(o,f)=>Object.defineProperty(f,"name",{value:o});function Bm(o,f,w){var T=(f=Dm(o,f>>>0)).shift();o--;var O=`return function (obj, func, destructorsRef, args) { `,ue=0,Le=[];w===0&&Le.push("obj");for(var it=["retType"],It=[T],Dt=0;DtQt.name).join(", ")}) => ${T.name}>`,zm(Wh(w,o))}function Lm(o){return o=Ad(o>>>0),jn(l[o])}function Rm(o,f){return f>>>=0,o=Nn(o>>>0),f=Nn(f),jn(o[f])}function Nm(o){9<(o>>>=0)&&(gs[o+1]+=1)}function jm(){return jn([])}function Vm(o){o=Nn(o>>>0);for(var f=Array(o.length),w=0;w>>0))}function Wm(){return jn({})}function Gm(o){for(var f=Nn(o>>>=0);f.length;){var w=f.pop();f.pop()(w)}yc(o)}function qm(o,f,w){f>>>=0,w>>>=0,o=Nn(o>>>0),f=Nn(f),w=Nn(w),o[f]=w}function Hm(o,f){return f>>>=0,o=(o=xc(o>>>0,"_emval_take_value")).readValueFromPointer(f),jn(o)}function Km(o,f){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[f>>>2>>>0]=o.getUTCSeconds(),i()[f+4>>>2>>>0]=o.getUTCMinutes(),i()[f+8>>>2>>>0]=o.getUTCHours(),i()[f+12>>>2>>>0]=o.getUTCDate(),i()[f+16>>>2>>>0]=o.getUTCMonth(),i()[f+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[f+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[f+28>>>2>>>0]=o}var Pa=o=>o%4==0&&(o%100!=0||o%400==0),Gh=[0,31,60,91,121,152,182,213,244,274,305,335],qh=[0,31,59,90,120,151,181,212,243,273,304,334];function Xm(o,f){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[f>>>2>>>0]=o.getSeconds(),i()[f+4>>>2>>>0]=o.getMinutes(),i()[f+8>>>2>>>0]=o.getHours(),i()[f+12>>>2>>>0]=o.getDate(),i()[f+16>>>2>>>0]=o.getMonth(),i()[f+20>>>2>>>0]=o.getFullYear()-1900,i()[f+24>>>2>>>0]=o.getDay();var w=(Pa(o.getFullYear())?Gh:qh)[o.getMonth()]+o.getDate()-1|0;i()[f+28>>>2>>>0]=w,i()[f+36>>>2>>>0]=-60*o.getTimezoneOffset(),w=new Date(o.getFullYear(),6,1).getTimezoneOffset();var T=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(w!=T&&o.getTimezoneOffset()==Math.min(T,w)),i()[f+32>>>2>>>0]=o}function Qm(o){o>>>=0;var f=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),w=i()[o+32>>>2>>>0],T=f.getTimezoneOffset(),O=new Date(f.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(f.getFullYear(),0,1).getTimezoneOffset(),Le=Math.min(ue,O);return 0>w?i()[o+32>>>2>>>0]=+(O!=ue&&Le==T):0>>2>>>0]=f.getDay(),w=(Pa(f.getFullYear())?Gh:qh)[f.getMonth()]+f.getDate()-1|0,i()[o+28>>>2>>>0]=w,i()[o>>>2>>>0]=f.getSeconds(),i()[o+4>>>2>>>0]=f.getMinutes(),i()[o+8>>>2>>>0]=f.getHours(),i()[o+12>>>2>>>0]=f.getDate(),i()[o+16>>>2>>>0]=f.getMonth(),i()[o+20>>>2>>>0]=f.getYear(),o=f.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Hh(o,f,w,T,O,ue,Le){return x?Kr(16,1,o,f,w,T,O,ue,Le):-52}function Kh(o,f,w,T,O,ue){if(x)return Kr(17,1,o,f,w,T,O,ue)}function Ym(o,f,w,T){o>>>=0,f>>>=0,w>>>=0,T>>>=0;var O=new Date().getFullYear(),ue=new Date(O,0,1),Le=new Date(O,6,1);O=ue.getTimezoneOffset();var it=Le.getTimezoneOffset(),It=Math.max(O,it);a()[o>>>2>>>0]=60*It,i()[f>>>2>>>0]=+(O!=it),ue=(o=Dt=>Dt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ue),Le=o(Le),it{Sc.length=0;for(var w;w=r()[o++>>>0];){var T=w!=105;f+=(T&=w!=112)&&f%8?4:0,Sc.push(w==112?a()[f>>>2>>>0]:w==106?Ur[f>>>3]:w==105?i()[f>>>2>>>0]:d()[f>>>3>>>0]),f+=T?8:4}return Sc};function Zm(o,f,w){return o>>>=0,f=Xh(f>>>0,w>>>0),dc[o](...f)}function Jm(o,f,w){return o>>>=0,f=Xh(f>>>0,w>>>0),dc[o](...f)}var e_=()=>{},t_=()=>Date.now();function r_(o,f){return ar(un(o>>>0,f>>>0))}var Qh,n_=()=>{throw fi+=1,"unwind"};function s_(){return 4294901760}Qh=()=>performance.timeOrigin+performance.now();var i_=()=>navigator.hardwareConcurrency;function a_(){return Ca("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function o_(o){o>>>=0;var f=r().length;if(o<=f||4294901760=w;w*=2){var T=f*(1+.2/w);T=Math.min(T,o+100663296);var O=Math;T=Math.max(o,T);e:{O=(O.min.call(O,4294901760,T+(65536-T%65536)%65536)-hr.buffer.byteLength+65535)/65536;try{hr.grow(O),$n();var ue=1;break e}catch{}ue=void 0}if(ue)return!0}return!1}var Id=()=>(Ca("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Tu={},Yh=o=>{o.forEach(f=>{Id()})};function l_(){var o=Error().stack.toString().split(` `);return o[0]=="Error"&&o.shift(),Yh(o),Tu.Ob=Id(),Tu.ac=o,Tu.Ob}function u_(o,f,w){if(o>>>=0,f>>>=0,Tu.Ob==o)var T=Tu.ac;else(T=Error().stack.toString().split(` `))[0]=="Error"&&T.shift(),Yh(T);for(var O=3;T[O]&&Id()!=o;)++O;for(o=0;o>>2>>>0]=Id();return o}var $c,Ec={},Zh=()=>{if(!$c){var o,f={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",_:fe};for(o in Ec)Ec[o]===void 0?delete f[o]:f[o]=Ec[o];var w=[];for(o in f)w.push(`${o}=${f[o]}`);$c=w}return $c};function Jh(o,f){if(x)return Kr(18,1,o,f);o>>>=0,f>>>=0;var w=0;return Zh().forEach((T,O)=>{var ue=f+w;for(O=a()[o+4*O>>>2>>>0]=ue,ue=0;ue>>0]=T.charCodeAt(ue);t()[O>>>0]=0,w+=T.length+1}),0}function ef(o,f){if(x)return Kr(19,1,o,f);o>>>=0,f>>>=0;var w=Zh();a()[o>>>2>>>0]=w.length;var T=0;return w.forEach(O=>T+=O.length+1),a()[f>>>2>>>0]=T,0}function tf(o){return x?Kr(20,1,o):52}function rf(o,f,w,T){return x?Kr(21,1,o,f,w,T):52}function nf(o,f,w,T){return x?Kr(22,1,o,f,w,T):70}var d_=[null,[],[]];function sf(o,f,w,T){if(x)return Kr(23,1,o,f,w,T);f>>>=0,w>>>=0,T>>>=0;for(var O=0,ue=0;ue>>2>>>0],it=a()[f+4>>>2>>>0];f+=8;for(var It=0;It>>0],Qt=d_[o];Dt===0||Dt===10?((o===1?dr:ar)(yh(Qt,0)),Qt.length=0):Qt.push(Dt)}O+=it}return a()[T>>>2>>>0]=O,0}var af=[31,29,31,30,31,30,31,31,30,31,30,31],of=[31,28,31,30,31,30,31,31,30,31,30,31],c_=(o,f)=>{t().set(o,f>>>0)};function lf(o,f,w,T){function O(Ae,vr,Yr){for(Ae=typeof Ae=="number"?Ae.toString():Ae||"";Ae.lengthvf?-1:0_i-Ae.getDate())){Ae.setDate(Ae.getDate()+vr);break}vr-=_i-Ae.getDate()+1,Ae.setDate(1),11>Yr?Ae.setMonth(Yr+1):(Ae.setMonth(0),Ae.setFullYear(Ae.getFullYear()+1))}return Yr=new Date(Ae.getFullYear()+1,0,4),vr=it(new Date(Ae.getFullYear(),0,4)),Yr=it(Yr),0>=Le(vr,Ae)?0>=Le(Yr,Ae)?Ae.getFullYear()+1:Ae.getFullYear():Ae.getFullYear()-1}o>>>=0,f>>>=0,w>>>=0,T>>>=0;var Dt=a()[T+40>>>2>>>0];for(var Qt in T={fc:i()[T>>>2>>>0],ec:i()[T+4>>>2>>>0],Gb:i()[T+8>>>2>>>0],Kb:i()[T+12>>>2>>>0],Hb:i()[T+16>>>2>>>0],Cb:i()[T+20>>>2>>>0],ub:i()[T+24>>>2>>>0],Bb:i()[T+28>>>2>>>0],nc:i()[T+32>>>2>>>0],dc:i()[T+36>>>2>>>0],hc:Dt?un(Dt):""},w=un(w),Dt={"%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"})w=w.replace(new RegExp(Qt,"g"),Dt[Qt]);var $r="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),zr="January February March April May June July August September October November December".split(" ");for(Qt in Dt={"%a":Ae=>$r[Ae.ub].substring(0,3),"%A":Ae=>$r[Ae.ub],"%b":Ae=>zr[Ae.Hb].substring(0,3),"%B":Ae=>zr[Ae.Hb],"%C":Ae=>ue((Ae.Cb+1900)/100|0,2),"%d":Ae=>ue(Ae.Kb,2),"%e":Ae=>O(Ae.Kb,2," "),"%g":Ae=>It(Ae).toString().substring(2),"%G":It,"%H":Ae=>ue(Ae.Gb,2),"%I":Ae=>((Ae=Ae.Gb)==0?Ae=12:12{for(var vr=0,Yr=0;Yr<=Ae.Hb-1;vr+=(Pa(Ae.Cb+1900)?af:of)[Yr++]);return ue(Ae.Kb+vr,3)},"%m":Ae=>ue(Ae.Hb+1,2),"%M":Ae=>ue(Ae.ec,2),"%n":()=>` `,"%p":Ae=>0<=Ae.Gb&&12>Ae.Gb?"AM":"PM","%S":Ae=>ue(Ae.fc,2),"%t":()=>" ","%u":Ae=>Ae.ub||7,"%U":Ae=>ue(Math.floor((Ae.Bb+7-Ae.ub)/7),2),"%V":Ae=>{var vr=Math.floor((Ae.Bb+7-(Ae.ub+6)%7)/7);if(2>=(Ae.ub+371-Ae.Bb-2)%7&&vr++,vr)vr==53&&((Yr=(Ae.ub+371-Ae.Bb)%7)==4||Yr==3&&Pa(Ae.Cb)||(vr=1));else{vr=52;var Yr=(Ae.ub+7-Ae.Bb-1)%7;(Yr==4||Yr==5&&Pa(Ae.Cb%400-1))&&vr++}return ue(vr,2)},"%w":Ae=>Ae.ub,"%W":Ae=>ue(Math.floor((Ae.Bb+7-(Ae.ub+6)%7)/7),2),"%y":Ae=>(Ae.Cb+1900).toString().substring(2),"%Y":Ae=>Ae.Cb+1900,"%z":Ae=>{var vr=0<=(Ae=Ae.dc);return Ae=Math.abs(Ae)/60,(vr?"+":"-")+("0000"+(Ae/60*100+Ae%60)).slice(-4)},"%Z":Ae=>Ae.hc,"%%":()=>"%"},w=w.replace(/%%/g,"\0\0"),Dt)w.includes(Qt)&&(w=w.replace(new RegExp(Qt,"g"),Dt[Qt](T)));return Qt=function(Ae){var vr=Array(mc(Ae)+1);return vh(Ae,vr,0,vr.length),vr}(w=w.replace(/\0\0/g,"%")),Qt.length>f?0:(c_(Qt,o),Qt.length-1)}function p_(o,f,w,T){return lf(o>>>0,f>>>0,w>>>0,T>>>0)}x||function(){for(var o=l.numThreads-1;o--;)mh();gn.unshift(()=>{Ls++,function(f){x?f():Promise.all(Rs.map(fh)).then(f)}(()=>nh())})}();for(var uf=Array(256),Fd=0;256>Fd;++Fd)uf[Fd]=String.fromCharCode(Fd);Oh=uf,Ns=l.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},l.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},gs.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>gs.length/2-5-wc.length;var h_=[hc,dh,_h,bh,Mh,xh,Th,Sh,$h,Eh,Ch,kh,Ph,Ah,Ih,Fh,Hh,Kh,Jh,ef,tf,rf,nf,sf],Gt=function(){function o(w,T){return Gt=w.exports,Gt=function(){var O=Gt,ue={};for(let[Le,it]of Object.entries(O))ue[Le]=typeof it=="function"?(...It)=>{kd.push(Le);try{return it(...It)}finally{An||(kd.pop(),ns&&Vs===1&&kd.length===0&&(Vs=0,fi+=1,Cd(wf),typeof Fibers<"u"&&Fibers.oc()))}}:it;return ue}(),Gt=function(){var O=Gt,ue=it=>It=>it(It)>>>0,Le=it=>()=>it()>>>0;return(O=Object.assign({},O)).Ca=ue(O.Ca),O.fb=Le(O.fb),O.gb=ue(O.gb),O.emscripten_main_runtime_thread_id=Le(O.emscripten_main_runtime_thread_id),O.sb=ue(O.sb),O.tb=Le(O.tb),O}(),ch.push(Gt.ib),cn.unshift(Gt.Ba),Yt=T,nh(),Gt}var f=lh();if(Ls++,l.instantiateWasm)try{return l.instantiateWasm(f,o)}catch(w){ar(`Module.instantiateWasm callback failed with error: ${w}`),g(w)}return uc||=l.locateFile?sh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ne):Ne+"ort-wasm-simd-threaded.jsep.wasm":new URL(N("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),N.b).href,function(w,T){var O=uc;return mt||typeof WebAssembly.instantiateStreaming!="function"||sh(O)||ih(O)||typeof fetch!="function"?oh(O,w,T):fetch(O,{credentials:"same-origin"}).then(ue=>WebAssembly.instantiateStreaming(ue,w).then(T,function(Le){return ar(`wasm streaming compile failed: ${Le}`),ar("falling back to ArrayBuffer instantiation"),oh(O,w,T)}))}(f,function(w){o(w.instance,w.module)}).catch(g),{}}(),df=o=>(df=Gt.Ca)(o),cf=()=>(cf=Gt.Da)();l._OrtInit=(o,f)=>(l._OrtInit=Gt.Ea)(o,f),l._OrtGetLastError=(o,f)=>(l._OrtGetLastError=Gt.Fa)(o,f),l._OrtCreateSessionOptions=(o,f,w,T,O,ue,Le,it,It,Dt)=>(l._OrtCreateSessionOptions=Gt.Ga)(o,f,w,T,O,ue,Le,it,It,Dt),l._OrtAppendExecutionProvider=(o,f)=>(l._OrtAppendExecutionProvider=Gt.Ha)(o,f),l._OrtAddFreeDimensionOverride=(o,f,w)=>(l._OrtAddFreeDimensionOverride=Gt.Ia)(o,f,w),l._OrtAddSessionConfigEntry=(o,f,w)=>(l._OrtAddSessionConfigEntry=Gt.Ja)(o,f,w),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Gt.Ka)(o),l._OrtCreateSession=(o,f,w)=>(l._OrtCreateSession=Gt.La)(o,f,w),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Gt.Ma)(o),l._OrtGetInputOutputCount=(o,f,w)=>(l._OrtGetInputOutputCount=Gt.Na)(o,f,w),l._OrtGetInputName=(o,f)=>(l._OrtGetInputName=Gt.Oa)(o,f),l._OrtGetOutputName=(o,f)=>(l._OrtGetOutputName=Gt.Pa)(o,f),l._OrtFree=o=>(l._OrtFree=Gt.Qa)(o),l._OrtCreateTensor=(o,f,w,T,O,ue)=>(l._OrtCreateTensor=Gt.Ra)(o,f,w,T,O,ue),l._OrtGetTensorData=(o,f,w,T,O)=>(l._OrtGetTensorData=Gt.Sa)(o,f,w,T,O),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Gt.Ta)(o),l._OrtCreateRunOptions=(o,f,w,T)=>(l._OrtCreateRunOptions=Gt.Ua)(o,f,w,T),l._OrtAddRunConfigEntry=(o,f,w)=>(l._OrtAddRunConfigEntry=Gt.Va)(o,f,w),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Gt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Gt.Xa)(o),l._OrtBindInput=(o,f,w)=>(l._OrtBindInput=Gt.Ya)(o,f,w),l._OrtBindOutput=(o,f,w,T)=>(l._OrtBindOutput=Gt.Za)(o,f,w,T),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Gt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Gt.$a)(o),l._OrtRunWithBinding=(o,f,w,T,O)=>(l._OrtRunWithBinding=Gt.ab)(o,f,w,T,O),l._OrtRun=(o,f,w,T,O,ue,Le,it)=>(l._OrtRun=Gt.bb)(o,f,w,T,O,ue,Le,it),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Gt.cb)(o),l._JsepOutput=(o,f,w)=>(l._JsepOutput=Gt.db)(o,f,w),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Gt.eb)(o);var Od,Aa=()=>(Aa=Gt.fb)(),zd=l._malloc=o=>(zd=l._malloc=Gt.gb)(o),ss=l._free=o=>(ss=l._free=Gt.hb)(o),Cc=(o,f,w,T,O,ue)=>(Cc=Gt.kb)(o,f,w,T,O,ue),pf=()=>(pf=Gt.lb)(),hf=(o,f,w,T,O)=>(hf=Gt.mb)(o,f,w,T,O),kc=o=>(kc=Gt.nb)(o),Dd=o=>(Dd=Gt.ob)(o),ff=()=>(ff=Gt.pb)(),mf=(o,f)=>(mf=Gt.qb)(o,f),Bd=o=>(Bd=Gt.rb)(o),Pc=o=>(Pc=Gt.sb)(o),Ac=()=>(Ac=Gt.tb)(),_f=l.dynCall_ii=(o,f)=>(_f=l.dynCall_ii=Gt.vb)(o,f),gf=o=>(gf=Gt.wb)(o),wf=()=>(wf=Gt.xb)(),yf=o=>(yf=Gt.yb)(o),bf=()=>(bf=Gt.zb)();function Mf(){0Ac(),l.stackRestore=o=>Bd(o),l.stackAlloc=o=>Pc(o),l.UTF8ToString=un,l.stringToUTF8=ka,l.lengthBytesUTF8=mc,hi=function o(){Od||Mf(),Od||(hi=o)},Mf(),y}),Ct=lt,globalThis.self?.name==="em-pthread"&<()}),ze,Rt,Ot,Wt,zt,Ut,Ht,ur,rr=R(()=>{et(),ze=import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Rt=typeof location>"u"?void 0:location.origin,Ot=(e,t)=>{try{let r=t??ze;return(r?new URL(e,r):new URL(e)).origin===Rt}catch{return!1}},Wt=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},zt=(ke(),P(B)).default,Ut=async()=>{if(!ze)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ot(ze))return[void 0,zt()];let e=await Wt(ze);return[e,zt(e)]},Ht=(gt(),P(tt)).default,ur=async(e,t,r)=>[void 0,Ht]}),wr,Qe,yt,Ft,Zr,Xn,is,Hr,pn=R(()=>{rr(),Qe=!1,yt=!1,Ft=!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}},Xn=()=>{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}},is=async e=>{if(Qe)return Promise.resolve();if(yt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ft)throw new Error("previous call to 'initializeWebAssembly()' failed.");yt=!0;let t=e.initTimeout,r=e.numThreads;if(!Xn())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Zr();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,i=typeof s=="string"?s:void 0,a=s?.mjs,u=a?.href??a,d=s?.wasm,c=d?.href??d,g=e.wasmBinary,[l,y]=await ur(u,i,r>1),v=!1,S=[];if(t>0&&S.push(new Promise(x=>{setTimeout(()=>{v=!0,x()},t)})),S.push(new Promise((x,G)=>{let q={numThreads:r};g?q.wasmBinary=g:(c||i)&&(q.locateFile=(k,Z)=>c??(i??Z)+k),y(q).then(k=>{yt=!1,Qe=!0,wr=k,x(),l&&URL.revokeObjectURL(l)},k=>{yt=!1,Ft=!0,G(k)})})),await Promise.race(S),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Hr=()=>{if(Qe&&wr)return wr;throw new Error("WebAssembly is not initialized yet.")}}),Xr,Qn,Lr,Vn=R(()=>{pn(),Xr=(e,t)=>{let r=Hr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Qn=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,i])=>{let a=t?t+s:s;if(typeof i=="object")Qn(i,a+".",r,n);else if(typeof i=="string"||typeof i=="number")n(a,i.toString());else if(typeof i=="boolean")n(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},Lr=e=>{let t=Hr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let s=t.HEAP32[n/4],i=t.HEAPU32[n/4+1],a=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(r)}}}),In,Us=R(()=>{pn(),Vn(),In=e=>{let t=Hr(),r=0,n=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.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?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(s.terminate=!1);let i=0;return e?.tag!==void 0&&(i=Xr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,i),r===0&&Lr("Can't create run options."),e?.extra!==void 0&&Qn(e.extra,"",new WeakSet,(a,u)=>{let d=Xr(a,n),c=Xr(u,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&Lr(`Can't set a run config entry: ${a} - ${u}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}}),ws,ys,bs,Ms,Un,Ws=R(()=>{pn(),Vn(),ws=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}`)}},ys=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bs=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Ms=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let a=n?.deviceType;if(a){let u=Xr("deviceType",r),d=Xr(a,r);Hr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Lr(`Can't set a session config entry: 'deviceType' - ${a}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let u=Xr("preferredLayout",r),d=Xr(a.preferredLayout,r);Hr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Lr(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let i=Xr(s,r);Hr()._OrtAppendExecutionProvider(e,i)!==0&&Lr(`Can't append execution provider: ${s}.`)}},Un=e=>{let t=Hr(),r=0,n=[],s=e||{};bs(s);try{let i=ws(s.graphOptimizationLevel??"all"),a=ys(s.executionMode??"sequential"),u=typeof s.logId=="string"?Xr(s.logId,n):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=s.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let g=typeof s.optimizedModelFilePath=="string"?Xr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!s.enableCpuMemArena,!!s.enableMemPattern,a,!!s.enableProfiling,0,u,d,c,g),r===0&&Lr("Can't create session options."),s.executionProviders&&Ms(r,s.executionProviders,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let l=Xr("enableGraphCapture",n),y=Xr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,l,y)!==0&&Lr(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[l,y]of Object.entries(s.freeDimensionOverrides)){if(typeof l!="string")throw new Error(`free dimension override name must be a string: ${l}`);if(typeof y!="number"||!Number.isInteger(y)||y<0)throw new Error(`free dimension override value must be a non-negative integer: ${y}`);let v=Xr(l,n);t._OrtAddFreeDimensionOverride(r,v,y)!==0&&Lr(`Can't set a free dimension override: ${l} - ${y}.`)}return s.extra!==void 0&&Qn(s.extra,"",new WeakSet,(l,y)=>{let v=Xr(l,n),S=Xr(y,n);t._OrtAddSessionConfigEntry(r,v,S)!==0&&Lr(`Can't set a session config entry: ${l} - ${y}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(a=>t._free(a)),i}}}),as,Cn,Wn,Fn,Yn,os,ls,Kt=R(()=>{as=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}`)}},Cn=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}`)}},Wn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,i)=>s*i,1);return r>0?Math.ceil(n*r):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}`)}},Yn=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}`)}},os=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ls=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;default:throw new Error(`unsupported data location: ${e}`)}}}),Zn,vs=R(()=>{et(),Zn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let a=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let c=d.byteLength;new Uint8Array(i,a,c).set(d),a+=c}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),xs,us,Ts,Ss,ds,$s,Nr,wn=R(()=>{Kt(),xs=["V","I","W","E","F"],us=(e,t)=>{console.log(`[${xs[e]},${new Date().toISOString()}]${t}`)},ds=(e,t)=>{Ts=e,Ss=t},$s=(e,t)=>{let r=Yn(e),n=Yn(Ts);r>=n&&us(r,typeof t=="function"?t():t)},Nr=(...e)=>{Ss&&$s(...e)}}),we,m=R(()=>{Kt(),we=(e,t)=>new(Fn(t))(e)}),z=R(()=>{}),Y,J,ve,Be,xt,vt,kt,bt,fr,or=R(()=>{wn(),z(),Y=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]]),J=[],ve=e=>Math.ceil(e/16)*16,Be=e=>{for(let t=0;txt++,kt=async(e,t,r,n)=>{let s=ve(r),i=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,s),e.flush(),await i.mapAsync(GPUMapMode.READ);let u=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{i.destroy()}},bt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[t]of Y)J.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,i=ve(s),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(a.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${s}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,n,s)),u.unmap();let c=this.backend.getCommandEncoder();this.backend.endComputePass(),c.copyBufferToBuffer(u,0,a.gpuData.buffer,0,i),Nr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=ve(r.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(e,t,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(e===r)return Nr("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!`);this.externalBuffers.delete(r)}else n=vt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),Nr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),Nr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Be(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||i){let u=(s?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let a={id:vt(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:e}),Nr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return Nr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await kt(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Y.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},fr=(...e)=>new bt(...e)}),yr,qt,Cr=R(()=>{yr=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}},qt=e=>new yr(e)}),yn,Rr,Ie,On,xr,Jr,dn,Xt=R(()=>{yn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Rr=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let i=Math.max(e.length,t.length),a=new Array(i);if(r){if(n<2||s<2)return;let u=yn.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(u===void 0)return;[a[i-2],a[i-1]]=u}for(let u=r?3:1;u<=i;u++){let d=n-u<0?1:e[n-u],c=s-u<0?1:t[s-u];if(d!==c&&d>1&&c>1)return;let g=Math.max(d,c);if(d&&c)a[i-u]=Math.max(d,c);else{if(g>1)return;a[i-u]=0}}return a}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},Ie=class Vd{static size(t){return Vd.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let s=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){s[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");s[i]=1,r/=t[i],i--}for(i--;i>=0;i--)s[i]=t[i];return s}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Vd.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Vd.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let s=1;for(let i=r;i=0;--s)n[s]=n[s+1]*t[s+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((s,i)=>s+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,s)=>n===r[s])}},On=class $u{static adjustPoolAttributes(t,r,n,s,i,a){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||a[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,i,a,u){if(u){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Kt(),Xt(),hn=64,sn=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(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}`)}},Er=(e,t=1)=>{let r=sn(e,t);return typeof r=="string"?r:r[0]},Tr=(e,t=1)=>{let r=sn(e,t);return typeof r=="string"?r:r[1]},Pt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Ie.computeStrides(r)})}),t},Sr=e=>e%4===0?4:e%2===0?2:1,Fr=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,jr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,fn=(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,Nt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Gs=(e,t,r,n,s)=>{let i=typeof r=="number",a=i?r:r.length,u=[...new Array(a).keys()],d=a<2?"u32":a<=4?`vec${a}`:`array`,c=sn(t,s),g=typeof c=="string"?c:c[1],l=typeof c=="string"?c:c[0],y={indices:d,value:g,storage:l,tensor:t},v=Ke=>typeof Ke=="string"?Ke:`${Ke}u`,S={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},x=i?"uniforms.":"",G=`${x}${e}_shape`,q=`${x}${e}_strides`,k="";for(let Ke=0;Ke ${y.indices} { var indices: ${y.indices}; var current = offset; ${k} return indices; }`,ee=Ke=>(S.offsetToIndices=!0,a<2?Ke:`o2i_${e}(${Ke})`),fe=[];if(a>=2)for(let Ke=a-1;Ke>=0;Ke--)fe.push(`${Nt(q,Ke,a)} * (indices[${Ke}])`);let We=a<2?"":` fn i2o_${e}(indices: ${y.indices}) -> u32 { return ${fe.join("+")}; }`,Ne=Ke=>(S.indicesToOffset=!0,a<2?Ke:`i2o_${e}(${Ke})`),mt=(...Ke)=>a===0?"0u":`${y.indices}(${Ke.map(v).join(",")})`,jt=(Ke,$t)=>a<2?`${Ke}`:`${Nt(Ke,$t,a)}`,Lt=(Ke,$t,cr)=>a<2?`${Ke}=${cr};`:`${Nt(Ke,$t,a)}=${cr};`,dr={},ar=(Ke,$t)=>{S.broadcastedIndicesToOffset=!0;let cr=`${$t.name}broadcastedIndicesTo${e}Offset`;if(cr in dr)return`${cr}(${Ke})`;let Vr=[];for(let Ur=a-1;Ur>=0;Ur--){let Rn=$t.indicesGet("outputIndices",Ur+$t.rank-a);Vr.push(`${jt(q,Ur)} * (${Rn} % ${jt(G,Ur)})`)}return dr[cr]=`fn ${cr}(outputIndices: ${$t.type.indices}) -> u32 { return ${Vr.length>0?Vr.join("+"):"0u"}; }`,`${cr}(${Ke})`},_r=(Ke,$t)=>(()=>{if(y.storage===y.value)return`${e}[${Ke}]=${$t};`;if(y.storage==="vec2"&&y.value==="i32")return`${e}[${Ke}]=vec2(u32(${$t}), select(0u, 0xFFFFFFFFu, ${$t} < 0));`;if(y.storage==="vec2"&&y.value==="u32")return`${e}[${Ke}]=vec2(u32(${$t}), 0u);`;if(y.storage==="u32"&&y.value==="vec4")return`${e}[${Ke}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${$t}));`;throw new Error(`not supported combination of storage type ${y.storage} and value type ${y.value} yet`)})(),Pr=Ke=>(()=>{if(y.storage===y.value)return`${e}[${Ke}]`;if(y.storage==="vec2"&&y.value==="i32")return`i32(${e}[${Ke}].x)`;if(y.storage==="vec2"&&y.value==="u32")return`u32(${e}[${Ke}].x)`;if(y.storage==="u32"&&y.value==="vec4")return`vec4(bool(${e}[${Ke}] & 0xFFu), bool(${e}[${Ke}] & 0xFF00u), bool(${e}[${Ke}] & 0xFF0000u), bool(${e}[${Ke}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${y.storage} and value type ${y.value} yet`)})(),hr=a<2?"":` fn get_${e}ByIndices(indices: ${y.indices}) -> ${g} { return ${Pr(`i2o_${e}(indices)`)}; }`,Yt=a<2?"":(()=>{let Ke=u.map(cr=>`d${cr}: u32`).join(", "),$t=u.map(cr=>`d${cr}`).join(", ");return` fn get_${e}(${Ke}) -> ${g} { return get_${e}ByIndices(${mt($t)}); }`})(),Ar=(...Ke)=>{if(Ke.length!==a)throw new Error(`indices length must be ${a}`);let $t=Ke.map(v).join(",");return a===0?Pr("0u"):a===1?Pr($t[0]):(S.get=!0,S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}(${$t})`)},Br=Ke=>a<2?Pr(Ke):(S.getByIndices=!0,S.indicesToOffset=!0,`get_${e}ByIndices(${Ke})`),tr=a<2?"":` fn set_${e}ByIndices(indices: ${y.indices}, value: ${g}) { ${_r(`i2o_${e}(indices)`,"value")} }`,gr=a<2?"":(()=>{let Ke=u.map(cr=>`d${cr}: u32`).join(", "),$t=u.map(cr=>`d${cr}`).join(", ");return` fn set_${e}(${Ke}, value: ${g}) { set_${e}ByIndices(${mt($t)}, value); }`})();return{impl:()=>{let Ke=[],$t=!1;return S.offsetToIndices&&(Ke.push(Z),$t=!0),S.indicesToOffset&&(Ke.push(We),$t=!0),S.broadcastedIndicesToOffset&&(Object.values(dr).forEach(cr=>Ke.push(cr)),$t=!0),S.set&&(Ke.push(gr),$t=!0),S.setByIndices&&(Ke.push(tr),$t=!0),S.get&&(Ke.push(Yt),$t=!0),S.getByIndices&&(Ke.push(hr),$t=!0),!i&&$t&&Ke.unshift(`const ${G} = ${y.indices}(${r.join(",")});`,`const ${q} = ${y.indices}(${Ie.computeStrides(r).join(",")});`),Ke.join(` `)},type:y,offsetToIndices:ee,indicesToOffset:Ne,broadcastedIndicesToOffset:ar,indices:mt,indicesGet:jt,indicesSet:Lt,set:(...Ke)=>{if(Ke.length!==a+1)throw new Error(`indices length must be ${a}`);let $t=Ke[a];if(typeof $t!="string")throw new Error("value must be string");let cr=Ke.slice(0,a).map(v).join(",");return a===0?_r("0u",$t):a===1?_r(cr[0],$t):(S.set=!0,S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}(${cr}, ${$t})`)},setByOffset:_r,setByIndices:(Ke,$t)=>a<2?_r(Ke,$t):(S.setByIndices=!0,S.indicesToOffset=!0,`set_${e}ByIndices(${Ke}, ${$t});`),get:Ar,getByOffset:Pr,getByIndices:Br,usage:n,name:e,strides:q,shape:G,rank:a}},Ze=(e,t,r,n=1)=>Gs(e,t,r,"input",n),Vt=(e,t,r,n=1)=>Gs(e,t,r,"output",n),wi=(e,t,r,n=1)=>Gs(e,t,r,"internal",n),yi=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=hn){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=s?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @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`,a=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) fn main(${i}) { ${a} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}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])}},Fa=(e,t)=>new yi(e,t),cs=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&a===1&&n.unshift(i)}return n}}),Oa,bi,Es,za,kn,Da,Mi,ps=R(()=>{Kt(),Xt(),Cr(),sr(),Oa=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},bi=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Es=(e,t)=>Ie.sortBasedOnPerm(e,bi(e.length,t)),za=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let i=0;i{let r=e.dataType,n=e.dims.length,s=bi(n,t),i=Es(e.dims,s),a=Vt("output",r,i.length),u=Ze("a",r,n),d;if(s.length===2&&s[0]===1&&s[1]===0){let c=a.type.value,g=[16,16,1];d=l=>` ${l.registerUniform("output_size","u32").declareVariables(u,a)} var tile : array, ${g[0]}>; ${l.mainStart(g)} var x = workgroup_id.x * ${g[0]}u + local_id.x; var y = workgroup_id.y * ${g[0]}u + local_id.y; let width = uniforms.output_shape[0]; let height = uniforms.output_shape[1]; if (x < width && y < height) { tile[local_id.y][local_id.x] = ${u.getByOffset("y * width + x")}; } workgroupBarrier(); x = workgroup_id.y * ${g[0]}u + local_id.x; y = workgroup_id.x * ${g[0]}u + local_id.y; if (x < height && y < width) { ${a.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} } }`}else d=c=>` ${c.registerUniform("output_size","u32").declareVariables(u,a)} ${za(s,n,u,a)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${a.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${a.setByOffset("global_idx",u.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let c=Ie.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},...Pt(e.dims,i)]}},getShaderSource:d}},Da=(e,t)=>{Oa(e.inputs),e.compute(kn(e.inputs[0],t.perm))},Mi=e=>qt({perm:e.perm})}),Ba,La,Ra,Na,vi,ja,Va,xi,Ua,Wa,bn,Ga,qa,Ti,Ha,Ka,Si,Xa,Qa,$i,Ya,Cu=R(()=>{Kt(),Xt(),sr(),Fi(),ps(),Ba={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"},La={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"},Ra={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Na={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},vi=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,s]},Va=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let i=0;i{for(let r=0;r{let r=[];if(!xi(e,t)){for(let n=0;nr.push(n))}return r},Wa=(e,t,r,n,s,i,a)=>{let u=r[0].dims,d=Ie.size(i),c=Ie.size(a),g=Ze("_A",r[0].dataType,u),l=Vt("output",s,i),y=32,v=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:S=>` ${S.registerUniform("reduceSize","u32").declareVariables(g,l)} ${v} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${S.mainStart(y)} let outputIndex = global_idx / ${y}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Ra[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${y}) { let candidate = f32(${g.getByOffset("offset + k")}); bestValue = ${Ba[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${y}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 = ${La[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${l.setByOffset("outputIndex",`${n==="mean"?`${l.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${l.type.storage}(${Na[n]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},bn=(e,t,r,n)=>{let s=e.inputs.length===1?r:Hs(e.inputs,r),i=s.axes;i.length===0&&!s.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((v,S)=>S));let a=Ie.normalizeAxes(i,e.inputs[0].dims.length),u=a,d=e.inputs[0],c=Ua(u,e.inputs[0].dims.length);c.length>0&&(d=e.compute(kn(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],u=vi(u.length,d.dims.length));let[g,l]=ja(d.dims,u),y=g;s.keepDims&&(y=Va(g,a)),e.compute(Wa(t,{hint:s.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,y,l),{inputs:[d]})},Ga=(e,t)=>{bn(e,"ReduceMeanShared",t,"mean")},qa=(e,t)=>{bn(e,"ReduceL1Shared",t,"l1")},Ti=(e,t)=>{bn(e,"ReduceL2Shared",t,"l2")},Ha=(e,t)=>{bn(e,"ReduceLogSumExpShared",t,"logSumExp")},Ka=(e,t)=>{bn(e,"ReduceMaxShared",t,"max")},Si=(e,t)=>{bn(e,"ReduceMinShared",t,"min")},Xa=(e,t)=>{bn(e,"ReduceProdShared",t,"prod")},Qa=(e,t)=>{bn(e,"ReduceSumShared",t,"sum")},$i=(e,t)=>{bn(e,"ReduceSumSquareShared",t,"sumSquare")},Ya=(e,t)=>{bn(e,"ReduceLogSumShared",t,"logSum")}}),Mn,Za,qs,Hs,xn,Ja,Ei,eo,to,Ci,ro,no,ki,so,io,vn,ao,oo,Pi,lo,uo,Ai,co,po,Ii,ho,Fi=R(()=>{Kt(),Xt(),Cr(),sr(),Cu(),Mn=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")};`,""],qs=(e,t,r,n,s,i,a=!1,u=!1)=>{let d=[],c=r[0].dims,g=c.length,l=Ie.normalizeAxes(s,g),y=!u&&l.length===0;c.forEach((x,G)=>{y||l.indexOf(G)>=0?a&&d.push(1):d.push(x)});let v=d.length,S=Ie.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let G=[],q=Ze("_A",r[0].dataType,g),k=Vt("output",i,v),Z=n(q,k,l),ee=Z[2];for(let fe=0,We=0;fe=0?(a&&We++,ee=`for(var j${fe}: u32 = 0; j${fe} < ${c[fe]}; j${fe}++) { ${Z[2].includes("last_index")?`let last_index = j${fe};`:""} ${q.indicesSet("input_indices",fe,`j${fe}`)} ${ee} }`):(G.push(`${q.indicesSet("input_indices",fe,k.indicesGet("output_indices",We))};`),We++);return` ${x.registerUniform("output_size","u32").declareVariables(q,k)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${q.type.indices}; let output_indices = ${k.offsetToIndices("global_idx")}; ${G.join(` `)} ${Z[0]} // init ops for reduce max/min ${Z[1]} ${ee} ${Z[3]} ${Z.length===4?k.setByOffset("global_idx","value"):Z.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...Pt(c,d)]})}},Hs=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),qt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},xn=(e,t,r,n)=>{let s=e.inputs,i=s.length===1?r:Hs(s,r);e.compute(qs(t,{hint:i.cacheKey,inputDependencies:["rank"]},[s[0]],i.noopWithEmptyAxes&&i.axes.length===0?Za:n,i.axes,s[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},Ja=(e,t)=>{Mn(e.inputs),xn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Ei=(e,t)=>{Mn(e.inputs),xn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},eo=(e,t)=>{Mn(e.inputs),xn(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},to=(e,t)=>{Mn(e.inputs),xn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Ci=(e,t)=>{Mn(e.inputs),xn(e,"ReduceMax",t,(r,n,s)=>{let i=[];for(let a=0;a=0||s.length===0)&&i.push(r.indicesSet("input_indices",a,0));return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},ro=(e,t)=>{Mn(e.inputs),xn(e,"ReduceMean",t,(r,n,s)=>{let i=1;for(let a=0;a=0||s.length===0)&&(i*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${i});`]})},no=(e,t)=>{Mn(e.inputs),xn(e,"ReduceMin",t,(r,n,s)=>{let i=[];for(let a=0;a=0||s.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},ki=(e,t)=>{Mn(e.inputs),xn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},so=(e,t)=>{Mn(e.inputs),xn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},io=(e,t)=>{Mn(e.inputs),xn(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},vn=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let i=0;i1024},ao=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):Ga(e,t)},oo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ei(e,t):qa(e,t)},Pi=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?eo(e,t):Ti(e,t)},lo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?to(e,t):Ha(e,t)},uo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ci(e,t):Ka(e,t)},Ai=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?no(e,t):Si(e,t)},co=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ki(e,t):Xa(e,t)},po=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?so(e,t):Qa(e,t)},Ii=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?io(e,t):$i(e,t)},ho=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):Ya(e,t)}}),Ks,fo,mo,Xs,ku=R(()=>{Kt(),Cr(),Fi(),Ks=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.")},fo=(e,t)=>{Ks(e.inputs);let r=(n,s,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.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); }`,"",s.setByOffset("global_idx","best_index")]};e.compute(qs("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},mo=(e,t)=>{Ks(e.inputs);let r=(n,s,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.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); }`,"",s.setByOffset("global_idx","best_index")]};e.compute(qs("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Xs=e=>qt(e)}),_o,Oi,go,wo,hs,yo,bo,Qs=R(()=>{Kt(),Xt(),z(),sr(),_o=(e,t)=>{let r=e[0],n=e[1],s=e[2],i=e[3],a=e[4],u=e[5];if(a&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],c=r.dims[1],g=r.dims[2];if(s.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]!==g)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let l=s.dims[0]/3,y=l,v=y;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let Z of t.qkvHiddenSizes)if(Z%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");l=t.qkvHiddenSizes[0],y=t.qkvHiddenSizes[1],v=t.qkvHiddenSizes[2]}let S=c;if(l!==y)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==l+y+v)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let x=0;if(a){if(y!==v)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==y/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(x=a.dims[3])}let G=S+x,q=-1,k=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==c||u.dims[3]!==G)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:x,kvSequenceLength:S,totalSequenceLength:G,maxSequenceLength:q,inputHiddenSize:g,hiddenSize:l,vHiddenSize:v,headSize:Math.floor(l/t.numHeads),vHeadSize:Math.floor(v/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:k,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Oi=(e,t,r)=>{let n=Sr(r),s=64,i=r/n;i{let v=Vt("x",e.dataType,e.dims,n),S=Tr(e.dataType),x=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${y.registerUniforms(x).declareVariables(v)} ${y.mainStart([s,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; var thread_max_vector = ${c}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${c}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(n){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: ${n}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${s}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${c}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${c}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(n){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: ${n}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${s}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${v.type.value}(${S}(uniforms.d_inv)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${c}(x[offset + i]); x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${d};${n}`,inputDependencies:g},getShaderSource:l,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:u})}},go=(e,t,r,n,s,i,a,u)=>{let d=u+i.kvSequenceLength,c=[i.batchSize,i.numHeads,i.sequenceLength,d],g=i.kvNumHeads===void 0&&e>1&&n,l=g?[i.batchSize,i.numHeads,d,i.headSize]:void 0,y=a.scale===0?1/Math.sqrt(i.headSize):a.scale,v=Sr(i.headSize),S=i.headSize/v,x=12,G={x:Math.ceil(d/x),y:Math.ceil(i.sequenceLength/x),z:i.batchSize*i.numHeads},q=[{type:12,data:i.sequenceLength},{type:12,data:S},{type:12,data:d},{type:12,data:i.numHeads},{type:1,data:y},{type:12,data:u},{type:12,data:i.kvSequenceLength}],k=g&&n&&Ie.size(n.dims)>0,Z=["type","type"];k&&Z.push("type"),s&&Z.push("type");let ee=[{dims:c,dataType:t.dataType,gpuDataType:0}];g&&ee.push({dims:l,dataType:t.dataType,gpuDataType:0});let fe=We=>{let Ne=Ze("q",t.dataType,t.dims,v),mt=Ze("key",r.dataType,r.dims,v),jt=[Ne,mt];if(k){let Pr=Ze("past_key",n.dataType,n.dims,v);jt.push(Pr)}s&&jt.push(Ze("attention_bias",s.dataType,s.dims));let Lt=Vt("output",t.dataType,c),dr=[Lt];g&&dr.push(Vt("present_key",t.dataType,l,v));let ar=Tr(1,v),_r=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${x}u; var tileQ: array<${Ne.type.storage}, ${x*x}>; var tileK: array<${Ne.type.storage}, ${x*x}>; ${We.registerUniforms(_r).declareVariables(...jt,...dr)} ${We.mainStart([x,x,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; ${k&&g?` let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} ${g?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${ar}(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; ${k&&g?` if (n + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else { tileK[idx] = key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} ${g?"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 += ${ar}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(v){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: ${v}`)}})()}; output[outputIdx] = ${Lt.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${v};${s!==void 0};${n!==void 0};${e}`,inputDependencies:Z},getRunData:()=>({outputs:ee,dispatchGroup:G,programUniforms:q}),getShaderSource:fe}},wo=(e,t,r,n,s,i)=>{let a=i+s.kvSequenceLength,u=s.nReps?s.nReps:1,d=s.vHiddenSize*u,c=s.kvNumHeads==null&&e>1&&n,g=c?[s.batchSize,s.numHeads,a,s.headSize]:void 0,l=[s.batchSize,s.sequenceLength,d],y=12,v={x:Math.ceil(s.vHeadSize/y),y:Math.ceil(s.sequenceLength/y),z:s.batchSize*s.numHeads},S=[{type:12,data:s.sequenceLength},{type:12,data:a},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:d},{type:12,data:i},{type:12,data:s.kvSequenceLength}],x=c&&n&&Ie.size(n.dims)>0,G=["type","type"];x&&G.push("type");let q=[{dims:l,dataType:t.dataType,gpuDataType:0}];c&&q.push({dims:g,dataType:t.dataType,gpuDataType:0});let k=Z=>{let ee=Ze("probs",t.dataType,t.dims),fe=Ze("v",r.dataType,r.dims),We=[ee,fe];x&&We.push(Ze("past_value",n.dataType,n.dims));let Ne=[Vt("output",t.dataType,l)];c&&Ne.push(Vt("present_value",t.dataType,g));let mt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${y}u; var tileQ: array<${ee.type.value}, ${y*y}>; var tileK: array<${ee.type.value}, ${y*y}>; ${Z.registerUniforms(mt).declareVariables(...We,...Ne)} ${Z.mainStart([y,y,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${x&&c?` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; `:` let offsetB = headIdx * uniforms.N * uniforms.K + n; `} ${c?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${ee.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&&c?` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } `:` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `} ${c?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:G},getRunData:()=>({outputs:q,dispatchGroup:v,programUniforms:S}),getShaderSource:k}},hs=(e,t,r,n,s,i,a,u,d,c,g)=>{let l=Math.min(e.outputCount,1+(a?1:0)+(u?1:0)),y=c.kvNumHeads!==void 0||l>1?c.pastSequenceLength:0,v=y+c.kvSequenceLength,S=d&&Ie.size(d.dims)>0?d:void 0,x=[t,r];c.kvNumHeads===void 0&&l>1&&a&&Ie.size(a.dims)>0&&x.push(a),S&&x.push(S);let G=e.compute(go(l,t,r,a,S,c,g,y),{inputs:x,outputs:c.kvNumHeads===void 0&&l>1?[-1,1]:[-1]})[0];e.compute(Oi(G,c.batchSize*c.numHeads*c.sequenceLength,v),{inputs:[G],outputs:[]});let q=[G,n];c.kvNumHeads===void 0&&l>1&&u&&Ie.size(u.dims)>0&&q.push(u),e.compute(wo(l,G,n,u,c,y),{inputs:q,outputs:c.kvNumHeads===void 0&&l>1?[0,2]:[0]})},yo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,i=t.headSize,a=12,u={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:s},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],g=l=>{let y=Vt("output_q",d[0].dataType,r),v=Vt("output_k",d[0].dataType,r),S=Vt("output_v",d[0].dataType,r),x=Ze("input",d[0].dataType,d[0].dims),G=Ze("weight",d[1].dataType,d[1].dims),q=Ze("bias",d[2].dataType,d[2].dims),k=x.type.storage,Z=[{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 = ${a}u; var tileInput: array<${k}, ${a*a}>; var tileWeightQ: array<${k}, ${a*a}>; var tileWeightK: array<${k}, ${a*a}>; var tileWeightV: array<${k}, ${a*a}>; ${l.registerUniforms(Z).declareVariables(x,G,q,y,v,S)} ${l.mainStart([a,a,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 = ${k}(0); var valueK = ${k}(0); var valueV = ${k}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:c}),getShaderSource:g},{inputs:d,outputs:[-1,-1,-1]})},bo=(e,t)=>{let r=_o(e.inputs,t),[n,s,i]=yo(e,r);return hs(e,n,s,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Mo,vo,zi,xo,Pu=R(()=>{Bt(),Kt(),Xt(),Cr(),sr(),Mo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,i)=>{let a=s.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);s.forEach((u,d)=>{if(u!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},vo=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,i=e[0].dims,a=n?Sr(i[i.length-1]):1,u=s==="NHWC"&&i.length>1?a:1,d=Ie.size(i)/a,c=n,g=c?i.length:i,l=Ze("x",e[0].dataType,e[0].dims,a),y=Ze("scale",e[1].dataType,e[1].dims,u),v=Ze("bias",e[2].dataType,e[2].dims,u),S=Ze("inputMean",e[3].dataType,e[3].dims,u),x=Ze("inputVar",e[4].dataType,e[4].dims,u),G=Vt("y",e[0].dataType,g,a),q=()=>{let Z="";if(n)Z=`let cOffset = ${i.length===1?"0u":s==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(s==="NCHW")Z=` ${G.indicesSet("outputIndices","0","0")} let cOffset = ${G.indicesToOffset("outputIndices")};`;else{Z=`var cIndices = ${y.type.indices}(0); cIndices[0] = outputIndices[${i.length-1}];`;for(let ee=1;ee` const epsilon = ${r}; ${Z.registerUniform("outputSize","u32").declareVariables(l,y,v,S,x,G)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${G.offsetToIndices(`global_idx * ${a}`)}; ${q()} let scale = ${y.getByOffset("cOffset")}; let bias = ${v.getByOffset("cOffset")}; let inputMean = ${S.getByOffset("cOffset")}; let inputVar = ${x.getByOffset("cOffset")}; let x = ${l.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${G.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:k,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...Pt(i)]:[{type:12,data:d}]})}},zi=e=>qt(e),xo=(e,t)=>{let{inputs:r,outputCount:n}=e,s=zi({...t,outputCount:n});if(C.webgpu.validateInputContent&&Mo(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(vo(r,s))}}),To,So,Di,Au=R(()=>{Xt(),sr(),To=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")},So=e=>{let t=e[0].dims,r=e[0].dims[2],n=Ie.size(t)/4,s=e[0].dataType,i=Ze("input",s,t,4),a=Ze("bias",s,[r],4),u=Ze("residual",s,t,4),d=Vt("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:c=>` const channels = ${r}u / 4; ${c.declareVariables(i,a,u,d)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${i.getByOffset("global_idx")} + ${a.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; ${d.setByOffset("global_idx","value")} }`}},Di=e=>{To(e.inputs),e.compute(So(e.inputs))}}),$o,br,Eo,Co,Bi,ko,Po,Li,Ao,Io,Ri,Fo,Oo,Ys,zo,Do,Cs,Ni,Zs,ji,Bo,Lo,Ro,Vi,No,jo,Vo,Ui,Uo,Wo,Wi,Go,qo,Gi,Ho,qi,Hi,Ki,Xi,Qi,Ko,Xo,Yi,Qo,Yo,Zi=R(()=>{Kt(),Xt(),Cr(),sr(),$o=(e,t,r,n,s,i)=>{let a=Math.ceil(t/4),u="";typeof s=="string"?u=`${s}(a)`:u=s("a");let d=Ze("inputData",r,[a],4),c=Vt("outputData",n,[a],4);return` ${e.registerUniform("vec_size","u32").declareVariables(d,c)} ${i??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${d.getByOffset("global_idx")}; ${c.setByOffset("global_idx",u)} }`},br=(e,t,r,n,s,i=e.dataType)=>({name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:a=>$o(a,Ie.size(e.dims),e.dataType,i,r,n),getRunData:a=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(Ie.size(a[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(Ie.size(e.dims)/4)}]})}),Eo=e=>{e.compute(br(e.inputs[0],"Abs","abs"))},Co=e=>{e.compute(br(e.inputs[0],"Acos","acos"))},Bi=e=>{e.compute(br(e.inputs[0],"Acosh","acosh"))},ko=e=>{e.compute(br(e.inputs[0],"Asin","asin"))},Po=e=>{e.compute(br(e.inputs[0],"Asinh","asinh"))},Li=e=>{e.compute(br(e.inputs[0],"Atan","atan"))},Ao=e=>{e.compute(br(e.inputs[0],"Atanh","atanh"))},Io=e=>qt(e),Ri=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(br(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Fo=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Jr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:dn;return qt({min:t,max:r})},Oo=(e,t)=>{let r=e.inputs.length===1?t:Fo(e.inputs),n=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"Clip",s=>`clamp(${s}, clip_min_, clip_max_)`,` const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); `,r.cacheKey),{inputs:[0]})},Ys=e=>{e.compute(br(e.inputs[0],"Ceil","ceil"))},zo=e=>{e.compute(br(e.inputs[0],"Cos","cos"))},Do=e=>{e.compute(br(e.inputs[0],"Cosh","cosh"))},Cs=e=>qt(e),Ni=(e,t)=>{let r=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},Zs=(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)); }`,ji=e=>{let t=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Zs(t)))},Bo=e=>{e.compute(br(e.inputs[0],"Exp","exp"))},Lo=e=>{e.compute(br(e.inputs[0],"Floor","floor"))},Ro=e=>{let t=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Zs(t)))},Vi=(e,t)=>{let r=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},No=e=>{e.compute(br(e.inputs[0],"Not",t=>`!${t}`))},jo=e=>{e.compute(br(e.inputs[0],"Neg",t=>`-${t}`))},Vo=e=>{e.compute(br(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ui=e=>{let t=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Uo=e=>{e.compute(br(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Wo=e=>qt(e),Wi=(e,t)=>{let r=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Go=e=>{e.compute(br(e.inputs[0],"Sin","sin"))},qo=e=>{e.compute(br(e.inputs[0],"Sinh","sinh"))},Gi=e=>{e.compute(br(e.inputs[0],"Sqrt","sqrt"))},Ho=e=>{e.compute(br(e.inputs[0],"Tan","tan"))},qi=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Hi=e=>{e.compute(br(e.inputs[0],"Tanh",qi))},Ki=(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 ${qi("v")}; } `,Xi=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Qi=e=>{let t=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"FastGelu",Xi,Ki(t),void 0,e.inputs[0].dataType))},Ko=(e,t)=>{let r=Tr(e.inputs[0].dataType);return e.compute(br(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},Xo=e=>{e.compute(br(e.inputs[0],"Log","log"))},Yi=(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; } `,Qo=e=>`quick_gelu_impl(${e})`,Yo=(e,t)=>{let r=Tr(e.inputs[0].dataType);e.compute(br(e.inputs[0],"QuickGelu",Qo,Yi(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Zo,Js,Jo,Iu=R(()=>{Xt(),sr(),Zi(),Zo=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")},Js=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Ze("input",e[0].dataType,e[0].dims,4),n=Ze("bias",e[0].dataType,[e[0].dims[2]],4),s=Vt("output",e[0].dataType,t,4),i=Ie.size(t)/4,a=Er(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:u=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${u.declareVariables(r,n,s)} ${Zs(a)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(i)} 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); ${s.setByOffset("global_idx","valueLeft * geluRight")} }`}},Jo=e=>{Zo(e.inputs),e.compute(Js(e.inputs))}}),el,Ji,Tn,tl,rl,nl,ea,sl,il,ta,al,ol,ra,Fu=R(()=>{Kt(),Xt(),sr(),el=(e,t,r,n,s,i,a,u,d,c,g,l)=>{let y,v;typeof u=="string"?y=v=(k,Z)=>`${u}((${k}),(${Z}))`:typeof u=="function"?y=v=u:(y=u.scalar,v=u.vector);let S=Vt("outputData",g,n.length,4),x=Ze("aData",d,t.length,4),G=Ze("bData",c,r.length,4),q;if(s)if(i){let k=Ie.size(t)===1,Z=Ie.size(r)===1,ee=t.length>0&&t[t.length-1]%4===0,fe=r.length>0&&r[r.length-1]%4===0;k||Z?q=S.setByOffset("global_idx",v(k?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"),Z?`${G.type.value}(${G.getByOffset("0")}.x)`:G.getByOffset("global_idx"))):q=` let outputIndices = ${S.offsetToIndices("global_idx * 4u")}; let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",S)}; let offsetB = ${G.broadcastedIndicesToOffset("outputIndices",S)}; ${S.setByOffset("global_idx",v(a||ee?x.getByOffset("offsetA / 4u"):`${x.type.value}(${x.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||fe?G.getByOffset("offsetB / 4u"):`${G.type.value}(${G.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else q=S.setByOffset("global_idx",v(x.getByOffset("global_idx"),G.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let k=(Z,ee,fe="")=>{let We=`aData[indexA${ee}][componentA${ee}]`,Ne=`bData[indexB${ee}][componentB${ee}]`;return` let outputIndices${ee} = ${S.offsetToIndices(`global_idx * 4u + ${ee}u`)}; let offsetA${ee} = ${x.broadcastedIndicesToOffset(`outputIndices${ee}`,S)}; let offsetB${ee} = ${G.broadcastedIndicesToOffset(`outputIndices${ee}`,S)}; let indexA${ee} = offsetA${ee} / 4u; let indexB${ee} = offsetB${ee} / 4u; let componentA${ee} = offsetA${ee} % 4u; let componentB${ee} = offsetB${ee} % 4u; ${Z}[${ee}] = ${fe}(${y(We,Ne)}); `};g===9?q=` var data = vec4(0); ${k("data",0,"u32")} ${k("data",1,"u32")} ${k("data",2,"u32")} ${k("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:q=` ${k("outputData[global_idx]",0)} ${k("outputData[global_idx]",1)} ${k("outputData[global_idx]",2)} ${k("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(x,G,S)} ${l??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${q} }`},Ji=(e,t,r,n,s,i,a=r.dataType)=>{let u=!Ie.areEqual(r.dims,n.dims),d=r.dims,c=Ie.size(r.dims),g=!1,l=!1,y=[u];if(u){let v=Rr.calcShape(r.dims,n.dims,!1);if(!v)throw new Error("Can't perform binary op on the given tensors");d=v,c=Ie.size(d);let S=Ie.size(r.dims)===1,x=Ie.size(n.dims)===1,G=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,q=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;y.push(S),y.push(x),y.push(G),y.push(q);let k=1;for(let Z=1;Zv.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:v=>el(v,r.dims,n.dims,d,g,u,l,s,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Ie.size(d)/4)},...Pt(r.dims,n.dims,d)]})}},Tn=(e,t,r,n,s,i)=>{e.compute(Ji(t,s??"",e.inputs[0],e.inputs[1],r,n,i))},tl=e=>{Tn(e,"Add",(t,r)=>`${t}+${r}`)},rl=e=>{Tn(e,"Div",(t,r)=>`${t}/${r}`)},nl=e=>{Tn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},ea=e=>{Tn(e,"Mul",(t,r)=>`${t}*${r}`)},sl=e=>{let t=Ze("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Tn(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},il=e=>{Tn(e,"Sub",(t,r)=>`${t}-${r}`)},ta=e=>{Tn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},al=e=>{Tn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},ol=e=>{Tn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},ra=e=>{Tn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),ll,na,ul,dl,cl,pl,Ou=R(()=>{Kt(),Xt(),Cr(),sr(),ll=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,i=n.dims.length;e.forEach((a,u)=>{if(u!==r){if(a.dataType!==s)throw new Error("input tensors should be one type");if(a.dims.length!==i)throw new Error("input tensors should have the same shape");a.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error("non concat dimensions must match")})}})},na=(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; }`,ul=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=Ie.size(r),i=new Array(e.length),a=new Array(e.length),u=0,d=[],c=[],g=[{type:12,data:s}];for(let x=0;x`uniforms.sizeInConcatAxis${x}`).join(","),S=x=>` ${(()=>{x.registerUniform("outputSize","u32");for(let G=0;G(${v}); ${y} -= sizeInConcatAxis[inputIndex - 1u]; } ${ul(a,l)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:g}),getShaderSource:S}},cl=(e,t)=>{let r=e.inputs,n=r[0].dims,s=Ie.normalizeAxis(t.axis,n.length);ll(r,s);let i=n.slice();i[s]=r.reduce((u,d)=>u+(d.dims.length>s?d.dims[s]:0),0);let a=r.filter(u=>Ie.size(u.dims)>0);e.compute(dl(a,s,i,r[0].dataType),{inputs:a})},pl=e=>qt({axis:e.axis})}),Gn,zn,qn,sa,Dn=R(()=>{Kt(),Xt(),Gn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},zn=(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})},qn=(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"})},sa=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=e?.activation_params||[Jr,dn];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}}),an,ia,Pn=R(()=>{an=(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.`)}},ia=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),aa,hl=R(()=>{aa=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)); } `}),fl,ml,ks,oa,_l,ei,gl,Ps,ti=R(()=>{Kt(),Xt(),sr(),Dn(),Pn(),fl=(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":""}); `,ml=(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];"} }`,ks=(e,t,r="f32",n,s=!1,i=32,a=!1,u=32)=>{let d=t[1]*e[1],c=t[0]*e[0],g=s?d:i,l=s?i:d,y=g/t[0],v=i/t[1];if(!((s&&y===4&&e[1]===4||!s&&(y===3||y===4))&&g%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${y} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${y} must be 3 or 4. tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${g/y}>, ${l}>; var mm_Bsub: array, ${c/e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${y}; const tileInner = ${i}; @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 = ${a?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${d}; let num_tiles = ${a?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${v}; 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; ${fl(s,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${v}; 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]; ${y===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${ml(s,y)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},oa=(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":""}); `,_l=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ei=(e,t,r="f32",n,s=!1,i=32,a=!1,u=32,d=!1)=>{let c=e[1]*t[1],g=e[0]*t[0],l=s?c:i,y=s?i:c;if(!(y%t[1]===0&&l%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${y} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${l} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let v=y/t[1],S=l/t[0],x=i/t[1],G=d?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${c}; let globalColStart = i32(workgroupId.x) * ${g}; // 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 < ${y}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${l}; inputCol = inputCol + ${t[0]}) { ${oa(s,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${s?`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) * ${c}; let tileRowA = i32(localId.y) * ${v}; let tileColA = i32(localId.x) * ${S}; let tileRowB = i32(localId.y) * ${x}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${v}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${S}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${oa(s,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${x}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${_l(s)} 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, ${y}>; var mm_Bsub : array, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${i}; @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 = ${a?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${a?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; var acc : array, rowPerThread>; ${G} } `},gl=(e,t,r,n,s,i=!1)=>{let[a,u,d]=s,[c,g,l,y]=n,v=cs(a,d),S=cs(u,d),x=Er(n[0].type.tensor),G=()=>{let k=g.rank,Z=c.rank,ee=`var aIndices: ${g.type.indices};`;for(let fe=k-2-1,We=Z-1;fe>=0;fe--,We--)ee+=` aIndices[${fe}] = ${Z>1?`batchIndices[${We}]`:"batchIndices"};`;return v.forEach(fe=>{ee+=` aIndices[${fe}] = 0;`}),ee+=` aIndices[${k-2}] = u32(row); aIndices[${k-1}] = u32(colIn);`,ee},q=()=>{let k=l.rank,Z=c.rank,ee=`var bIndices: ${l.type.indices};`;for(let fe=k-2-1,We=Z-1;fe>=0;fe--,We--)ee+=` bIndices[${fe}] = ${Z>1?`batchIndices[${We}]`:"batchIndices"};`;return S.forEach(fe=>{ee+=` bIndices[${fe}] = 0;`}),ee+=` bIndices[${k-2}] = u32(row); bIndices[${k-1}] = u32(colIn);`,ee};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${an(e,x)} { var value = ${an(e,x)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${G()} value = ${g.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${c.type.indices}) -> ${an(e,x)} { var value = ${an(e,x)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${q()} value = ${l.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${an(e,x)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${i?"bias[colIn]":`${an(e,x)}(bias[row])`};`:""} ${r} ${y.setByIndices("vec3(coords)","value")} } } `},Ps=(e,t,r,n,s=!1,i)=>{let a=e[0].dims,u=e[1].dims,d=a.slice(0,-2),c=u.slice(0,-2),g=n?n.slice(0,-2):r.slice(0,-2),l=Ie.size(g),y=a[a.length-2],v=a[a.length-1],S=u[u.length-1],x=v%4===0&&S%4===0,G=y<=8?[4,1,1]:[4,4,1],q=[8,8,1],k=[Math.ceil(S/q[0]/G[0]),Math.ceil(y/q[1]/G[1]),Math.ceil(l/q[2]/G[2])],Z=x?4:1,ee=[...d,y,v/Z],fe=ee.length,We=[...c,v,S/Z],Ne=We.length,mt=[l,y,S/Z],jt=[{type:6,data:y},{type:6,data:S},{type:6,data:v}];zn(t,jt),jt.push(...Pt(g,ee,We));let Lt=["rank","rank"],dr=e.length>2;dr&&(jt.push(...Pt(e[2].dims)),Lt.push("rank")),jt.push(...Pt(mt));let ar=_r=>{let Pr=g.length,hr=wi("batchDims",e[0].dataType,Pr,1),Yt=Er(e[0].dataType),Ar=Ze("a",e[0].dataType,fe,Z),Br=Ze("b",e[1].dataType,Ne,Z),tr=Vt("result",e[0].dataType,mt.length,Z),gr=[Ar,Br];if(dr){let Ur=s?Z:1;gr.push(Ze("bias",e[2].dataType,e[2].dims.length,Ur))}let Ke=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];qn(t,Ke);let $t=Er(tr.type.tensor),cr=Gn(t,tr.type.value,$t),Vr=gl(Z,dr,cr,[hr,Ar,Br,tr],[d,c,g],s);return` ${_r.registerUniforms(Ke).registerInternalVariables(hr).declareVariables(...gr,tr)} ${Vr} ${x?ks(G,q,Yt,hr):ei(G,q,Yt,hr)} `};return{name:"MatMul",shaderCache:{hint:`${G};${t.activation};${x};${s}`,inputDependencies:Lt},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:jt}),getShaderSource:ar}}}),wl,yl,ri=R(()=>{Kt(),wn(),sr(),Dn(),Pn(),hl(),ti(),wl=(e,t,r,n,s=!1,i,a=4,u=4,d=4,c="f32")=>{let g=jt=>{switch(jt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${jt} is not supported.`)}},l=jt=>{switch(jt){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 ${jt} is not supported.`)}},y=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,v=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,S=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",G=e?"row":"col",q=e?"col":"row",k=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${G} / outWidth; let outCol = ${G} % outWidth; let WRow = ${q} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${q} / 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 = ${q} % inChannels; var resData = ${an(a,c)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${S} && xCol >= 0 && xCol < ${x}) { ${y} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${g(a)} } return resData;`,Z=e?t&&n?` let col = colIn * ${a}; ${k}`:` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${k} } return ${an(a,c)}(0.0);`:n&&r?` let col = colIn * ${a}; ${k}`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${k} } return ${an(a,c)}(0.0);`,ee=`${l(u)}`,fe=an(d,c),We=an(e?a:u,c),Ne=an(e?u:a,c),mt=Gn(i,fe,c);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${We} { ${e?Z:ee} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ne} { ${e?ee:Z} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${fe}) { let col = colIn * ${d}; 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])"}; ${v} ${ia(s)} ${mt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},yl=(e,t,r,n,s,i,a,u,d)=>{let c=t.format==="NHWC",g=c?e[0].dims[3]:e[0].dims[1],l=r[0],y=c?r[2]:r[3],v=c?r[1]:r[2],S=c?r[3]:r[1],x=c&&(g%4===0||g%3===0)&&S%4===0,G=c?S:y*v,q=c?y*v:S,k=[8,8,1],Z=n<=8?[4,1,1]:[4,4,1],ee=[Math.ceil(G/k[0]/Z[0]),Math.ceil(q/k[1]/Z[1]),Math.ceil(l/k[2]/Z[2])];Nr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${ee}`);let fe=x?c&&g%4!==0?3:4:1,We=k[1]*Z[1],Ne=k[0]*Z[0],mt=Math.max(k[0]*fe,k[1]),jt=n%We===0,Lt=s%Ne===0,dr=i%mt===0,ar=x?[fe,4,4]:[1,1,1],_r=[{type:6,data:n},{type:6,data:s},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];zn(t,_r),_r.push(...Pt(e[0].dims,e[1].dims));let Pr=["rank","rank"];a&&(_r.push(...Pt(e[2].dims)),Pr.push("rank")),_r.push(...Pt(r));let hr=Yt=>{let Ar=[{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}];qn(t,Ar);let Br=x?4:1,tr=Er(e[0].dataType),gr=` fn setOutputAtIndex(flatIndex : i32, value : ${x?`vec4<${tr}>`:tr}) { result[flatIndex] = ${x?`vec4<${tr}>`:tr}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${x?`vec4<${tr}>`:tr}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${x?"/ 4":""}, value); }`,Ke=Ze("x",e[0].dataType,e[0].dims.length,fe===3?1:fe),$t=Ze("w",e[1].dataType,e[1].dims.length,Br),cr=[Ke,$t],Vr=Vt("result",e[0].dataType,r.length,Br);if(a){let Ur=Ze("bias",e[2].dataType,e[2].dims.length,Br);cr.push(Ur),gr+=` fn getBiasByOutputCoords(coords : vec4) -> ${x?`vec4<${tr}>`:tr} { return bias[coords.${c?"w":"y"}${x?"/ 4":""}]; }`}return` ${aa("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 }; ${Yt.registerUniforms(Ar).declareVariables(...cr,Vr)} ${gr} ${wl(c,jt,Lt,dr,a,t,ar[0],ar[1],ar[2],tr)} ${x?ks(Z,k,tr,void 0,!c,mt):ei(Z,k,tr,void 0,!c,mt,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${fe};${x};${jt};${Lt};${dr};${We};${Ne};${mt}`,inputDependencies:Pr},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:ee[0],y:ee[1],z:ee[2]},programUniforms:_r}),getShaderSource:hr}}}),bl,la,As,Ml,Is,vl,xl,Tl,Wd=R(()=>{Kt(),wn(),Xt(),sr(),Dn(),Pn(),bl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,As=(e,t)=>t<=1?e:e+(e-1)*(t-1),Ml=(e,t,r,n=1)=>{let s=As(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},Is=(e,t,r,n,s)=>{s==null&&(s=Ml(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*s>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*s)/n[a]+1));return i},vl=(e,t,r,n,s,i,a,u,d,c)=>{let g,l,y,v;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let S=Is([t,r,n,1],[u,d,c],1,[s,i,a],e);l=S[0],y=S[1],v=S[2]}else if(Array.isArray(e)){if(!e.every((x,G,q)=>x===q[0]))throw Error(`Unsupported padding parameter: ${e}`);g={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let S=Is([t,r,n,1],[u,d,c],1,[s,i,a],e[0]);l=S[0],y=S[1],v=S[2]}else if(e==="SAME_UPPER"){l=Math.ceil(t/s),y=Math.ceil(r/i),v=Math.ceil(n/a);let S=(l-1)*s+u-t,x=(y-1)*i+d-r,G=(v-1)*a+c-n,q=Math.floor(S/2),k=S-q,Z=Math.floor(x/2),ee=x-Z,fe=Math.floor(G/2),We=G-fe;g={top:Z,bottom:ee,left:fe,right:We,front:q,back:k}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:l,outHeight:y,outWidth:v}},xl=(e,t,r,n,s,i=!1,a="channelsLast")=>{let u,d,c,g,l;if(a==="channelsLast")[u,d,c,g,l]=e;else if(a==="channelsFirst")[u,l,d,c,g]=e;else throw new Error(`Unknown dataFormat ${a}`);let[y,,v,S,x]=t,[G,q,k]=la(r),[Z,ee,fe]=la(n),We=As(v,Z),Ne=As(S,ee),mt=As(x,fe),{padInfo:jt,outDepth:Lt,outHeight:dr,outWidth:ar}=vl(s,d,c,g,G,q,k,We,Ne,mt),_r=i?y*l:y,Pr=[0,0,0,0,0];return a==="channelsFirst"?Pr=[u,_r,Lt,dr,ar]:a==="channelsLast"&&(Pr=[u,Lt,dr,ar,_r]),{batchSize:u,dataFormat:a,inDepth:d,inHeight:c,inWidth:g,inChannels:l,outDepth:Lt,outHeight:dr,outWidth:ar,outChannels:_r,padInfo:jt,strideDepth:G,strideHeight:q,strideWidth:k,filterDepth:v,filterHeight:S,filterWidth:x,effectiveFilterDepth:We,effectiveFilterHeight:Ne,effectiveFilterWidth:mt,dilationDepth:Z,dilationHeight:ee,dilationWidth:fe,inShape:e,outShape:Pr,filterShape:t}},Tl=(e,t,r,n,s,i)=>{let a=i==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((G,q)=>q)},c=[Math.ceil(bl(d.x.map(G=>r[G]))/u[0]),1,1];Nr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let g=1,l=Ie.size(r),y=[{type:12,data:l},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];zn(t,y),y.push(...Pt(e[0].dims,e[1].dims));let v=["rank","rank"],S=e.length===3;S&&(y.push(...Pt(e[2].dims)),v.push("rank")),y.push(...Pt(r));let x=G=>{let q=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];qn(t,q);let k=1,Z=Er(e[0].dataType),ee=Ze("x",e[0].dataType,e[0].dims.length,g),fe=Ze("W",e[1].dataType,e[1].dims.length,k),We=[ee,fe],Ne=Vt("result",e[0].dataType,r.length,k),mt="";if(S){let dr=Ze("bias",e[2].dataType,e[2].dims.length,k);We.push(dr),mt+=` fn getBiasByOutputCoords(coords : array) -> ${Z} { return bias[${a?Nt("coords",4,5):Nt("coords",1,5)}]; }`}let jt=an(g,Z),Lt=Gn(t,jt,Z);return` ${mt} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ee.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${fe.getByIndices("aIndices")}; } ${G.registerUniforms(q).declareVariables(...We,Ne)} ${G.mainStart()} ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ne.offsetToIndices("global_idx")}; let batch = ${Nt("coords",0,ee.rank)}; let d2 = ${a?Nt("coords",ee.rank-1,ee.rank):Nt("coords",1,ee.rank)}; let xFRCCorner = vec3(${a?Nt("coords",1,ee.rank):Nt("coords",2,ee.rank)}, ${a?Nt("coords",2,ee.rank):Nt("coords",3,ee.rank)}, ${a?Nt("coords",3,ee.rank):Nt("coords",4,ee.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${a?Nt("uniforms.x_shape",1,ee.rank):Nt("uniforms.x_shape",2,ee.rank)}; let xShapeZ = ${a?Nt("uniforms.x_shape",2,ee.rank):Nt("uniforms.x_shape",3,ee.rank)}; let xShapeW = ${a?Nt("uniforms.x_shape",3,ee.rank):Nt("uniforms.x_shape",4,ee.rank)}; let xShapeU = ${a?Nt("uniforms.x_shape",4,ee.rank):Nt("uniforms.x_shape",1,ee.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) { ${a?`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) { ${a?`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) { ${a?`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) { ${a?`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); } } } } ${S?"value = value + getBiasByOutputCoords(coords)":""}; ${Lt} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${g};${S}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:y}),getShaderSource:x}}}),Sl,$l,zu=R(()=>{Kt(),Xt(),sr(),ha(),Dn(),Sl=(e,t,r)=>{let n=e.length>2,s=n?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,u=a[0]/t.group,d=t.format==="NHWC",c=ni(i,a,t.dilations,t.pads,t.strides,d),g=Ie.size(c),l=[{type:12,data:g},{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:u}];zn(t,l),l.push(...Pt(i,a));let y=["rank","rank"];n&&(l.push(...Pt(e[2].dims)),y.push("rank")),l.push(...Pt(c));let v=S=>{let x=Vt("output",e[0].dataType,c.length),G=Er(x.type.tensor),q=Gn(t,x.type.value,G),k=Ze("x",e[0].dataType,i.length),Z=Ze("w",e[1].dataType,a.length),ee=[k,Z];n&&ee.push(Ze("b",e[2].dataType,e[2].dims.length));let fe=[{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"}];return qn(t,fe),` ${S.registerUniforms(fe).declareVariables(...ee,x)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${x.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${d?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${x.type.value} = ${x.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + 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[${d?1: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[${d?2:3}]) { continue; } let xVal = ${d?k.get("batch","xHeight","xWidth","input_channel"):k.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${Z.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${s} ${q} ${x.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:y},getRunData:()=>({outputs:[{dims:r?r(c):c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:l}),getShaderSource:v}},$l=(e,t,r,n)=>{let s=e.length>2,i=Sr(r[3]),a=Sr(r[2]),u=Ie.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],g=[r[0],r[1],r[2],r[3]/i],l=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];zn(t,l),l.push(...Pt(d,c,g));let y=(a-1)*t.strides[1]+c[1],v=S=>{let x=Vt("output",e[0].dataType,g.length,i),G=Er(x.type.tensor),q=Gn(t,x.type.value,G),k=Ze("x",e[0].dataType,d.length,i),Z=Ze("w",e[1].dataType,c.length,i),ee=[k,Z];s&&ee.push(Ze("b",e[2].dataType,e[2].dims,i));let fe=s?"value += b[output_channel];":"",We=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return qn(t,We),` ${S.registerUniforms(We).declareVariables(...ee,x)} ${S.mainStart()} ${S.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] / ${a}u; let col = (index1 % width1) * ${a}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<${k.type.value}, ${y}>; var values: array<${x.type.value}, ${a}>; 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 < ${c[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 < ${y}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${k.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${k.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { let w_val = ${Z.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${a}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${a}u; i++) { var value = values[i]; ${fe} ${q} ${x.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${a};${y};${c[0]};${c[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l}),getShaderSource:v}}}),Jn,El,Cl,kl=R(()=>{Kt(),Xt(),ti(),sr(),Dn(),Jn=(e,t,r,n,s=!1,i)=>{let a=e[0].dims,u=e[1].dims,d=a[a.length-2],c=u[u.length-1],g=a[a.length-1],l=Sr(c),y=Sr(g),v=Sr(d),S=Ie.size(r)/l/v,x=e.length>2,G=n?n.slice(0,-2):r.slice(0,-2),q=[Ie.size(G),d,c],k=[{type:12,data:S},{type:12,data:d},{type:12,data:c},{type:12,data:g}];zn(t,k),k.push(...Pt(G,a,u)),x&&k.push(...Pt(e[2].dims)),k.push(...Pt(q));let Z=ee=>{let fe=wi("batch_dims",e[0].dataType,G.length),We=Ze("a",e[0].dataType,a.length,y),Ne=Ze("b",e[1].dataType,u.length,l),mt=Vt("output",e[0].dataType,q.length,l),jt=Er(mt.type.tensor),Lt=Gn(t,mt.type.value,jt),dr=[We,Ne],ar="";if(x){let gr=s?l:1;dr.push(Ze("bias",e[2].dataType,e[2].dims.length,gr)),ar=`${s?`value += bias[col / ${gr}];`:`value += ${mt.type.value}(bias[row + i]);`}`}let _r=a.slice(0,-2),Pr=u.slice(0,-2),hr=cs(_r,G),Yt=cs(Pr,G),Ar=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];qn(t,Ar);let Br=(gr,Ke)=>{let $t=gr.rank,cr=gr.name;if($t===2)return`var ${cr}_indices = ${gr.type.indices}(0u, 0u);`;let Vr=fe.rank,Ur=`var ${cr}_indices: ${gr.type.indices};`;for(let Rn=$t-2-1,Kn=Vr-1;Rn>=0;Rn--,Kn--)Ur+=` ${cr}_indices[${Rn}] = ${Vr>1?`batch_indices[${Kn}]`:"batch_indices"};`;return Ke.forEach(Rn=>{Ur+=` ${cr}_indices[${Rn}] = 0;`}),Ur+=`${cr}_indices[${$t-2}] = 0u; ${cr}_indices[${$t-1}] = 0u;`,Ur},tr=()=>{let gr=`var a_data: ${We.type.value};`;for(let Ke=0;Ke; for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) { ${tr()} } for (var i = 0u; i < ${v}u; i++) { var value = values[i]; ${ar} ${Lt} let cur_indices = ${mt.type.indices}(batch, row + i, col); let offset = ${mt.indicesToOffset("cur_indices")}; ${mt.setByOffset(`offset / ${l}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${l};${y};${v};${s}`,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:k}),getShaderSource:Z}},El=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.")},Cl=e=>{El(e.inputs);let t=Rr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&n<8?e.compute(Jn(e.inputs,{activation:""},t)):e.compute(Ps(e.inputs,{activation:""},t))}}),ni,si,ii,ua,da,ca,Pl,Al,pa,ha=R(()=>{Xt(),ri(),Wd(),ti(),zu(),Dn(),kl(),ps(),ni=(e,t,r,n,s,i)=>{let a=e[0],u=e.slice(i?1:2,i?3:4),d=u.length,c=t[0],g=t.slice(2).map((y,v)=>y+(y-1)*(r[v]-1)),l=u.map((y,v)=>y+n[v]+n[v+d]).map((y,v)=>Math.floor((y-g[v]+s[v])/s[v]));return l.splice(0,0,a),l.splice(i?3:1,0,c),l},si=[2,3,1,0],ii=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ua=(e,t)=>{let r=e.kernelShape.slice();for(let i=2;i{let t=sa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,i=e.group,a=e.kernel_shape,u=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:i,kernelShape:a,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},ca=(e,t,r,n)=>{let s=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let We=ni(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,s),Ne=e.kernelCustomData.wT??e.compute(kn(t[1],si),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ne);let mt=[t[0],Ne];t.length===3&&mt.push(t[2]),e.compute($l(mt,r,We,n),{inputs:mt})}else e.compute(Sl(t,r,n));return}let i=t.length===3,a=t[0].dims[s?1:2],u=t[0].dims[s?2:3],d=t[0].dims[s?3:1],c=t[1].dims[2],g=t[1].dims[3],l=ni(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,s),y=l[s?1:2],v=l[s?2:3],S=l[s?3:1],x=s&&c===a&&g===u&&r.pads[0]===0&&r.pads[1]===0;if(x||c===1&&g===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let We=l[0],Ne,mt,jt,Lt=[];if(s){let _r=e.kernelCustomData.wT??e.compute(kn(t[1],si),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=_r),x){let Pr=a*u*d;Ne=t[0].reshape([1,We,Pr]),mt=_r.reshape([1,Pr,S]),jt=[1,We,S]}else Ne=t[0].reshape([We,a*u,d]),mt=_r.reshape([1,d,S]),jt=[We,y*v,S];Lt.push(Ne),Lt.push(mt)}else Ne=t[0].reshape([We,d,a*u]),mt=t[1].reshape([1,S,d]),jt=[We,S,y*v],Lt.push(mt),Lt.push(Ne);i&&Lt.push(t[2]);let dr=jt[2],ar=Lt[0].dims[Lt[0].dims.length-1];dr<8&&ar<8?e.compute(Jn(Lt,r,l,jt,s,n),{inputs:Lt}):e.compute(Ps(Lt,r,l,jt,s,n),{inputs:Lt});return}let G=!0,q=e.kernelCustomData.wT??e.compute(kn(t[1],si),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=q);let k=[t[0],q];i&&k.push(t[2]);let Z=s?y*v:S,ee=s?S:y*v,fe=c*g*d;e.compute(yl(k,r,l,Z,ee,fe,i,G,n),{inputs:k})},Pl=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=ua({...t,pads:s,strides:i,dilations:a,kernelShape:u},n);ca(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Al=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=ua(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,a=xl(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Tl(t,s,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},pa=(e,t)=>{if(ii(e.inputs,t),e.inputs[0].dims.length===3)Pl(e,t);else if(e.inputs[0].dims.length===5)Al(e,e.inputs,t);else{let r=ua(t,e.inputs);ca(e,e.inputs,r)}}}),Il,Fl,Ol=R(()=>{Kt(),wn(),sr(),Dn(),Pn(),hl(),ti(),Il=(e,t=!1,r,n,s=4)=>{let i=G=>{switch(G){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${n}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${G} is not supported.`)}},a=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,u=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",c=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",g=e?"row":"col",l=e?"col":"row",y=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${g} / outWidth; let outCol = ${g} % outWidth; let WRow = ${l} / (uniforms.filter_dims[1] * inChannels); let WCol = ${l} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${c}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${l} % inChannels; ${a} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,v=e?` let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${y} } return ${n}(0.0);`:` let col = colIn * ${s}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${y} } return ${n}(0.0);`,S=` let col = colIn * ${s}; let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${i(s)} } return ${n}(0.0); `,x=Gn(r,n);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?v:S} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e?S:v} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${s}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${u} ${ia(t)} ${x} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; } }`},Fl=(e,t,r,n,s,i,a,u)=>{let d=t.format==="NHWC",c=d?e[0].dims[3]:e[0].dims[1],g=r[0],l=d?r[2]:r[3],y=d?r[1]:r[2],v=d?r[3]:r[1],S=d&&c%4===0&&c%3&&v%4===0,x=d?v:l*y,G=d?l*y:v,q=[8,8,1],k=n<=8?[4,1,1]:[4,4,1],Z=[Math.ceil(x/q[0]/k[0]),Math.ceil(G/q[1]/k[1]),Math.ceil(g/q[2]/k[2])];Nr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${Z}`);let ee=S?4:1,fe=Math.max(q[0]*ee,q[1]),We=S?4:1,Ne=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],mt=[Ne[0]+(t.dilations[0]<=1?0:(Ne[0]-1)*(t.dilations[0]-1)),Ne[1]+(t.dilations[1]<=1?0:(Ne[1]-1)*(t.dilations[1]-1))],jt=[mt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),mt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Lt=[{type:6,data:n},{type:6,data:s},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Ne},{type:6,data:jt}];zn(t,Lt),Lt.push(...Pt(e[0].dims,e[1].dims));let dr=["rank","rank"];a&&(Lt.push(...Pt(e[2].dims)),dr.push("rank")),Lt.push(...Pt(r));let ar=_r=>{let Pr=Ze("x",e[0].dataType,e[0].dims.length,We),hr=Ze("w",e[1].dataType,e[1].dims.length,1),Yt=Vt("result",e[0].dataType,r.length,We),Ar=[Pr,hr],Br="";if(a){let Ke=Ze("bias",e[2].dataType,e[2].dims.length,We);Ar.push(Ke),Br+=` fn getBiasByOutputCoords(coords : vec4) -> ${Ke.type.value} { return bias[coords.${d?"w":"y"}${S?"/ 4":""}]; }`}let tr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Ne.length},{name:"pads",type:"i32",length:jt.length}];qn(t,tr);let gr=Er(e[0].dataType,1);if(gr!=="f16"&&gr!=="f32")throw new Error(`elemType ${gr} is not supported.`);return` ${aa("uniforms.result_strides")} ${_r.registerUniforms(tr).declareVariables(...Ar,Yt)}; ${Br} ${Il(d,a,t,Pr.type.value,ee)} ${S?ks(k,q,gr,void 0,!d,fe):ei(k,q,gr,void 0,!d,fe,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${k};${q};${S}`,inputDependencies:dr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Z[0],y:Z[1],z:Z[2]},programUniforms:Lt}),getShaderSource:ar}}}),zl,fa,Dl=R(()=>{Kt(),wn(),Xt(),sr(),zl=(e,t,r,n,s,i=!1,a,u,d=!1)=>{let c=d?1:2,g=d?2:3,l=d?3:1,y=i?2:1,v=` fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${a}>`:a}) { result[flatIndex] = ${i?`vec4<${a}>`:a}(value); }`;n&&(v+=` fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${a}>`:a} { return bias[coords.${d?"w":"y"}${i?"/ 4":""}]; }`);let S=i?4:1,x=Ze("W",t[1].dataType,t[1].dims.length,S),G=Ze("Dy",t[0].dataType,t[0].dims.length,S),q=[G,x];n&&q.push(Ze("bias",t[2].dataType,[r[l]].length,S));let k=Vt("result",t[0].dataType,r.length,S),Z=`{ let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${s?"global_id.y":"workgroup_id.y"} * ${y}; let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${y}>; for (var i = 0; i < ${y}; i++) { dotProd[i] = vec4<${a}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y); let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${G.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${G.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${l}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${G.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${G.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${y}; i = i + 1) { let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${a}>(0.0)`}; ${k.set("batch","r","c + i","d1","value")}; } }`,ee=` let outputIndices = ${k.offsetToIndices("global_idx")}; let batch = ${k.indicesGet("outputIndices",0)}; let d1 = ${k.indicesGet("outputIndices",l)}; let r = ${k.indicesGet("outputIndices",c)}; let c = ${k.indicesGet("outputIndices",g)}; 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 = ${a}(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 = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${c}]) || 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 = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${g}]) || 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 = ${d?G.get("batch","idyR","idyC","inputChannel"):G.get("batch","inputChannel","idyR","idyC")}; let wValue = ${x.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n?"bias[d1]":`${a}(0.0)`}; ${k.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(u).declareVariables(...q,k)} ${v} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${i?Z:ee}}`},fa=(e,t,r)=>{let n=e.length>2,s=t.outputShape,i=Ie.size(s),a=[Math.ceil(i/64),1,1];Nr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let u=t.format==="NHWC",d=["rank","rank"],c=[t.strides[0],t.strides[1]],g=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],l=[t.dilations[0],t.dilations[1]],y=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],v=[y[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),y[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],S=!1,x=t.group,G=e[1].dims,q=G[0]/x,k=G[1],Z=[{type:12,data:i},{type:12,data:c},{type:12,data:g},{type:12,data:l},{type:12,data:y},{type:6,data:v},{type:12,data:q},{type:12,data:k},...Pt(e[0].dims,e[1].dims)];n&&(Z.push(...Pt(e[2].dims)),d.push("rank")),Z.push(...Pt(s));let ee=a[1]===1&&a[2]===1,fe=We=>{let Ne=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:c.length},{name:"filter_dims",type:"u32",length:g.length},{name:"dilations",type:"u32",length:g.length},{name:"effective_filter_dims",type:"u32",length:y.length},{name:"pads",type:"i32",length:v.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],mt=Er(e[0].dataType);return`${zl(We,e,s,n,ee,S,mt,Ne,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:Z}),getShaderSource:fe}}}),Bl,Ll,ai,ma,Rl,Nl,jl,_a,oi,Du,Bu=R(()=>{Ol(),Dl(),Dn(),ps(),Bl=(e,t,r,n,s,i)=>(e-1)*t+r+(n-1)*s+1-i,Ll=(e,t,r,n,s)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=i,r[s]=e-i):t==="SAME_LOWER"&&(r[n]=e-i,r[s]=i)},ai=(e,t,r,n,s,i,a,u,d,c)=>{let g=e.length-2,l=c.length===0;if(d.length===0)for(let S=0;S{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((l,y)=>l*y,1)===0){r.length=0;for(let l=2;ll+y,0)===0){let l=t[0].dims.length-2;d=new Array(l).fill(1)}let c=e.strides.slice();if(c.reduce((l,y)=>l+y,0)===0){let l=t[0].dims.length-2;c=new Array(l).fill(1)}ai(u,r,d,e.autoPad,e.group,s,c,n,a,i);let g=Object.assign({},e);return Object.assign(g,{kernelShape:r,pads:s,outputPadding:a,outputShape:i,dilations:d,strides:c}),g},Rl=e=>{let t=sa(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,i=e.group,a=e.kernelShape,u=e.pads,d=e.strides,c=e.wIsConst(),g=e.outputPadding,l=e.outputShape;return{autoPad:n,format:r,dilations:s,group:i,kernelShape:a,outputPadding:g,outputShape:l,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Nl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((a,u)=>a+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((a,u)=>a+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((a,u)=>a+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((a,u)=>a+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},jl=[2,3,1,0],_a=(e,t,r)=>{let n=ma(r,t),s=r.format==="NHWC",i=n.outputShape,a=i[s?3:1],u=t[0].dims[s?3:1];if(n.group!==1||a===1&&u===1){e.compute(fa(t,n));return}let d=i[s?1:2],c=i[s?2:3],g=t[1].dims[2],l=t[1].dims[3],y=s?d*c:a,v=s?a:d*c,S=g*l*u,x=!0,G=e.kernelCustomData.wT??e.compute(kn(t[1],jl),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=G);let q=[t[0],G],k=t.length===3;k&&(!s&&t[2].dims.length===1?q.push(t[2].reshape([t[2].dims[0],1,1])):q.push(t[2])),e.compute(Fl(q,n,i,y,v,S,k,x),{inputs:q})},oi=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],a=[1].concat(a),i=[1].concat(i),s=[1].concat(s);let d=ma({...t,pads:u,strides:a,dilations:i,kernelShape:s},n);e.compute(fa(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},Du=(e,t)=>{Nl(e.inputs,t),e.inputs[0].dims.length===3?oi(e,t):_a(e,e.inputs,t)}}),Vl,ga,Ul,Lu=R(()=>{Kt(),Xt(),Cr(),sr(),Vl=(e,t,r,n)=>{let s=Ie.size(t),i=t.length,a=Ze("input",e,i),u=Vt("output",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=Ie.normalizeAxis(d,i),g=l=>{let y=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,v=Nt("uniforms.input_shape","uniforms.axis",i),S=n.reverse?y+(n.exclusive?" + 1":""):"0",x=n.reverse?v:y+(n.exclusive?"":" + 1");return` ${l.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,u)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${u.offsetToIndices("global_idx")}; var sum = ${u.type.value}(0); let first : i32 = ${S}; let last : i32 = ${x}; for (var i : i32 = first; i < last; i++) { ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${a.getByIndices("inputIndices")}; } ${u.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:c},...Pt(t,t)]}),getShaderSource:g}},ga=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(Vl(n,r,s,t),{inputs:[0]})},Ul=e=>{let t=e.exclusive===1,r=e.reverse===1;return qt({exclusive:t,reverse:r})}}),wa,Wl,Gl,ya,Ru,Gd=R(()=>{Kt(),Xt(),Cr(),sr(),wa=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.")},Wl=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let i=0;i{let r,n,s,i,a,u,d=t.format==="NHWC",c=t.blocksize,g=t.mode==="DCR";d?([r,n,s,i]=e.dims,a=g?[r,n,s,c,c,i/c**2]:[r,n,s,i/c**2,c,c],u=g?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=g?[r,c,c,i/c**2,n,s]:[r,i/c**2,c,c,n,s],u=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let l=e.reshape(a),y=l.dims.length,v=e.dataType,S=Ze("a",v,y),x=Vt("output",v,y),G=q=>` ${q.registerUniform("output_size","u32").declareVariables(S,x)} ${Wl(u,y,S,x)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${x.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${x.setByOffset("global_idx",S.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:q=>{let k=d?[r,n*c,s*c,i/c**2]:[r,i/c**2,n*c,s*c],Z=Ie.size(k),ee=l.dims,fe=Ie.sortBasedOnPerm(ee,u);return{outputs:[{dims:k,dataType:q[0].dataType}],dispatchGroup:{x:Math.ceil(Z/64)},programUniforms:[{type:12,data:Z},...Pt(ee,fe)]}},getShaderSource:G}},ya=(e,t)=>{wa(e.inputs),e.compute(Gl(e.inputs[0],t))},Ru=e=>qt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Fs,fs,ba,ql,Ma,Hl,Kl,li,Xl,Ql,va,Nu=R(()=>{Kt(),Xt(),Cr(),sr(),Fs="[a-zA-Z]|\\.\\.\\.",fs="("+Fs+")+",ba="^"+fs+"$",ql="("+fs+",)*"+fs,Ma="^"+ql+"$",Hl=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Kl=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Ma)))throw new Error("Invalid LHS term");if(r.split(",").forEach((s,i)=>{let a=e[i].dims.slice();if(!s.match(RegExp(ba)))throw new Error("Invalid LHS term");let u=this.processTerm(s,!0,a,i);this.lhs.push(u)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([s,i])=>i.count===1||s==="...").map(([s])=>s).join("");else if(!n.match(RegExp(fs)))throw new Error("Invalid RHS");n.match(RegExp(Fs,"g"))?.forEach(s=>{if(s==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(s);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,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let s=r.length,i=!1,a=[],u=0;if(!e.match(RegExp(ba))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Fs,"g")),c=new Hl(n);return d?.forEach((g,l)=>{if(g==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let y=s-d.length+1;if(y<0)throw new Error("Ellipsis out of bounds");if(a=r.slice(u,u+y),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let v=0;ve+"_max",Xl=(e,t,r,n)=>{let s=e.map(c=>c.length).map((c,g)=>Ze(`input${g}`,t,c)),i=Ie.size(n),a=Vt("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(c=>!r.rhs.symbolToIndices.has(c)),d=c=>{let g=[],l="var prod = 1.0;",y="var sum = 0.0;",v="sum += prod;",S=[],x=[],G=[],q=[],k=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((ee,fe)=>{if(r.rhs.symbolToIndices.has(fe)){let We=r.rhs.symbolToIndices.get(fe)?.[0];We!==void 0&&r.lhs.forEach((Ne,mt)=>{if(ee.inputIndices.includes(mt)){let jt=Ne.symbolToIndices.get(fe);if(jt===void 0)throw new Error("Invalid symbol error");jt.forEach(Lt=>{g.push(`${s[mt].indicesSet(`input${mt}Indices`,Lt,a.indicesGet("outputIndices",We))}`)})}})}else r.lhs.forEach((We,Ne)=>{if(ee.inputIndices.includes(Ne)){let mt=We.symbolToIndices.get(fe);if(mt===void 0)throw new Error("Invalid symbol error");mt.forEach(jt=>{S.push(`${s[Ne].indicesSet(`input${Ne}Indices`,jt,`${fe}`)}`)}),q.push(`prod *= ${s[Ne].getByIndices(`input${Ne}Indices`)};`)}}),x.push(`for(var ${fe}: u32 = 0; ${fe} < uniforms.${li(fe)}; ${fe}++) {`),G.push("}")});let Z=k?[...g,`let sum = ${s.map((ee,fe)=>ee.getByIndices(`input${fe}Indices`)).join(" * ")};`]:[...g,y,...x,...S,l,...q,v,...G];return` ${c.registerUniforms(u.map(ee=>({name:`${li(ee)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,a)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${a.offsetToIndices("global_idx")}; ${s.map((ee,fe)=>`var input${fe}Indices: ${s[fe].type.indices};`).join(` `)} ${Z.join(` `)}; ${a.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=u.filter(l=>r.symbolToInfo.has(l)).map(l=>({type:12,data:r.symbolToInfo.get(l)?.dimValue||0}));c.push({type:12,data:i});let g=e.map((l,y)=>[...Pt(l)]).reduce((l,y)=>l.concat(y),c);return g.push(...Pt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:g}},getShaderSource:d}},Ql=(e,t)=>{let r=new Kl(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((i,a)=>i.dims);e.compute(Xl(s,e.inputs[0].dataType,r,n))},va=e=>{let t=e.equation.replace(/\s+/g,"");return qt({equation:t})}}),Yl,Or,ju,Vu,Uu,Zl=R(()=>{Kt(),Xt(),sr(),Yl=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let s=0;se.length>t.length?Or(e,t):Or(t,e),Vu=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=ju(t,r),s=e[0].dataType,i=s===9?4:1,a=Math.ceil(Ie.size(n)/i),u=c=>{let g=Ze("input",s,t.length,i),l=Vt("output",s,n.length,i),y;if(s===9){let v=(S,x,G="")=>` let outputIndices${x} = ${l.offsetToIndices(`outputOffset + ${x}u`)}; let offset${x} = ${g.broadcastedIndicesToOffset(`outputIndices${x}`,l)}; let index${x} = offset${x} / 4u; let component${x} = offset${x} % 4u; ${S}[${x}] = ${G}(${g.getByOffset(`index${x}`)}[component${x}]); `;y=` let outputOffset = global_idx * ${i}; var data = vec4(0); ${v("data",0,"u32")} ${v("data",1,"u32")} ${v("data",2,"u32")} ${v("data",3,"u32")} ${l.setByOffset("global_idx","data")} }`}else y=` let outputIndices = ${l.offsetToIndices("global_idx")}; let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",l)}; ${l.setByOffset("global_idx",g.getByOffset("inputOffset"))} }`;return` ${c.registerUniform("vec_size","u32").declareVariables(g,l)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${y}`},d=[{type:12,data:a},...Pt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d})}},Uu=e=>{Yl(e.inputs),e.compute(Vu(e.inputs),{inputs:[0]})}}),Jl,eu,Wu=R(()=>{Kt(),Xt(),sr(),Zi(),Jl=e=>{let t=e[0].dataType,r=Ie.size(e[0].dims),n=Ie.size(e[1].dims),s=n%4===0,i=a=>{let u=Ze("x",t,[1],4),d=Ze("bias",t,[1],4),c=Vt("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],l=v=>` let bias${v}_offset: u32 = (global_idx * 4 + ${v}) % uniforms.bias_size; let bias${v} = ${d.getByOffset(`bias${v}_offset / 4`)}[bias${v}_offset % 4];`,y=s?` let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${l(0)}${l(1)}${l(2)}${l(3)} let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(g).declareVariables(u,d,c)} ${Ki(Tr(t))} ${a.mainStart(hn)} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${u.getByOffset("global_idx")}; ${y} let x_in = x + bias; ${c.setByOffset("global_idx",Xi("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/hn/4)}})}},eu=e=>{e.inputs.length<2||Ie.size(e.inputs[1].dims)===0?Qi(e):e.compute(Jl(e.inputs))}}),tu,xa,Ta,ru,Gu=R(()=>{Kt(),Xt(),Cr(),sr(),tu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},xa=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,i=Ie.normalizeAxis(t.axis,s),a=r.slice(0);a.splice(i,1,...n);let u=r[i],d=e[0].dataType===9?4:1,c=Math.ceil(Ie.size(a)/d),g=[{type:12,data:c},{type:6,data:u},{type:12,data:i},...Pt(e[0].dims,e[1].dims,a)],l=y=>{let v=Ze("data",e[0].dataType,e[0].dims.length,d),S=Ze("inputIndices",e[1].dataType,e[1].dims.length),x=Vt("output",e[0].dataType,a.length,d),G=k=>{let Z=n.length,ee=`var indicesIndices${k} = ${S.type.indices}(0);`;for(let fe=0;fe1?`indicesIndices${k}[${fe}]`:`indicesIndices${k}`} = ${a.length>1?`outputIndices${k}[uniforms.axis + ${fe}]`:`outputIndices${k}`};`;ee+=` var idx${k} = ${S.getByIndices(`indicesIndices${k}`)}; if (idx${k} < 0) { idx${k} = idx${k} + uniforms.axisDimLimit; } var dataIndices${k} : ${v.type.indices}; `;for(let fe=0,We=0;fe1?`dataIndices${k}[${fe}]`:`dataIndices${k}`} = u32(idx${k});`,We+=Z):(ee+=`${s>1?`dataIndices${k}[${fe}]`:`dataIndices${k}`} = ${a.length>1?`outputIndices${k}[${We}]`:`outputIndices${k}`};`,We++);return ee},q;if(e[0].dataType===9){let k=(Z,ee,fe="")=>` let outputIndices${ee} = ${x.offsetToIndices(`outputOffset + ${ee}u`)}; ${G(ee)}; let offset${ee} = ${v.indicesToOffset(`dataIndices${ee}`)}; let index${ee} = offset${ee} / 4u; let component${ee} = offset${ee} % 4u; ${Z}[${ee}] = ${fe}(${v.getByOffset(`index${ee}`)}[component${ee}]); `;q=` let outputOffset = global_idx * ${d}; var value = vec4(0); ${k("value",0,"u32")} ${k("value",1,"u32")} ${k("value",2,"u32")} ${k("value",3,"u32")} ${x.setByOffset("global_idx","value")} `}else q=` let outputIndices = ${x.offsetToIndices("global_idx")}; ${G("")}; let value = ${v.getByIndices("dataIndices")}; ${x.setByOffset("global_idx","value")}; `;return` ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(v,S,x)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${q} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:l}},Ta=e=>qt({axis:e.axis}),ru=(e,t)=>{let r=e.inputs;tu(r),e.compute(xa(e.inputs,t))}}),Sa,qu,Hu,nu,Ku=R(()=>{Kt(),Xt(),Cr(),sr(),Sa=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Ie.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,s=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==s.dims.length||!s.dims.map((u,d)=>d===r?Math.ceil(u/n)===i.dims[d]:u===i.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==i.dims.length||!a.dims.map((u,d)=>u===i.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},qu=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,i=Ie.normalizeAxis(t.gatherAxis,s),a=Ie.normalizeAxis(t.quantizeAxis,s),u=r.slice(0);u.splice(i,1,...n);let d=Ie.size(u),c=e[2].dataType,g=e[0].dataType===22,l=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...Pt(...e.map((v,S)=>v.dims),u)],y=v=>{let S=Ze("data",e[0].dataType,e[0].dims.length),x=Ze("inputIndices",e[1].dataType,e[1].dims.length),G=Ze("scales",e[2].dataType,e[2].dims.length),q=e.length>3?Ze("zeroPoint",e[3].dataType,e[3].dims.length):void 0,k=Vt("output",c,u.length),Z=[S,x,G];q&&Z.push(q);let ee=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${v.registerUniforms(ee).declareVariables(...Z,k)} ${v.mainStart()} let output_indices = ${k.offsetToIndices("global_idx")}; var indices_indices = ${x.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${k.indicesGet("output_indices","uniforms.gather_axis + i")}; ${x.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${k.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${S.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${k.indicesGet("output_indices","i")}; ${S.indicesSet("data_indices","i","index")}; } var index_from_indices = ${x.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[i]}; } ${S.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { let index = ${k.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${S.indicesSet("data_indices","i","index")}; } let data_offset = ${S.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${S.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${g?"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 = ${G.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${G.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${G.getByIndices("scale_indices")}; ${q?` let zero_point_indices = scale_indices; let zero_point_offset = ${q.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${q.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${Tr(c)}(quantized_data - zero_point) * scale; ${k.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((v,S)=>S!==1).map(v=>v.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(v,S)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:l}),getShaderSource:y}},Hu=(e,t)=>{let r=e.inputs;Sa(r,t),e.compute(qu(e.inputs,t))},nu=e=>qt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),su,iu,au,ou,Xu=R(()=>{Kt(),Xt(),Cr(),sr(),su=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.`)},iu=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,i=e[1].dims,a=e[1].dataType,u=Ie.normalizeAxis(t.axis,s),d=r[u],c=i.slice(0),g=Ie.size(c),l=Ze("input",n,s),y=Ze("indicesInput",a,i.length),v=Vt("output",n,c.length),S=[{type:12,data:g},{type:6,data:d},{type:12,data:u}];return S.push(...Pt(r,i,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:S}),getShaderSource:x=>` ${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(l,y,v)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${v.offsetToIndices("global_idx")}; var idx = ${y.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${l.type.indices}(outputIndices); ${l.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${l.getByIndices("inputIndices")}; ${v.setByOffset("global_idx","value")}; }`}},au=e=>qt({axis:e.axis}),ou=(e,t)=>{let r=e.inputs;su(r),e.compute(iu(e.inputs,t))}}),lu,uu,du,cu,Qu=R(()=>{Kt(),Xt(),sr(),lu=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")},uu=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,i,a]=xr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[s,i];if(!u)throw new Error("Can't use gemm on the given tensors");let d=Ie.size(u),c=[{type:12,data:d},{type:12,data:s},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],g=["type","type"];e.length===3&&(c.push(...Pt(e[2].dims)),g.push("rank")),c.push(...Pt(u));let l=y=>{let v="";t.transA&&t.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=t.alpha===1?"":"value *= uniforms.alpha;",x=Ze("a",e[0].dataType,e[0].dims),G=Ze("b",e[1].dataType,e[1].dims),q=x.type.value,k=null,Z=[x,G];e.length===3&&(k=Ze("c",e[2].dataType,e[2].dims.length),Z.push(k));let ee=Vt("output",e[0].dataType,u.length);Z.push(ee);let fe=[{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` ${y.registerUniforms(fe).declareVariables(...Z)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${q}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${v} } ${S} ${k!=null?`let cOffset = ${k.broadcastedIndicesToOffset("vec2(m, n)",ee)}; value += ${q}(uniforms.beta) * ${k.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:l}},du=e=>{let t=e.transA,r=e.transB,n=e.alpha,s=e.beta;return{transA:t,transB:r,alpha:n,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},cu=(e,t)=>{lu(e.inputs),e.compute(uu(e.inputs,t))}}),ln,pu,hu,$a,Yu,ui,Zu,Ju=R(()=>{Kt(),Xt(),Cr(),z(),Qs(),sr(),ps(),ln=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,pu=(e,t)=>{let r=e[0],n=ln(e,1),s=ln(e,2),i=ln(e,3),a=ln(e,4),u=ln(e,5),d=ln(e,6),c=ln(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let g=r.dims[0],l=r.dims[1],y=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],v=l,S=0,x=0,G=Math.floor(y/t.numHeads);if(d&&c&&Ie.size(d.dims)&&Ie.size(c.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==g||d.dims[1]!==t.numHeads||d.dims[3]!==G)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==g||c.dims[1]!==t.numHeads||c.dims[3]!==G)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');S=d.dims[2],x=d.dims[2]}else if(d&&Ie.size(d.dims)||c&&Ie.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let q;if(n&&Ie.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');q=2,v=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==G)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');q=5,v=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==G)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');q=0,v=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');q=3}if(i&&Ie.size(i.dims)>0){if(i.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 k=S+v,Z=0;if(a&&Ie.size(a.dims)>0){Z=8;let Ne=a.dims;throw Ne.length===1?Ne[0]===g?Z=1:Ne[0]===3*g+2&&(Z=3):Ne.length===2&&Ne[0]===g&&Ne[1]===k&&(Z=5),Z===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let ee=!1,fe=y;if(s&&Ie.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(v!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');fe=s.dims[2]}else{if(v!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');fe=s.dims[1]*s.dims[3],ee=!0}}let We=!1;if(a&&Ie.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Ie.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==g||u.dims[1]!==t.numHeads||u.dims[2]!==l||u.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:l,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:k,maxSequenceLength:x,inputHiddenSize:0,hiddenSize:y,vHiddenSize:fe,headSize:G,vHeadSize:Math.floor(fe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:Z,scale:t.scale,broadcastResPosBias:We,passPastInKv:ee,qkvFormat:q}},hu=e=>qt({...e}),$a=qt({perm:[0,2,1,3]}),Yu=(e,t,r,n,s,i,a)=>{let u=[n,s,i],d=Ie.size(u),c=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],g=l=>{let y=Vt("qkv_with_bias",t.dataType,u),v=Ze("qkv",t.dataType,u),S=Ze("bias",r.dataType,u),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${l.registerUniforms(x).declareVariables(v,S,y)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:g},{inputs:[t,r],outputs:[-1]})[0]},ui=(e,t,r,n,s,i,a,u)=>{let d=i;if(a&&Ie.size(a.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Yu(e,i,a,t,n,r*s,u),d=d.reshape([t,n,r,s]),e.compute(kn(d,$a.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,s])),e.compute(kn(d,$a.perm),{inputs:[d],outputs:[-1]})[0]},Zu=(e,t)=>{let r=pu(e.inputs,t),n=e.inputs[0],s=ln(e.inputs,1),i=ln(e.inputs,2),a=ln(e.inputs,3),u=ln(e.inputs,4),d=ln(e.inputs,5),c=ln(e.inputs,6),g=ln(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(s?.dims.length===5)throw new Error("Packed KV is not implemented");let l=s&&i&&s.dims.length===4&&i.dims.length===4,y=ui(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(l)return hs(e,y,s,i,u,void 0,c,g,d,r,t);if(!s||!i)throw new Error("key and value must be provided");let v=ui(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,a,r.hiddenSize),S=ui(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);hs(e,y,v,S,u,void 0,c,g,d,r,t)}}),fu,ed,td,mu,rd,nd=R(()=>{Kt(),Xt(),sr(),fu=e=>Array.from(e.getBigInt64Array(),Number),ed=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(fu(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")},td=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??fu(e[1]),s=td(r,n),i=Ie.size(s),a=e[0].dataType,u=Ze("input",a,r.length),d=Vt("output",a,s.length),c=g=>` const inputShape = ${u.indices(...r)}; ${g.registerUniform("output_size","u32").declareVariables(u,d)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${d.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; for (var i = 0; i < ${r.length}; i++) { let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; ${u.indicesSet("input_indices","i","input_dim_value")} } ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...Pt(e[0].dims,s)]}),getShaderSource:c}},rd=e=>{ed(e.inputs),e.compute(mu(e.inputs),{inputs:[0]})}}),sd,_u,id,ad,gu,od,qd=R(()=>{Kt(),Xt(),Cr(),Qs(),sr(),Ju(),nd(),ps(),sd=(e,t)=>{let r=e[0],n=e[1],s=e[2],i=e[3],a=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],c=r.dims[1],g=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],l=c,y=0,v=0,S=Math.floor(g/t.numHeads),x=i&&i.dims.length!==0,G=a&&a.dims.length!==0,q=!0;if(x&&G){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');y=i.dims[1],v=i.dims[1]}else if(x||G)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let k;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');k=2,l=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==S)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');k=5,l=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==S)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');k=0,l=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');k=3}let Z=0,ee=!1,fe=g;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(l!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');fe=s.dims[2]}else{if(l!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');fe=s.dims[1]*s.dims[3],ee=!0}}let We=y+l;return{batchSize:d,sequenceLength:c,pastSequenceLength:y,kvSequenceLength:l,totalSequenceLength:We,maxSequenceLength:v,inputHiddenSize:0,hiddenSize:g,vHiddenSize:fe,headSize:S,vHeadSize:Math.floor(fe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:Z,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ee,qkvFormat:k,isPastkvBSNH:q}},_u=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],i=4,a=Ie.size(s)/i,u=n.totalSequenceLength,d=Vt("present_kv",r,s.length,i),c=Ze("new_kv",e.dataType,e.dims.length,i),g=t?Ze("past_kv",t.dataType,t.dims.length,i):void 0,l=Math.ceil(n.headSize/i),y={x:u,y:e.dims[0],z:1},v=t?["rank","rank"]:["rank"],S=[{type:12,data:a},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],x=[c];g?(S.push(...Pt(e.dims),...Pt(t.dims),...Pt(s)),x.push(g)):S.push(...Pt(e.dims),...Pt(s));let G=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],q=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; var past_head_stride = uniforms.past_seqlen * H; if (is_bsnh) { past_head_stride = H; } let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; present_kv[out_offset] = past_kv[in_offset];`,k=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; let new_row_stride = num_heads * H; let new_head_stride = H; let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; present_kv[out_offset] = new_kv[in_offset];`,Z=t?`if (s < past_seqlen) { ${q} } else if (s < past_seqlen + uniforms.new_seqlen) { ${k} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${k} }`,ee=fe=>` ${fe.registerUniforms(G).declareVariables(...x,d)} ${fe.mainStart([l,n.kvNumHeads,1])} ${fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${d.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${n.kvNumHeads}u; let H = ${l}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${n.isPastkvBSNH}; if (is_bsnh) { row_stride = num_heads * H; } var present_head_stride = present_seqlen * H; if (is_bsnh) { present_head_stride = H; } let past_seqlen = uniforms.past_seqlen; let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; ${Z} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${l}${!!t}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:y,programUniforms:S}),getShaderSource:ee}},id=e=>qt({...e}),ad=qt({perm:[0,2,1,3]}),gu=(e,t,r,n,s)=>{let i=t,a=n.kvNumHeads,u=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(i=t.reshape([n.batchSize,n.kvSequenceLength,a,n.headSize])),r?i=e.compute(_u(i,r,i.dataType,n),{inputs:[i,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:i=e.compute(_u(i,void 0,i.dataType,n),{inputs:[i],outputs:[n.isPastkvBSNH?s:-1]})[0],u!==1&&(i=e.compute(mu([i],[1,1,1,u]),{inputs:[i],outputs:[-1]})[0],i=i.reshape([n.batchSize,n.totalSequenceLength,a*u,n.headSize])),e.compute(kn(i,ad.perm),{inputs:[i],outputs:[-1]})[0]},od=(e,t)=>{let r=sd(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let n=ui(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,i=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,a=gu(e,e.inputs[1],s,r,1),u=gu(e,e.inputs[2],i,r,2);hs(e,n,a,u,void 0,void 0,void 0,void 0,void 0,r,t)}}),ld,ud,dd,cd,Hd=R(()=>{Kt(),Xt(),sr(),ld=(e,t)=>{let r=e[0].dims,n=r,s=2,i=Ie.sizeToDimension(r,s),a=Ie.sizeFromDimension(r,s),u=Sr(a),d=a/u,c=[r[0],r[1],d],g=["rank","type","type"],l=[{type:12,data:a},{type:12,data:d}];l.push(...Pt(c,c));let y=v=>{let S=Ze("x",e[0].dataType,c.length,u),x=Ze("scale",e[1].dataType,e[1].dims),G=Ze("bias",e[2].dataType,e[2].dims),q=Vt("output",e[0].dataType,c.length,u),k=[S,x,G,q],Z=S.type.value,ee=u===1?"f32":`vec${u}`,fe=64,We=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${ee}, ${fe}>; const workgroupSize = ${fe}u; ${v.registerUniforms(We).declareVariables(...k)} ${v.mainStart(fe)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${ee}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${ee}(${S.get("batch","channel","h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${fn("workgroupShared[0]",u)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${ee}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${ee}(${S.get("batch","channel","h")}) - ${ee}(meanShared); initial = initial + deviation * deviation; } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the sum of square of deviation of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { squaredNormShared = ${fn("workgroupShared[0]",u)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); let channelScale = invStdDev * f32(${x.getByOffset("channel")}); let channelShift = f32(${G.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${S.get("batch","channel","h")} * ${Z}(${ee}(channelScale)) + ${Z}(${ee}(channelShift)); ${q.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${u}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:i},programUniforms:l}),getShaderSource:y}},ud=(e,t,r,n,s,i,a,u)=>{let d=Sr(a),c=64,g=d===1?"vec2f":`mat2x${d}f`,l=d===1?"f32":`vec${d}f`,y=(We,Ne)=>`${g}(${We}, ${Ne})`,v=s*a/d,S=Math.ceil(i/c),x=["type"],G=[{type:12,data:S},{type:12,data:i},{type:12,data:Math.floor(a/d)},{type:12,data:Math.floor(i*a/d)}],q=We=>{let Ne=Ze("input",t.dataType,t.dims,d);return` ${We.declareVariables(Ne)} @group(0) @binding(1) var output : array<${g}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${We.mainStart(c)} let currentImageNumber = global_idx / ${c} / uniforms.C; let currentChannelNumber = (global_idx / ${c}) % uniforms.C; let wgOffset = local_id.x * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${Fr("f32",d)}; var squaredSum = ${Fr("f32",d)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${l}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${y("sum","squaredSum")}; }`},k=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${d}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:[s,a,c,2],dataType:1}],dispatchGroup:{x:s*a/d},programUniforms:G}),getShaderSource:q},{inputs:[t],outputs:[-1]})[0],Z=[{type:12,data:v},{type:12,data:i},{type:12,data:Math.floor(a/d)},{type:12,data:Math.floor(c*a/d)}],ee=["type","type","type"],fe=We=>{let Ne=Ze("scale",r.dataType,r.dims,d),mt=Ze("bias",n.dataType,n.dims,d);return` @group(0) @binding(0) var input : array<${g}>; @group(0) @binding(1) var scale : array<${Ne.type.storage}>; @group(0) @binding(2) var bias : array<${mt.type.storage}>; @group(0) @binding(3) var output : array<${g}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${We.mainStart()} ${We.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} let currentImageNumber = global_idx / uniforms.C; let currentChannelNumber = global_idx % uniforms.C; let offset = currentImageNumber * uniforms.image_size; var sum = ${Fr("f32",d)}; var squaredSum = ${Fr("f32",d)}; for (var i: u32 = 0; i < min(${c}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${c}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${u})); let channelScale = invStdDev * ${l}(scale[currentChannelNumber]); let channelShift = ${l}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${y("channelScale","channelShift")}; }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:[s,a,2],dataType:1}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:Z}),getShaderSource:fe},{inputs:[k,r,n],outputs:[-1]})[0]},dd=(e,t,r)=>{let n=t[0].dims,s=n,i=n[0],a=n[n.length-1],u=Ie.sizeFromDimension(n,1)/a,d=Sr(a),c=Ie.size(s)/d,g=[{type:12,data:u},{type:12,data:Math.floor(a/d)}],l=["type","type"],y=ud(e,t[0],t[1],t[2],i,u,a,r.epsilon),v=S=>{let x=Er(t[0].dataType),G=d===1?"vec2f":`mat2x${d}f`,q=d===1?x:`vec${d}<${x}>`,k=Ze("input",t[0].dataType,t[0].dims,d),Z=Vt("output",t[0].dataType,s,d);return` @group(0) @binding(0) var input : array<${k.type.storage}>; @group(0) @binding(1) var scaleInput : array<${G}>; @group(0) @binding(2) var output : array<${Z.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${S.mainStart()} let currentImageNumber = global_idx / (uniforms.C * uniforms.H); let currentChannelNumber = global_idx % uniforms.C; let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; let scale = scaleInput[scaleOffset]; output[global_idx] = fma(input[global_idx], ${q}(scale[0]), ${q}(scale[1])); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:v},{inputs:[t[0],y]})},cd=(e,t)=>{t.format==="NHWC"?dd(e,e.inputs,t):e.compute(ld(e.inputs,t))}}),pd,hd,fd,Kd=R(()=>{Kt(),Xt(),sr(),pd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},hd=(e,t,r)=>{let n=t.simplified,s=e[0].dims,i=e[1],a=!n&&e[2],u=s,d=Ie.normalizeAxis(t.axis,s.length),c=Ie.sizeToDimension(s,d),g=Ie.sizeFromDimension(s,d),l=Ie.size(i.dims),y=a?Ie.size(a.dims):0;if(l!==g||a&&y!==g)throw new Error(`Size of X.shape()[axis:] == ${g}. Size of scale and bias (if provided) must match this. Got scale size of ${l} and bias size of ${y}`);let v=[];for(let fe=0;fe1,k=r>2,Z=fe=>{let We=Er(e[0].dataType),Ne=[Ze("x",e[0].dataType,e[0].dims,S),Ze("scale",i.dataType,i.dims,S)];a&&Ne.push(Ze("bias",a.dataType,a.dims,S)),Ne.push(Vt("output",e[0].dataType,u,S)),q&&Ne.push(Vt("mean_data_output",1,v)),k&&Ne.push(Vt("inv_std_output",1,v));let mt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${fe.registerUniforms(mt).declareVariables(...Ne)} ${fe.mainStart()} ${fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Fr("f32",S)}; var mean_square_vector = ${Fr("f32",S)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${jr(We,S,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${fn("mean_vector",S)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${fn("mean_square_vector",S)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${jr(We,S,"x[j + offset]")}; let f32scale = ${jr(We,S,"scale[j]")}; output[j + offset] = ${Ne[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${a?`+ ${jr(We,S,"bias[j]")}`:""} ); } ${q?"mean_data_output[global_idx] = mean":""}; ${k?"inv_std_output[global_idx] = inv_std_dev":""}; }`},ee=[{dims:u,dataType:e[0].dataType}];return q&&ee.push({dims:v,dataType:1}),k&&ee.push({dims:v,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${S};${r};${n}`,inputDependencies:x},getRunData:()=>({outputs:ee,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:G}),getShaderSource:Z}},fd=(e,t)=>{pd(e.inputs),e.compute(hd(e.inputs,t,e.outputCount))}}),md,_d,gd,lr,wd=R(()=>{Kt(),Xt(),Cr(),sr(),md=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!Ie.areEqual(a.dims,[t.n,s,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Ie.size(u)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,c=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(Ie.size(d)!==c)throw new Error("zeroPoints input size error.")}},_d=(e,t)=>{let r=e[0].dims,n=r.length,s=r[n-2],i=t.k,a=t.n,u=r.slice(0,n-2),d=Ie.size(u),c=e[1].dims[2]/4,g=e[0].dataType,l=Sr(t.k),y=Sr(c),v=Sr(a),S=u.concat([s,a]),x=s>1&&a/v%2===0?2:1,G=Ie.size(S)/v/x,q=64,k=[],Z=[d,s,i/l],ee=Ie.convertShape(e[1].dims).slice();ee.splice(-1,1,c/y),k.push(...Pt(Z)),k.push(...Pt(ee)),k.push(...Pt(e[2].dims)),e.length===4&&k.push(...Pt(Ie.convertShape(e[3].dims)));let fe=[d,s,a/v];k.push(...Pt(fe));let We=Ne=>{let mt=Z.length,jt=Ze("a",e[0].dataType,mt,l),Lt=Ze("b",12,ee.length,y),dr=Ze("scales",e[2].dataType,e[2].dims.length),ar=[jt,Lt,dr],_r=e.length===4?Ze("zero_points",12,e[3].dims.length):void 0;_r&&ar.push(_r);let Pr=fe.length,hr=Vt("output",e[0].dataType,Pr,v),Yt=Er(e[0].dataType),Ar=(()=>{switch(l){case 1:return`array<${Yt}, 8>`;case 2:return`mat4x2<${Yt}>`;case 4:return`mat2x4<${Yt}>`;default:throw new Error(`${l}-component is not supported.`)}})(),Br=()=>{let Ke=` // reuse a data var input_offset = ${jt.indicesToOffset(`${jt.type.indices}(batch, row, word_offset)`)}; var a_data: ${Ar}; for (var j: u32 = 0; j < ${8/l}; j++) { a_data[j] = ${jt.getByOffset("input_offset")}; input_offset++; } `;for(let $t=0;$t> 4) & b_mask); b_quantized_values = ${Ar}(${Array.from({length:4},(cr,Vr)=>`${Yt}(b_value_lower[${Vr}]), ${Yt}(b_value_upper[${Vr}])`).join(", ")}); b_dequantized_values = ${l===1?`${Ar}(${Array.from({length:8},(cr,Vr)=>`(b_quantized_values[${Vr}] - ${_r?`zero_point${$t}`:"zero_point"}) * scale${$t}`).join(", ")});`:`(b_quantized_values - ${Ar}(${Array(8).fill(`${_r?`zero_point${$t}`:"zero_point"}`).join(",")})) * scale${$t};`}; workgroup_shared[local_id.x * ${x} + ${Math.floor($t/v)}]${v>1?`[${$t%v}]`:""} += ${Array.from({length:8/l},(cr,Vr)=>`${l===1?`a_data[${Vr}] * b_dequantized_values[${Vr}]`:`dot(a_data[${Vr}], b_dequantized_values[${Vr}])`}`).join(" + ")}; `;return Ke},tr=()=>{let Ke=` var col_index = col * ${v}; ${_r?` 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 = ${Yt}(8);`} `;for(let $t=0;$t> 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 = ${_r.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${$t} = ${Yt}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return Ke},gr=()=>{let Ke=`col_index = col * ${v};`;for(let $t=0;$t; var b_value_upper: vec4; var b_quantized_values: ${Ar}; var b_dequantized_values: ${Ar};`,Ke};return` var workgroup_shared: array<${hr.type.value}, ${x*q}>; ${Ne.declareVariables(...ar,hr)} ${Ne.mainStart([q,1,1])} let output_indices = ${hr.offsetToIndices(`(global_idx / ${q}) * ${x}`)}; 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 += ${q}) { //process one block var word_offset: u32 = block * ${t.blockSize/l}; ${tr()} for (var word: u32 = 0; word < ${c}; word += ${y}) { ${gr()} for (var i: u32 = 0; i < ${y}; i++) { ${Br()} word_offset += ${8/l}; } } } workgroupBarrier(); if (local_id.x < ${x}) { var output_value: ${hr.type.value} = ${hr.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${q}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${x}; } ${hr.setByIndices(`${hr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${l};${y};${v};${x};${q}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:S,dataType:g}],dispatchGroup:{x:G},programUniforms:k}),getShaderSource:We}},gd=(e,t)=>{md(e.inputs,t),e.compute(_d(e.inputs,t))},lr=e=>qt(e)}),en,rn,on,es,yd,wu,yu,_,h,D=R(()=>{Kt(),Xt(),sr(),en=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].")}},rn=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Nt("uniforms.pads",s,r)}; if (k < 0) { break; } if (k >= i32(${Nt("uniforms.x_shape",s,t)})) { break; } offset += k * i32(${Nt("uniforms.x_strides",s,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]; } `},on=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Nt("uniforms.pads",s,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Nt("uniforms.x_shape",s,t)}) - 1); k = k % _2n_1; if(k >= i32(${Nt("uniforms.x_shape",s,t)})) { k = _2n_1 - k; } } offset += k * i32(${Nt("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},es=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Nt("uniforms.pads",s,r)}; if (k < 0) { k = 0; } if (k >= i32(${Nt("uniforms.x_shape",s,t)})) { k = i32(${Nt("uniforms.x_shape",s,t)}) - 1; } offset += k * i32(${Nt("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},yd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` k = i32(${e.indicesGet("indices",s)}) - ${Nt("uniforms.pads",s,r)}; if (k < 0) { k += i32(${Nt("uniforms.x_shape",s,t)}]); } if (k >= i32(${Nt("uniforms.x_shape",s,t)})) { k -= i32(${Nt("uniforms.x_shape",s,t)}); } offset += k * i32(${Nt("uniforms.x_strides",s,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},wu=(e,t,r)=>{switch(r.mode){case 0:return rn(e,t,r.pads.length);case 1:return on(e,t,r.pads.length);case 2:return es(e,t,r.pads.length);case 3:return yd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},yu=(e,t)=>{let r=Ie.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=Ie.size(r),i=[{type:12,data:s},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...Pt(e[0].dims,r));let u=["rank"],d=c=>{let g=Vt("output",e[0].dataType,r.length),l=Ze("x",e[0].dataType,n.length),y=l.type.value,v=wu(g,n.length,t),S=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&S.push({name:"constant_value",type:a?y:"f32"}),` ${c.registerUniforms(S).declareVariables(l,g)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${g.offsetToIndices("global_idx")}; var value = ${y}(0); ${v} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Ie.size(r)/64)},programUniforms:i}),getShaderSource:d}},_=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,s=e[0].dims.length,i=new Int32Array(2*s).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(u));let a=[];return i.forEach(u=>a.push(u)),{mode:t.mode,value:n,pads:a}}else return t},h=(e,t)=>{en(e.inputs);let r=_(e.inputs,t);e.compute(yu(e.inputs,r),{inputs:[0]})}}),re,Oe,Ye,wt,At,Zt,mr,kr,Ir,pr,er,Dr,ir,Mr,qr,tn,Hn,Sn,mn,Qr=R(()=>{Bt(),Kt(),Xt(),sr(),re=e=>{if(C.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Oe=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let i=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),u=t.strides.slice(),d=i?t.dilations.slice():[],c=t.pads.slice();On.adjustPoolAttributes(r,s,a,u,d,c);let g=On.computePoolOutputShape(r,s,u,d,a,c,t.autoPad),l=Object.assign({},t);i?Object.assign(l,{kernelShape:a,strides:u,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(l,{kernelShape:a,strides:u,pads:c,cacheKey:t.cacheKey});let y=g.slice();return y.push(y.splice(1,1)[0]),[l,n?y:g]},Ye=(e,t)=>{let r=t.format==="NHWC",n=Ie.size(e),s=Ie.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:s}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],g=t.pads[t.pads.length-1],l=!!(c+g);i.push({type:12,data:u},{type:12,data:d},{type:12,data:c},{type:12,data:g}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let y=!1;if(t.kernelShape.length===2){let v=t.kernelShape[t.kernelShape.length-2],S=t.strides[t.strides.length-2],x=t.pads[t.pads.length/2-2],G=t.pads[t.pads.length-2];y=!!(x+G),i.push({type:12,data:v},{type:12,data:S},{type:12,data:x},{type:12,data:G}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,l,y]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Ie.computeStrides(t.kernelShape);i.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((c,g)=>c+g);return[i,a,!!d,!1,!1]}},wt=(e,t,r,n,s,i,a,u,d,c,g,l)=>{let y=s.format==="NHWC",v=t.type.value,S=Vt("output",t.type.tensor,n);if(s.kernelShape.length<=2){let x="",G="",q="",k=r-(y?2:1);if(g?x=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${k}] = indices[${k}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${k}] < 0 || xIndices[${k}] >= uniforms.x_shape[${k}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:x=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${k}] = indices[${k}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`,s.kernelShape.length===2){let Z=r-(y?3:2);l?G=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${Z}] = indices[${Z}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${Z}] < 0 || xIndices[${Z}] >= uniforms.x_shape[${Z}]) { pad += i32(uniforms.kw); continue; } `:G=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${Z}] = indices[${Z}] * uniforms.sh - uniforms.phStart + j; `,q=` } `}return` ${e.registerUniforms(d).declareVariables(t,S)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${S.offsetToIndices("global_idx")}; var xIndices = ${S.offsetToIndices("global_idx")}; var value = ${v}(${u}); var pad = 0; ${G} ${x} ${q} ${a} output[global_idx] = value; }`}else{if(y)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=s.kernelShape.length,G=s.pads.length,q="";return c?q=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:q=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} `,` ${e.registerUniforms(d).declareVariables(t,S)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${S.offsetToIndices("global_idx")}; var xIndices = ${S.offsetToIndices("global_idx")}; var offsets: array; var value = ${v}(${u}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${x-1}u; j++) { offsets[j] = offset / ${Nt("uniforms.kernelStrides","j",x)}; offset -= offsets[j] * ${Nt("uniforms.kernelStrides","j",x)}; } offsets[${x-1}] = offset; isPad = false; for (var j = ${r-x}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${Nt("uniforms.strides",`j - ${r-x}u`,x)} + offsets[j - ${r-x}u] - ${Nt("uniforms.pads","j - 2u",G)}; ${q} } ${a} output[global_idx] = value; }`}},At=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Zt=e=>`${At(e)};${e.countIncludePad}`,mr=e=>`${At(e)};${e.storageOrder};${e.dilations}`,kr=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}),Ir=(e,t,r,n)=>{let[s,i]=Oe(t,n,r),a=Ze("x",t.dataType,t.dims.length),u=a.type.value,d="value += x_val;",c="";s.countIncludePad?c+=`value /= ${u}(uniforms.kernelSize);`:c+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[g,l,y,v,S]=Ye(i,s);g.push(...Pt(t.dims,i));let x=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${y};${v};${S}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Ie.size(i)/64)},programUniforms:g}),getShaderSource:G=>wt(G,a,t.dims.length,i.length,s,d,c,0,l,y,v,S)}},pr=e=>{let t=e.count_include_pad!==0,r=kr(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:Zt(n)}},er=(e,t)=>{re(e.inputs),e.compute(Ir("AveragePool",e.inputs[0],!1,t))},Dr={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ir=e=>{let t=e.format;return{format:t,...Dr,cacheKey:t}},Mr=(e,t)=>{re(e.inputs),e.compute(Ir("GlobalAveragePool",e.inputs[0],!0,t))},qr=(e,t,r,n)=>{let[s,i]=Oe(t,n,r),a=` value = max(x_val, value); `,u="",d=Ze("x",t.dataType,t.dims.length),c=["rank"],[g,l,y,v,S]=Ye(i,s);return g.push(...Pt(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${y};${v};${S}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Ie.size(i)/64)},programUniforms:g}),getShaderSource:x=>wt(x,d,t.dims.length,i.length,s,a,u,t.dataType===10?-65504:-1e5,l,y,v,S)}},tn=(e,t)=>{re(e.inputs),e.compute(qr("MaxPool",e.inputs[0],!1,t))},Hn=e=>{let t=e.storage_order,r=e.dilations,n=kr(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 s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:mr(s)}},Sn=e=>{let t=e.format;return{format:t,...Dr,cacheKey:t}},mn=(e,t)=>{re(e.inputs),e.compute(qr("GlobalMaxPool",e.inputs[0],!0,t))}}),_n,di,Os,Xd,Bn=R(()=>{Kt(),Xt(),Cr(),sr(),_n=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((s,i)=>i===t.axis||s===e[0].dims[i]).reduce((s,i)=>s&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},di=(e,t)=>{let r=Ie.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,s=n===3,i=e[0].dims,a=e[1].dataType,u=Ie.size(i),d=n===3||n===2,c=d?[Math.ceil(Ie.size(e[0].dims)/4)]:e[0].dims,g=e[1].dims,l=e.length>2?e[2]:void 0,y=l?d?[Math.ceil(Ie.size(l.dims)/4)]:l.dims:void 0,v=g.length===0||g.length===1&&g[0]===1,S=v===!1&&g.length===1,x=Sr(u),G=v&&(!d||x===4),q=G?x:1,k=G&&!d?x:1,Z=Ze("input",d?12:n,c.length,k),ee=Ze("scale",a,g.length),fe=l?Ze("zero_point",d?12:n,y.length):void 0,We=Vt("output",a,i.length,q),Ne=[Z,ee];fe&&Ne.push(fe);let mt=[c,g];l&&mt.push(y);let jt=[{type:12,data:u/q},{type:12,data:r},{type:12,data:t.blockSize},...Pt(...mt,i)],Lt=dr=>{let ar=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${dr.registerUniforms(ar).declareVariables(...Ne,We)} ${dr.mainStart()} ${dr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${We.offsetToIndices("global_idx")}; // Set input x ${d?` let input = ${Z.getByOffset("global_idx / 4")}; let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${q===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${Z.getByOffset("global_idx")};`}; // Set scale input ${v?`let scale_value= ${ee.getByOffset("0")}`:S?` let scale_index = ${We.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${ee.getByOffset("scale_index")};`:` var scale_indices: ${ee.type.indices} = output_indices; let index = ${ee.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${ee.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${ee.getByIndices("scale_indices")};`}; // Set zero-point input ${fe?v?d?` let zero_point_input = ${fe.getByOffset("0")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${fe.getByOffset("0")}`:S?d?` let zero_point_index = ${We.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${fe.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${We.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${fe.getByOffset("zero_point_index")};`:d?` let zero_point_offset = ${ee.indicesToOffset("scale_indices")}; let zero_point_input = ${fe.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${fe.getByIndices("scale_indices")};`:`let zero_point_value = ${d?s?"i32":"u32":Z.type.value}(0);`}; // Compute and write output ${We.setByOffset("global_idx",`${We.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:fe?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Lt,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(u/q/64),y:1,z:1},programUniforms:jt})}},Os=(e,t)=>{_n(e.inputs,t),e.compute(di(e.inputs,t))},Xd=e=>qt({axis:e.axis,blockSize:e.blockSize})}),ms,bd,Md,Qd=R(()=>{Bt(),Kt(),sr(),ms=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||i)throw new Error("Range these inputs' contents are invalid.")},bd=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),i=[s],a=s,u=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...Pt(i)],d=c=>{let g=Vt("output",n,i.length),l=g.type.value,y=[{name:"outputSize",type:"u32"},{name:"start",type:l},{name:"delta",type:l}];return` ${c.registerUniforms(y).declareVariables(g)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${l}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u})}},Md=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),C.webgpu.validateInputContent&&ms(t,r,n),e.compute(bd(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),bu,jc,Vc,Uc,Wc,Gc,qc,Hc,Kc,Xc,Qc,Yd,Yc,Zc,Jc,ep,tp,rp,np,zf=R(()=>{Kt(),Xt(),Cr(),sr(),bu=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},jc=(e,t,r)=>{t.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((s,i)=>n[s]=e[i]),n},Vc=(e,t,r,n,s,i)=>{let[a,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(g=>i.push(g));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length>0){if(e[u].getFloat32Array().forEach(g=>n.push(g)),n.length!==0&&n.length!==c&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");bu(n,t),t.axes.length>0&&jc(n,t.axes,c).forEach((g,l)=>n[l]=g)}if(d>0&&e.length>d&&(e[d].getBigInt64Array().forEach(g=>s.push(Number(g))),s.length!==c||r>=18&&s.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!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.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 s<"u"&&n.length>0&&s.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Uc=(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`)}})()+"}",Wc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Gc=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),s=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=s[a],n[a+r]=s[t.length+a]}),n):s},qc=(e,t,r,n)=>{let s=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>s.push(i)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((i,a)=>s[i]=r[a])}else r.forEach(i=>s.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((i,a)=>Math.round(i*t[a]))}return s},Hc=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let s=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>s[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),s.forEach((i,a)=>s[a]=Math.round(i*t[a]))),s},Kc=(e,t,r,n,s)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Nt("uniforms.scales","i",n)}; var roi_low = ${Nt("uniforms.roi","i",s)}; var roi_hi = ${Nt("uniforms.roi",`i + ${t.length}`,s)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Nt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Nt("uniforms.output_shape","i",r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,Xc=(e,t,r,n,s,i,a)=>` 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 = ${Nt("uniforms.scales","i",s)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Nt("uniforms.roi","i",i)}; var roi_hi = ${Nt("uniforms.roi",`i + ${r.length}`,i)}; var input_shape_i = ${Nt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Nt("uniforms.output_shape","i",n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${a} || (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; }`,Qc=(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 >= ${Nt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Yd=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",Yc=(e,t,r,n,s)=>{let[i,a,u,d]=r.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",a,`max(0, min(row, ${r[a]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; ${Yd(e,d,i,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${c} = originalIndices[${a}]; var col:${c} = originalIndices[${u}]; ${n?`if (row < 0 || row > (${r[a]} - 1) || col < 0 || col > (${r[u]} - 1)) { return ${s}; }`:""}; row = max(0, min(row, ${r[a]} - 1)); col = max(0, min(col, ${r[u]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${r.length>2?`u32(originalIndices[${d}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${i}])`:"0"}; var x11: ${c} = getInputValue(batch, channel, row1, col1); var x12: ${c} = getInputValue(batch, channel, row1, col2); var x21: ${c} = getInputValue(batch, channel, row2, col1); var x22: ${c} = getInputValue(batch, channel, row2, col2); var dx1: ${c} = abs(row - ${c}(row1)); var dx2: ${c} = abs(${c}(row2) - row); var dy1: ${c} = abs(col - ${c}(col1)); var dy2: ${c} = abs(${c}(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); }`},Zc=(e,t,r,n,s,i,a,u,d,c)=>{let g=r.length===2,[l,y]=g?[0,1]:[2,3],v=e.type.value,S=x=>{let G=x===l?"row":"col";return` fn ${G}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${v} { var output_index = ${t.indicesGet("output_indices",x)}; var originalIdx: ${v} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[x]}, ${n[x]}, ${r[x]}, ${i[x]}, ${i[x]} + ${r.length}); var fractOriginalIdx: ${v} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${u} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) { return ${d}; } var data: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${G}: ${v} = originalIdx + ${v}(i); if (${G} < 0 || ${G} >= ${r[x]}) { ${c?`coefs[i + 1] = 0.0; continue;`:u?`return ${d};`:`${G} = max(0, min(${G}, ${r[x]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",x,`u32(${G})`)}; data[i + 1] = ${x===l?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${S(l)}; ${S(y)}; fn getCubicInterpolationCoefs(s: ${v}) -> array<${v}, 4> { var absS = abs(s); var coeffs: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${v} = 1.0 - absS; var twoMinusAbsS: ${v} = 2.0 - absS; var onePlusAbsS: ${v} = 1.0 + absS; coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; return coeffs; } fn cubicInterpolation1D(x: array<${v}, 4>, coefs: array<${v}, 4>) -> ${v} { var coefsSum: ${v} = 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}) -> ${v} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Jc=(e,t,r,n,s)=>{let[i,a,u,d,c]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",a,`max(0, min(depth, ${r[a]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; ${Yd(e,c,i,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${g} = originalIndices[${a}]; var height:${g} = originalIndices[${u}]; var width:${g} = originalIndices[${d}]; ${n?`if (depth < 0 || depth > (${r[a]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { return ${s}; }`:""}; depth = max(0, min(depth, ${r[a]} - 1)); height = max(0, min(height, ${r[u]} - 1)); width = max(0, min(width, ${r[d]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length>3?`u32(originalIndices[${c}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${i}])`:"0"}; var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${g} = abs(depth - ${g}(depth1)); var dx2: ${g} = abs(${g}(depth2) - depth); var dy1: ${g} = abs(height - ${g}(height1)); var dy2: ${g} = abs(${g}(height2) - height); var dz1: ${g} = abs(width - ${g}(width1)); var dz2: ${g} = abs(${g}(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); }`},ep=(e,t,r,n,s,i)=>{let a=e.dims,u=Gc(i,t.axes,a.length),d=qc(a,n,s,t.axes),c=n.slice();n.length===0&&(c=a.map((k,Z)=>k===0?1:d[Z]/k),t.keepAspectRatioPolicy!=="stretch"&&(d=Hc(a,c,t)));let g=Vt("output",e.dataType,d.length),l=Ze("input",e.dataType,a.length),y=Ie.size(d),v=a.length===d.length&&a.every((k,Z)=>k===d[Z]),S=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,G=l.type.value,q=k=>` ${v?"":` ${Uc(t.coordinateTransformMode,G)}; ${(()=>{switch(t.mode){case"nearest":return` ${Qc(l,a)}; ${Wc(t.nearestMode,r,G)}; ${Xc(l,g,a,d,c.length,u.length,S)}; `;case"linear":return` ${Kc(g,a,d,c.length,u.length)}; ${(()=>{if(a.length===2||a.length===4)return`${Yc(l,g,a,S,x)}`;if(a.length===3||a.length===5)return`${Jc(l,g,a,S,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(a.length===2||a.length===4)return`${Zc(l,g,a,d,c,u,t.cubicCoeffA,S,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")}})()}; `} ${k.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",u.length).declareVariables(l,g)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${v?"output[global_idx] = input[global_idx];":` let output_indices = ${g.offsetToIndices("global_idx")}; var input_indices: ${l.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${l.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?c:""}|${s.length>0?s:""}|${u.length>0?u:""}|${v}|${a}`,inputDependencies:["rank"]},getShaderSource:q,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},{type:1,data:c},{type:1,data:u},...Pt(a,d)]})}},tp=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},rp=(e,t)=>{let r=[],n=[],s=[],i=tp(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Vc(e.inputs,t,i,r,n,s),e.compute(ep(e.inputs[0],t,i,r,n,s),{inputs:[0]})},np=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return qt({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:u,mode:d,nearestMode:c})}}),sp,ip,ap,Df=R(()=>{Kt(),Xt(),Cr(),sr(),sp=(e,t)=>{let[r,n,s,i]=e,{numHeads:a,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!Ie.areEqual(n.dims,[])&&!Ie.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(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!Ie.areEqual(s.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],c=r.dims[r.dims.length-2],g=s.dims[0],l=Ie.sizeFromDimension(r.dims,1)/c,y=u===0?s.dims[1]*2:l/a;if(u>y)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(y/2!==s.dims[1]&&u/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(c>g)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ip=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:i}=t,a=e[0].dims[0],u=Ie.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=u/d,g=e[2].dims[1],l=s===0?g*2:c/n,y=new Array(a,d,c/l,l-g),v=Ie.computeStrides(y),S=[{type:1,data:i},{type:12,data:y},{type:12,data:v},...e[0].dims.length===3?new Array({type:12,data:[u,c,l,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,l,d*l,1]}):[],...Pt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],x=G=>{let q=Ze("input",e[0].dataType,e[0].dims.length),k=Ze("position_ids",e[1].dataType,e[1].dims.length),Z=Ze("cos_cache",e[2].dataType,e[2].dims.length),ee=Ze("sin_cache",e[3].dataType,e[3].dims.length),fe=Vt("output",e[0].dataType,e[0].dims.length);return G.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:y.length},{name:"global_strides",type:"u32",length:v.length},{name:"input_output_strides",type:"u32",length:v.length}]),` ${G.declareVariables(q,k,Z,ee,fe)} ${G.mainStart(hn)} let half_rotary_emb_dim = uniforms.${Z.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${G.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${k.broadcastedIndicesToOffset("bsnh.xy",Vt("",k.type.tensor,2))}; let position_id = u32(${k.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${q.getByOffset("i")} * ${Z.get("position_id","bsnh[3]")} - ${q.getByOffset("j")} * ${ee.get("position_id","bsnh[3]")}; ${fe.setByOffset("i","re")} let im = ${q.getByOffset("i")} * ${ee.get("position_id","bsnh[3]")} + ${q.getByOffset("j")} * ${Z.get("position_id","bsnh[3]")}; ${fe.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${fe.setByOffset("k",q.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:qt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Ie.size(y)/hn)},programUniforms:S})}},ap=(e,t)=>{sp(e.inputs,t),e.compute(ip(e.inputs,t))}}),op,lp,up,Bf=R(()=>{Kt(),Xt(),sr(),op=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)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]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},lp=(e,t,r,n)=>{let s=t.simplified,i=e[0].dims,a=Ie.size(i),u=i,d=a,c=i.slice(-1)[0],g=n?i.slice(0,-1).concat(1):[],l=!s&&e.length>3,y=e.length>4,v=n&&r>1,S=n&&r>2,x=r>3,G=64,q=Sr(c),k=[{type:12,data:d},{type:12,data:q},{type:12,data:c},{type:1,data:t.epsilon}],Z=fe=>{let We=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ne=[Ze("x",e[0].dataType,e[0].dims,q),Ze("skip",e[1].dataType,e[1].dims,q),Ze("gamma",e[2].dataType,e[2].dims,q)];l&&Ne.push(Ze("beta",e[3].dataType,e[3].dims,q)),y&&Ne.push(Ze("bias",e[4].dataType,e[4].dims,q)),Ne.push(Vt("output",e[0].dataType,u,q)),v&&Ne.push(Vt("mean_output",1,g)),S&&Ne.push(Vt("inv_std_output",1,g)),x&&Ne.push(Vt("input_skip_bias_sum",e[0].dataType,u,q));let mt=Er(e[0].dataType),jt=Er(1,q);return` ${fe.registerUniforms(We).declareVariables(...Ne)} var sum_shared : array<${jt}, ${G}>; var sum_squared_shared : array<${jt}, ${G}>; ${fe.mainStart([G,1,1])} let ix = local_id.x; let iy = global_id.x / ${G}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${G}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${G-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${y?"bias[offset1d + i]":mt+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${x?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${jr(mt,q,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${G}; 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 = ${fn("sum",q)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${fn("square_sum",q)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); ${v?"mean_output[global_idx] = mean;":""} ${S?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${s?"":`- ${mt}(mean)`}) * ${mt}(inv_std_dev) * gamma[offset1d + i] ${l?"+ beta[offset1d + i]":""}; } }`},ee=[{dims:u,dataType:e[0].dataType}];return r>1&&ee.push({dims:g,dataType:1}),r>2&&ee.push({dims:g,dataType:1}),r>3&&ee.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${q};${v};${S};${x}`,inputDependencies:e.map((fe,We)=>"type")},getShaderSource:Z,getRunData:()=>({outputs:ee,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:k})}},up=(e,t)=>{op(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(lp(e.inputs,t,e.outputCount,!1),{outputs:r})}}),dp,Mu,cp,Zd,pp,hp,fp,mp,Lf=R(()=>{Kt(),Xt(),Cr(),sr(),dp=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Mu=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},cp=(e,t)=>{if(e.length>1){let r=Mu(e,1),n=Mu(e,2),s=Mu(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),qt({starts:r,ends:n,axes:s})}else return t},Zd=(e,t,r,n,s)=>{let i=e;return e<0&&(i+=r[n[t]]),s[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},pp=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${Nt("uniforms.input_shape","i",r.length)}; let steps_i = ${Nt("uniforms.steps","i",r.length)}; let signs_i = ${Nt("uniforms.signs","i",r.length)}; let starts_i = ${Nt("uniforms.starts","i",r.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,hp=(e,t)=>{let r=e[0].dims,n=Ie.size(r),s=t.axes.length>0?Ie.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=Mu(e,4);i.forEach(q=>q!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(s.length).fill(1));let a=t.starts.map((q,k)=>Zd(q,k,r,s,i)),u=t.ends.map((q,k)=>Zd(q,k,r,s,i));if(s.length!==a.length||s.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let q=0;qMath.sign(q));i.forEach((q,k,Z)=>{if(q<0){let ee=(u[k]-a[k])/q,fe=a[k],We=fe+ee*i[k];a[k]=We,u[k]=fe,Z[k]=-q}});let c=r.slice(0);s.forEach((q,k)=>{c[q]=Math.ceil((u[q]-a[q])/i[q])});let g={dims:c,dataType:e[0].dataType},l=Vt("output",e[0].dataType,c.length),y=Ze("input",e[0].dataType,e[0].dims.length),v=Ie.size(c),S=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:i.length}],x=[{type:12,data:v},{type:12,data:a},{type:6,data:d},{type:12,data:i},...Pt(e[0].dims,c)],G=q=>` ${q.registerUniforms(S).declareVariables(y,l)} ${pp(y,l,r)} ${q.mainStart()} ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${l.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${l.setByOffset("global_idx",y.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:G,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:x})}},fp=(e,t)=>{dp(e.inputs,t);let r=cp(e.inputs,t);e.compute(hp(e.inputs,r),{inputs:[0]})},mp=e=>{let t=e.starts,r=e.ends,n=e.axes;return qt({starts:t,ends:r,axes:n})}}),_p,gp,wp,yp,Rf=R(()=>{Kt(),Xt(),Cr(),sr(),_p=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},gp=(e,t)=>{let r=e.dims,n=Ie.size(r),s=64,i=t.axis;if(i<0&&(i=r.length+i),iq===4?`max(max(${G}.x, ${G}.y), max(${G}.z, ${G}.w))`:q===2?`max(${G}.x, ${G}.y)`:q===3?`max(max(${G}.x, ${G}.y), ${G}.z)`:G,l=Ze("x",e.dataType,e.dims,d),y=Vt("result",e.dataType,e.dims,d),v=l.type.value,S=Er(e.dataType)==="f32"?`var threadMax = ${v}(-3.402823e+38f);`:`var threadMax = ${v}(-65504.0h);`,x=G=>` var rowMaxShared : ${v}; var rowSumShared : ${v}; var threadShared : array<${v}, ${s}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${v} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${v}) { let index = row * row_stride + col; result[index] = value; } ${G.registerUniform("packedCols","i32").declareVariables(l,y)} ${G.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${s}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${S} 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 = ${v}(${g("threadShared[0]",d)}); } workgroupBarrier(); // find the rows sum var threadSum = ${v}(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 = ${v}(${fn("threadShared[0]",d)}); } 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); } }`;return{name:"Softmax",shaderCache:{hint:`${d}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:c}]}),getShaderSource:x}},wp=(e,t)=>{_p(e.inputs),e.compute(gp(e.inputs[0],t))},yp=e=>qt({axis:e.axis})}),bp,Mp,vp,xp,Tp,Sp,$p,Nf=R(()=>{Kt(),Xt(),Cr(),sr(),bp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Mp=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),n=r.length),qt({numOutputs:n,axis:t.axis,splitSizes:r})},vp=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Nt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,xp=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Ie.size(r),s=e[0].dataType,i=Ie.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),u=Ze("input",s,r.length),d=new Array(t.numOutputs),c=[],g=[],l=0,y=[{type:12,data:n}];for(let S=0;S` ${S.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...a)} ${vp(d.length)} ${xp(a)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${u.offsetToIndices("global_idx")}; var index = ${u.indicesGet("indices",i)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Nt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; ${u.indicesSet("indices",i,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:y})}},Sp=(e,t)=>{bp(e.inputs);let r=e.inputs.length===1?t:Mp(e.inputs,t);e.compute(Tp(e.inputs,r),{inputs:[0]})},$p=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qt({axis:t,numOutputs:n,splitSizes:r})}}),Ep,Cp,kp,jf=R(()=>{Kt(),Xt(),sr(),Ep=(e,t,r,n,s)=>{let i=Vt("output_data",s,r.length,4),a=Ze("a_data",t[1].dataType,t[1].dims.length,4),u=Ze("b_data",t[2].dataType,t[2].dims.length,4),d=Ze("c_data",t[0].dataType,t[0].dims.length,4),c,g=(l,y,v)=>`select(${y}, ${l}, ${v})`;if(!n)c=i.setByOffset("global_idx",g(a.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let l=(y,v,S="")=>{let x=`a_data[index_a${v}][component_a${v}]`,G=`b_data[index_b${v}][component_b${v}]`,q=`bool(c_data[index_c${v}] & (0xffu << (component_c${v} * 8)))`;return` let output_indices${v} = ${i.offsetToIndices(`global_idx * 4u + ${v}u`)}; let offset_a${v} = ${a.broadcastedIndicesToOffset(`output_indices${v}`,i)}; let offset_b${v} = ${u.broadcastedIndicesToOffset(`output_indices${v}`,i)}; let offset_c${v} = ${d.broadcastedIndicesToOffset(`output_indices${v}`,i)}; let index_a${v} = offset_a${v} / 4u; let index_b${v} = offset_b${v} / 4u; let index_c${v} = offset_c${v} / 4u; let component_a${v} = offset_a${v} % 4u; let component_b${v} = offset_b${v} % 4u; let component_c${v} = offset_c${v} % 4u; ${y}[${v}] = ${S}(${g(x,G,q)}); `};s===9?c=` var data = vec4(0); ${l("data",0,"u32")} ${l("data",1,"u32")} ${l("data",2,"u32")} ${l("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` ${l("output_data[global_idx]",0)} ${l("output_data[global_idx]",1)} ${l("output_data[global_idx]",2)} ${l("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(d,a,u,i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${c} }`},Cp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,i=!(Ie.areEqual(t,r)&&Ie.areEqual(r,n)),a=t,u=Ie.size(t);if(i){let c=Rr.calcShape(Rr.calcShape(t,r,!1),n,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,u=Ie.size(a)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Ep(c,e,a,i,s),getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...Pt(n,t,r,a)]})}},kp=e=>{e.compute(Cp(e.inputs))}}),Pp,Vf=R(()=>{ku(),Qs(),Pu(),Au(),Iu(),Fu(),Ou(),ha(),Bu(),Lu(),Gd(),Nu(),Zl(),Wu(),Gu(),Ku(),Xu(),Qu(),qd(),Hd(),Kd(),kl(),wd(),Ju(),D(),Qr(),Bn(),Qd(),Fi(),zf(),Df(),Bf(),Lf(),Rf(),Nf(),nd(),ps(),Zi(),jf(),Pp=new Map([["Abs",[Eo]],["Acos",[Co]],["Acosh",[Bi]],["Add",[tl]],["ArgMax",[mo,Xs]],["ArgMin",[fo,Xs]],["Asin",[ko]],["Asinh",[Po]],["Atan",[Li]],["Atanh",[Ao]],["Attention",[bo]],["AveragePool",[er,pr]],["BatchNormalization",[xo]],["BiasAdd",[Di]],["BiasSplitGelu",[Jo]],["Cast",[Ri,Io]],["Ceil",[Ys]],["Clip",[Oo]],["Concat",[cl,pl]],["Conv",[pa,da]],["ConvTranspose",[Du,Rl]],["Cos",[zo]],["Cosh",[Do]],["CumSum",[ga,Ul]],["DepthToSpace",[ya,Ru]],["DequantizeLinear",[Os,Xd]],["Div",[rl]],["Einsum",[Ql,va]],["Elu",[Ni,Cs]],["Equal",[nl]],["Erf",[ji]],["Exp",[Bo]],["Expand",[Uu]],["FastGelu",[eu]],["Floor",[Lo]],["FusedConv",[pa,da]],["Gather",[ru,Ta]],["GatherElements",[ou,au]],["GatherBlockQuantized",[Hu,nu]],["Gelu",[Ro]],["Gemm",[cu,du]],["GlobalAveragePool",[Mr,ir]],["GlobalMaxPool",[mn,Sn]],["Greater",[ta]],["GreaterOrEqual",[ol]],["GroupQueryAttention",[od,id]],["HardSigmoid",[Wi,Wo]],["InstanceNormalization",[cd]],["LayerNormalization",[fd]],["LeakyRelu",[Vi,Cs]],["Less",[al]],["LessOrEqual",[ra]],["Log",[Xo]],["MatMul",[Cl]],["MatMulNBits",[gd,lr]],["MaxPool",[tn,Hn]],["Mul",[ea]],["MultiHeadAttention",[Zu,hu]],["Neg",[jo]],["Not",[No]],["Pad",[h]],["Pow",[sl]],["QuickGelu",[Yo,Cs]],["Range",[Md]],["Reciprocal",[Vo]],["ReduceMin",[Ai]],["ReduceMean",[ao]],["ReduceMax",[uo]],["ReduceSum",[po]],["ReduceProd",[co]],["ReduceL1",[oo]],["ReduceL2",[Pi]],["ReduceLogSum",[ho]],["ReduceLogSumExp",[lo]],["ReduceSumSquare",[Ii]],["Relu",[Ui]],["Resize",[rp,np]],["RotaryEmbedding",[ap]],["Sigmoid",[Uo]],["Sin",[Go]],["Sinh",[qo]],["Slice",[fp,mp]],["SkipLayerNormalization",[up]],["Split",[Sp,$p]],["Sqrt",[Gi]],["Softmax",[wp,yp]],["Sub",[il]],["Tan",[Ho]],["Tanh",[Hi]],["ThresholdedRelu",[Ko,Cs]],["Tile",[rd]],["Transpose",[Da,Mi]],["Where",[kp]]])}),Ap,Uf=R(()=>{Bt(),wn(),sr(),Ap=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,s){je(e.programInfo.name);let i=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let c of t)u.push({binding:u.length,resource:{buffer:c.buffer}});for(let c of r)u.push({binding:u.length,resource:{buffer:c.buffer}});s&&u.push({binding:u.length,resource:s});let d=i.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}a.setPipeline(e.computePipeline),a.setBindGroup(0,d),a.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(),Ve(e.programInfo.name)}dispose(){}build(e,t){je(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=Fa(t,this.backend.device.limits),i=e.getShaderSource(s),a=`${n.join(` `)} ${s.additionalImplementations} ${i}`,u=r.createShaderModule({code:a,label:e.name});Nr("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Ve(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let i=t*r*n,a=Math.ceil(Math.sqrt(i));if(a>s){if(a=Math.ceil(Math.cbrt(i)),a>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),Ip,Fp,Op,zp,Wf=R(()=>{Bt(),Kt(),wn(),m(),or(),Vf(),Uf(),Ip=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${Ip(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},Op=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},zp=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(n),this.adapterInfo=new Op(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fr(this),this.programManager=new Ap(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ds(e.logLevel,!!e.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.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;je(),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(()=>{let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let n=0;n"u"&&(this.queryTimeBase=y);let S=Number(y-this.queryTimeBase),x=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(G=>({dims:G.dims,dataType:Cn(G.dataType)})),outputsMetadata:l.map(G=>({dims:G.dims,dataType:Cn(G.dataType)})),kernelId:i,kernelType:u,kernelName:d,programName:c,startTime:S,endTime:x});else{let G="";g.forEach((k,Z)=>{G+=`input[${Z}]: [${k.dims}] | ${Cn(k.dataType)}, `});let q="";l.forEach((k,Z)=>{q+=`output[${Z}]: [${k.dims}] | ${Cn(k.dataType)}, `}),console.log(`[profiling] kernel "${i}|${u}|${d}|${c}" ${G}${q}execution time: ${x-S} ns`)}Ee("GPU",`${c}::${y}::${v}`)}e.unmap(),this.pendingQueries.delete(e)}),Ve()}run(e,t,r,n,s,i){je(e.name);let a=[];for(let k=0;kZ):r;if(g.length!==u.length)throw new Error(`Output size ${g.length} must be equal to ${u.length}.`);let l=[],y=[];for(let k=0;k=i)throw new Error(`Invalid output index: ${g[k]}`);if(g[k]===-3)continue;let Z=g[k]===-1,ee=g[k]===-2,fe=Z||ee?s(u[k].dataType,u[k].dims):n(g[k],u[k].dataType,u[k].dims);if(l.push(fe),fe.data===0)continue;let We=this.gpuDataManager.get(fe.data);if(!We)throw new Error(`no GPU data for output: ${fe.data}`);if(Z&&this.temporaryData.push(We),ee){let Ne=this.kernelPersistentData.get(this.currentKernelId);Ne||(Ne=[],this.kernelPersistentData.set(this.currentKernelId,Ne)),Ne.push(We)}y.push(We)}if(a.length!==t.length||y.length!==l.length){if(y.length===0)return Ve(e.name),l;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(c){let k=0,Z=[];c.forEach(Ne=>{let mt=typeof Ne.data=="number"?[Ne.data]:Ne.data;if(mt.length===0)return;let jt=Ne.type===10?2:4,Lt,dr;Ne.type===10?(dr=mt.length>4?16:mt.length>2?8:mt.length*jt,Lt=mt.length>4?16:jt*mt.length):(dr=mt.length<=2?mt.length*jt:16,Lt=16),k=Math.ceil(k/dr)*dr,Z.push(k);let ar=Ne.type===10?8:4;k+=mt.length>4?Math.ceil(mt.length/ar)*Lt:mt.length*jt});let ee=16;k=Math.ceil(k/ee)*ee;let fe=new ArrayBuffer(k);c.forEach((Ne,mt)=>{let jt=Z[mt],Lt=typeof Ne.data=="number"?[Ne.data]:Ne.data;if(Ne.type===6)new Int32Array(fe,jt,Lt.length).set(Lt);else if(Ne.type===12)new Uint32Array(fe,jt,Lt.length).set(Lt);else if(Ne.type===10)new Uint16Array(fe,jt,Lt.length).set(Lt);else if(Ne.type===1)new Float32Array(fe,jt,Lt.length).set(Lt);else throw new Error(`Unsupported uniform type: ${Cn(Ne.type)}`)});let We=this.gpuDataManager.create(k,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(We.buffer,0,fe,0,k),this.gpuDataManager.release(We.id),v={offset:0,size:k,buffer:We.buffer}}let S=this.programManager.normalizeDispatchGroupSize(d),x=S[1]===1&&S[2]===1,G=Fp(e,t,x),q=this.programManager.getArtifact(G);if(q||(q=this.programManager.build(e,S),this.programManager.setArtifact(G,q),Nr("info",()=>`[artifact] key: ${G}, programName: ${e.name}`)),c&&q.uniformVariablesInfo){if(c.length!==q.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${q.uniformVariablesInfo.length}, got ${c.length} in program "${q.programInfo.name}".`);for(let k=0;k`[ProgramManager] run "${e.name}" (key=${G}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let k={kernelId:this.currentKernelId,programName:q.programInfo.name,inputTensorViews:t,outputTensorViews:l};this.pendingKernels.push(k),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(k)}return this.programManager.run(q,a,y,S,v),Ve(e.name),l}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let s=Pp.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let i={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,i)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,i=n.kernelName,a=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${i}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),Nr("info",()=>`[WebGPU] Start to run kernel "[${s}] ${i}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),a(t,u[1]),0}catch(c){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${i}" failed. ${c}`)),1}finally{d&&r.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${s}] ${i}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let i=s.get(t),a=this.gpuDataManager.registerExternalBuffer(r,n,i?.[1]);return s.set(t,[a,r]),a}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await kt(this,e,t);return we(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.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(){Nr("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(){Nr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Nr("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}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()}}}),Dp={};$(Dp,{init:()=>Lp});var vd,Bp,Lp,Gf=R(()=>{Kt(),Wf(),wn(),Xt(),vd=class kf{constructor(t,r,n,s){this.module=t,this.dataType=r,this.data=n,this.dims=s}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Ie.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Ie.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=Ie.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=Ie.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Ie.size(t)!==Ie.size(this.dims))throw new Error("Invalid new shape");return new kf(this.module,this.dataType,this.data,t)}},Bp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,s=r>>>2;this.opKernelContext=n[s++];let i=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let a=[];for(let u=0;utypeof a=="number"?this.inputs[a]:a)??this.inputs,n=t?.outputs??[],s=(a,u,d)=>new vd(this.module,u,this.output(a,d),d),i=(a,u)=>{let d=Wn(a,u);if(!d)throw new Error(`Unsupported data type: ${a}`);let c=d>0?this.backend.gpuDataManager.create(d).id:0;return new vd(this.module,a,c,u)};return this.backend.run(e,r,n,s,i,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let i=0;i{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new zp;await i.initialize(r,n),s("webgpu",[i,a=>i.alloc(a),a=>i.free(a),(a,u,d,c=!1)=>{if(c)Nr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${u}, size=${d}`),i.memcpy(a,u);else{Nr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${u}, size=${d}`);let g=t.HEAPU8.subarray(a>>>0,(a>>>0)+d);i.upload(u,g)}},async(a,u,d)=>{Nr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${u}, size=${d}`),await i.download(a,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(a,u,d)=>i.createKernel(a,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),a=>i.releaseKernel(a),(a,u,d,c)=>{Nr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${u}`);let g=new Bp(t,i,u);return i.computeKernel(a,g,c)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else s("webnn")}}),Rp,Jd,ec,zs,Np,xd,tc,rc,nc,sc,ic,ac,jp=R(()=>{Us(),Ws(),Kt(),pn(),Vn(),vs(),Rp=(e,t)=>{Hr()._OrtInit(e,t)!==0&&Lr("Can't initialize onnxruntime.")},Jd=async e=>{Rp(e.wasm.numThreads,Yn(e.logLevel))},ec=async(e,t)=>{{let r=(Gf(),P(Dp)).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 s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",Hr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Hr(),e)}}},zs=new Map,Np=e=>{let t=Hr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Lr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},xd=e=>{let t=Hr(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},tc=async(e,t)=>{let r,n,s=Hr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=xd(e);let i=0,a=0,u=0,d=[],c=[],g=[];try{if([a,d]=Un(t),t?.externalData&&s.mountExternalData){let k=[];for(let Z of t.externalData){let ee=typeof Z=="string"?Z:Z.path;k.push(Zn(typeof Z=="string"?Z:Z.data).then(fe=>{s.mountExternalData(ee,fe)}))}await Promise.all(k)}for(let k of t?.executionProviders??[])if((typeof k=="string"?k:k.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof k!="string"){let Z=k,ee=Z?.context,fe=Z?.gpuDevice,We=Z?.deviceType,Ne=Z?.numThreads,mt=Z?.powerPreference;ee?s.currentContext=ee:fe?s.currentContext=await navigator.ml.createContext(fe):s.currentContext=await navigator.ml.createContext({deviceType:We,numThreads:Ne,powerPreference:mt})}else s.currentContext=await navigator.ml.createContext();break}i=await s._OrtCreateSession(r,n,a),i===0&&Lr("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[l,y]=Np(i),v=!!t?.enableGraphCapture,S=[],x=[],G=[];for(let k=0;kk==="gpu-buffer")&&(u=s._OrtCreateBinding(i),u===0&&Lr("Can't create IO binding."),q={handle:u,outputPreferredLocations:G,outputPreferredLocationsEncoded:G.map(k=>ls(k))}),zs.set(i,[i,c,g,q,v,!1]),[i,S,x]}catch(l){throw c.forEach(y=>s._OrtFree(y)),g.forEach(y=>s._OrtFree(y)),u!==0&&s._OrtReleaseBinding(u),i!==0&&s._OrtReleaseSession(i),l}finally{s._free(r),a!==0&&s._OrtReleaseSessionOptions(a),d.forEach(l=>s._free(l)),s.unmountExternalData?.()}},rc=e=>{let t=Hr(),r=zs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,i,a,u]=r;a&&(u&&t._OrtClearBoundOutputs(a.handle),t._OrtReleaseBinding(a.handle)),t.jsepOnReleaseSession?.(e),s.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n),zs.delete(e)},nc=(e,t,r,n,s,i=!1)=>{if(!e){t.push(0);return}let a=Hr(),u=e[0],d=e[1],c=e[3],g,l;if(u==="string"&&c==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(i&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let S=e[2].gpuBuffer;l=Wn(as(u),d);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=x(n,s,S,l)}else{let S=e[2];if(Array.isArray(S)){l=4*S.length,g=a._malloc(l),r.push(g);let x=g/4;for(let G=0;Ga.HEAP32[S++]=G);let x=a._OrtCreateTensor(as(u),g,l,v,d.length,ls(c));x===0&&Lr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(x)}finally{a.stackRestore(y)}},sc=async(e,t,r,n,s,i)=>{let a=Hr(),u=zs.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],c=u[1],g=u[2],l=u[3],y=u[4],v=u[5],S=t.length,x=n.length,G=0,q=[],k=[],Z=[],ee=[],fe=a.stackSave(),We=a.stackAlloc(S*4),Ne=a.stackAlloc(S*4),mt=a.stackAlloc(x*4),jt=a.stackAlloc(x*4);try{[G,q]=In(i);for(let Yt=0;Ytgn*cn,1);Ke=Cn(Vr);let $n=l?.outputPreferredLocations[n[Yt]];if(Ke==="string"){if($n==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let gn=[],cn=$t/4;for(let Bs=0;Bs0){let gn=a.jsepGetBuffer;if(!gn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let cn=gn($t),Bs=Wn(Vr,An);if(Bs===void 0||!os(Ke))throw new Error(`Unsupported data type: ${Ke}`);gr=!0,hr.push([Ke,Kn,{gpuBuffer:cn,download:a.jsepCreateDownloader(cn,Bs,Ke),dispose:()=>{a._OrtReleaseTensor(Ar)}},"gpu-buffer"])}else{let gn=Fn(Ke),cn=new gn(An);new Uint8Array(cn.buffer,cn.byteOffset,cn.byteLength).set(a.HEAPU8.subarray($t,$t+cn.byteLength)),hr.push([Ke,Kn,cn,"cpu"])}}finally{a.stackRestore(Br),Ke==="string"&&$t&&a._free($t),gr||a._OrtReleaseTensor(Ar)}}return l&&!y&&(a._OrtClearBoundOutputs(l.handle),zs.set(e,[d,c,g,l,y,!1])),hr}finally{a.stackRestore(fe),k.forEach(Lt=>a._OrtReleaseTensor(Lt)),Z.forEach(Lt=>a._OrtReleaseTensor(Lt)),ee.forEach(Lt=>a._free(Lt)),G!==0&&a._OrtReleaseRunOptions(G),q.forEach(Lt=>a._free(Lt))}},ic=e=>{let t=Hr(),r=zs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Lr("Can't get an profile file name."),t._OrtFree(s)},ac=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Ds,Ln,Ea,vu,xu,Td,oc,Sd,ci,pi,Vp,Up,Wp,Gp,qp,Hp,Kp,Xp,Qp=R(()=>{Bt(),jp(),pn(),rr(),Ds=()=>!!C.wasm.proxy&&typeof document<"u",Ea=!1,vu=!1,xu=!1,Sd=new Map,ci=(e,t)=>{let r=Sd.get(e);r?r.push(t):Sd.set(e,[t])},pi=()=>{if(Ea||!vu||xu||!Ln)throw new Error("worker not ready")},Vp=e=>{switch(e.data.type){case"init-wasm":Ea=!1,e.data.err?(xu=!0,oc[1](e.data.err)):(vu=!0,oc[0]()),Td&&(URL.revokeObjectURL(Td),Td=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Sd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Up=async()=>{if(!vu){if(Ea)throw new Error("multiple calls to 'initWasm()' detected.");if(xu)throw new Error("previous call to 'initWasm()' failed.");if(Ea=!0,Ds())return new Promise((e,t)=>{Ln?.terminate(),Ut().then(([r,n])=>{try{Ln=n,Ln.onerror=i=>t(i),Ln.onmessage=Vp,oc=[e,t];let s={type:"init-wasm",in:C};Ln.postMessage(s),Td=r}catch(s){t(s)}},t)});try{await is(C.wasm),await Jd(C),vu=!0}catch(e){throw xu=!0,e}finally{Ea=!1}}},Wp=async e=>{if(Ds())return pi(),new Promise((t,r)=>{ci("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:C}};Ln.postMessage(n)});await ec(C,e)},Gp=async e=>Ds()?(pi(),new Promise((t,r)=>{ci("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Ln.postMessage(n,[e.buffer])})):xd(e),qp=async(e,t)=>{if(Ds()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return pi(),new Promise((r,n)=>{ci("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Ln.postMessage(s,i)})}else return tc(e,t)},Hp=async e=>{if(Ds())return pi(),new Promise((t,r)=>{ci("release",[t,r]);let n={type:"release",in:e};Ln.postMessage(n)});rc(e)},Kp=async(e,t,r,n,s,i)=>{if(Ds()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return pi(),new Promise((a,u)=>{ci("run",[a,u]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Ln.postMessage(c,ac(d))})}else return sc(e,t,r,n,s,i)},Xp=async e=>{if(Ds())return pi(),new Promise((t,r)=>{ci("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Ln.postMessage(n)});ic(e)}}),lc,Yp,Zp,qf=R(()=>{Bt(),Qp(),Kt(),et(),vs(),lc=(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"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Yp=e=>{switch(e[3]){case"cpu":return new Fe(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!os(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Fe.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},Zp=class{async fetchModelAndCopyToWasmMemory(e){return Gp(await Zn(e))}async loadModel(e,t){je();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await qp(r,t),Ve()}async dispose(){return Hp(this.sessionId)}async run(e,t,r){je();let n=[],s=[];Object.entries(e).forEach(l=>{let y=l[0],v=l[1],S=this.inputNames.indexOf(y);if(S===-1)throw new Error(`invalid input '${y}'`);n.push(v),s.push(S)});let i=[],a=[];Object.entries(t).forEach(l=>{let y=l[0],v=l[1],S=this.outputNames.indexOf(y);if(S===-1)throw new Error(`invalid output '${y}'`);i.push(v),a.push(S)});let u=n.map((l,y)=>lc(l,()=>`input "${this.inputNames[s[y]]}"`)),d=i.map((l,y)=>l?lc(l,()=>`output "${this.outputNames[a[y]]}"`):null),c=await Kp(this.sessionId,s,u,a,d,r),g={};for(let l=0;l{Bt(),Qp(),qf(),rr(),Jp=()=>{if((typeof C.wasm.initTimeout!="number"||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0),C.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 C.wasm.proxy!="boolean"&&(C.wasm.proxy=!1),typeof C.wasm.trace!="boolean"&&(C.wasm.trace=!1),typeof C.wasm.numThreads!="number"||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>"u"?be("node:os").cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},eh=class{async init(e){Jp(),await Up(),await Wp(e)}async createInferenceSessionHandler(e,t){let r=new Zp;return await r.loadModel(e,t),Promise.resolve(r)}}}),th={};$(th,{wasmBackend:()=>rh});var rh,Kf=R(()=>{Hf(),rh=new eh});Bt(),Bt(),Bt();var Xf="1.20.0-dev.20240827-1d059b8702",Qf=pt;{let e=(Kf(),P(th)).wasmBackend;oe("webgpu",e,5),oe("webnn",e,5),oe("cpu",e,10),oe("wasm",e,10)}Object.defineProperty(C.versions,"web",{value:Xf,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":(_t,Me,N)=>{var I;N.r(Me),N.d(Me,{Tensor:()=>be.Tensor,createInferenceSession:()=>_e,deviceToExecutionProviders:()=>ne,isONNXProxy:()=>se,isONNXTensor:()=>F});var ae=N("./src/env.js"),he=N("?2ce3"),xe=N("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),be=N("./node_modules/onnxruntime-common/dist/esm/index.js");const R=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"}}),$=[];let V,P;if(ae.apis.IS_NODE_ENV){switch(P=he??(I||(I=N.t(he,2))),process.platform){case"win32":$.push("dml");break;case"linux":process.arch==="x64"&&$.push("cuda");break}$.push("cpu"),V=["cpu"]}else P=xe,ae.apis.IS_WEBNN_AVAILABLE&&$.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ae.apis.IS_WEBGPU_AVAILABLE&&$.push("webgpu"),$.push("wasm"),V=["wasm"];const K=P.InferenceSession;function ne(le=null){if(!le)return V;switch(le){case"auto":return $;case"gpu":return $.filter(ie=>["webgpu","cuda","dml","webnn-gpu"].includes(ie))}if($.includes(le))return[R[le]??le];throw new Error(`Unsupported device: "${le}". Should be one of: ${$.join(", ")}.`)}let oe=null;async function _e(le,ie){oe&&await oe;const j=K.create(le,ie);return oe??=j,await j}function F(le){return le instanceof P.Tensor}const Q=P?.env;Q?.wasm&&(Q.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${ae.env.version}/dist/`,Q.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(Q.wasm.numThreads=1)),Q?.webgpu&&(Q.webgpu.powerPreference="high-performance");function se(){return Q?.wasm?.proxy}ae.env.backends.onnx=Q},"./src/configs.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{AutoConfig:()=>$,PretrainedConfig:()=>R,getKeyValueShapes:()=>be});var I=N("./src/utils/core.js"),ae=N("./src/utils/hub.js");async function he(V,P){return await(0,ae.getModelJSON)(V,"config.json",!0,P)}function xe(V){const P={};let K={};switch(V.model_type){case"llava":case"paligemma":case"florence2":K=xe(V.text_config);break;case"moondream1":K=xe(V.phi_config);break;case"musicgen":K=xe(V.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":P.num_heads="num_attention_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size",P.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.dim_kv="head_dim";break;case"openelm":P.num_heads="num_kv_heads",P.num_layers="num_transformer_layers",P.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":P.num_heads="num_heads",P.num_layers="num_layers",P.hidden_size="hidden_size";break;case"bloom":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="hidden_size";break;case"mpt":P.num_heads="n_heads",P.num_layers="n_layers",P.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":P.num_decoder_layers="num_decoder_layers",P.num_decoder_heads="num_heads",P.decoder_dim_kv="d_kv",P.num_encoder_layers="num_layers",P.num_encoder_heads="num_heads",P.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":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="d_model",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="d_model";break;case"speecht5":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="hidden_size",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="hidden_size";break;case"trocr":P.num_encoder_layers=P.num_decoder_layers="decoder_layers",P.num_encoder_heads=P.num_decoder_heads="decoder_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="d_model";break;case"musicgen_decoder":P.num_encoder_layers=P.num_decoder_layers="num_hidden_layers",P.num_encoder_heads=P.num_decoder_heads="num_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const oe=xe(V.decoder),_e="num_decoder_layers"in oe,F=(0,I.pick)(V,["model_type","is_encoder_decoder"]);return _e?(F.num_decoder_layers=oe.num_decoder_layers,F.num_decoder_heads=oe.num_decoder_heads,F.decoder_hidden_size=oe.decoder_hidden_size,F.num_encoder_layers=oe.num_encoder_layers,F.num_encoder_heads=oe.num_encoder_heads,F.encoder_hidden_size=oe.encoder_hidden_size):(F.num_layers=oe.num_layers,F.num_heads=oe.num_heads,F.hidden_size=oe.hidden_size),F}const ne={...K,...(0,I.pick)(V,["model_type","multi_query","is_encoder_decoder"])};for(const oe in P)ne[oe]=V[P[oe]];return ne}function be(V,{prefix:P="past_key_values"}={}){const K={},ne=V.normalized_config,oe=1;if(ne.is_encoder_decoder&&"num_encoder_heads"in ne&&"num_decoder_heads"in ne){const _e=ne.encoder_dim_kv??ne.encoder_hidden_size/ne.num_encoder_heads,F=ne.decoder_dim_kv??ne.decoder_hidden_size/ne.num_decoder_heads,Q=[oe,ne.num_encoder_heads,0,_e],se=[oe,ne.num_decoder_heads,0,F];for(let le=0;le{N.r(Me),N.d(Me,{apis:()=>F,env:()=>A});var I=N("?569f"),ae=N("?3f59"),he=N("?154a");const xe="3.0.0-alpha.14",be=typeof self<"u",R=be&&self.constructor.name==="DedicatedWorkerGlobalScope",$=be&&"caches"in self,V=typeof navigator<"u"&&"gpu"in navigator,P=typeof navigator<"u"&&"ml"in navigator,K=typeof process<"u",ne=K&&process?.release?.name==="node",oe=!L(I),_e=!L(ae),F=Object.freeze({IS_BROWSER_ENV:be,IS_WEBWORKER_ENV:R,IS_WEB_CACHE_AVAILABLE:$,IS_WEBGPU_AVAILABLE:V,IS_WEBNN_AVAILABLE:P,IS_PROCESS_AVAILABLE:K,IS_NODE_ENV:ne,IS_FS_AVAILABLE:oe,IS_PATH_AVAILABLE:_e}),Q=oe&&_e,se=Q?ae.dirname(ae.dirname(he.fileURLToPath(import.meta.url))):"./",le=Q?ae.join(se,"/.cache/"):null,ie="/models/",j=Q?ae.join(se,ie):ie,A={version:xe,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!be,localModelPath:j,useFS:oe,useBrowserCache:$,useFSCache:oe,cacheDir:le,useCustomCache:!1,customCache:null};function L(C){return Object.keys(C).length===0}},"./src/generation/configuration_utils.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{GenerationConfig:()=>ae});var I=N("./src/utils/core.js");class ae{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(xe){Object.assign(this,(0,I.pick)(xe,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{ClassifierFreeGuidanceLogitsProcessor:()=>Q,ForcedBOSTokenLogitsProcessor:()=>R,ForcedEOSTokenLogitsProcessor:()=>$,LogitsProcessor:()=>he,LogitsProcessorList:()=>be,LogitsWarper:()=>xe,MinLengthLogitsProcessor:()=>oe,MinNewTokensLengthLogitsProcessor:()=>_e,NoBadWordsLogitsProcessor:()=>F,NoRepeatNGramLogitsProcessor:()=>K,RepetitionPenaltyLogitsProcessor:()=>ne,SuppressTokensAtBeginLogitsProcessor:()=>V,TemperatureLogitsWarper:()=>se,TopKLogitsWarper:()=>ie,TopPLogitsWarper:()=>le,WhisperTimeStampLogitsProcessor:()=>P});var I=N("./src/utils/generic.js");N("./src/utils/tensor.js");var ae=N("./src/utils/maths.js");class he extends I.Callable{_call(A,L){throw Error("`_call` should be implemented in a subclass")}}class xe extends I.Callable{_call(A,L){throw Error("`_call` should be implemented in a subclass")}}class be extends I.Callable{constructor(){super(),this.processors=[]}push(A){this.processors.push(A)}extend(A){this.processors.push(...A)}_call(A,L){let C=L;for(const me of this.processors)C=me(A,C);return C}[Symbol.iterator](){return this.processors.values()}}class R extends he{constructor(A){super(),this.bos_token_id=A}_call(A,L){for(let C=0;C=1&&ye[ye.length-1]>=this.timestamp_begin,Pe=ye.length<2||ye[ye.length-2]>=this.timestamp_begin;if(Se&&(Pe?me.subarray(this.timestamp_begin).fill(-1/0):me.subarray(0,this.eos_token_id).fill(-1/0)),A[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const dt=this.timestamp_begin+this.max_initial_timestamp_index;me.subarray(dt+1).fill(-1/0)}const Ce=(0,ae.log_softmax)(me),rt=Math.log(Ce.subarray(this.timestamp_begin).map(Math.exp).reduce((dt,ge)=>dt+ge)),Xe=(0,ae.max)(Ce.subarray(0,this.timestamp_begin))[0];rt>Xe&&me.subarray(0,this.timestamp_begin).fill(-1/0)}return L}}class K extends he{constructor(A){super(),this.no_repeat_ngram_size=A}getNgrams(A){const L=A.length,C=[];for(let ye=0;ye1 to use the classifier free guidance processor, got guidance scale ${A}.`);this.guidance_scale=A}_call(A,L){if(L.dims[0]!==2*A.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 ${L.dims[0]} for the logits and ${A.length} for the input ids.`);const C=A.length,me=L.slice([0,C],null),ye=L.slice([C,L.dims[0]],null);for(let Se=0;Se1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${A}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=A,this.filter_value=L,this.min_tokens_to_keep=C}}class ie extends xe{constructor(A,{filter_value:L=-1/0,min_tokens_to_keep:C=1}={}){if(super(),!Number.isInteger(A)||A<0)throw new Error(`\`top_k\` must be a positive integer, but is ${A}`);this.top_k=Math.max(A,C),this.filter_value=L}}},"./src/generation/logits_sampler.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{LogitsSampler:()=>xe});var I=N("./src/utils/generic.js"),ae=N("./src/utils/tensor.js"),he=N("./src/utils/maths.js");N("./src/generation/configuration_utils.js");class xe extends I.Callable{constructor(P){super(),this.generation_config=P}async _call(P){return this.sample(P)}async sample(P){throw Error("sample should be implemented in subclasses.")}getLogits(P,K){let ne=P.dims.at(-1),oe=P.data;if(K===-1)oe=oe.slice(-ne);else{let _e=K*ne;oe=oe.slice(_e,_e+ne)}return oe}randomSelect(P){let K=0;for(let oe=0;oe1)return new $(P);if(P.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${P.num_return_sequences}.`);return new be(P)}}class be extends xe{async sample(P){const K=(0,he.max)(P.data)[1];return[[BigInt(K),0]]}}class R extends xe{async sample(P){let K=P.dims.at(-1);this.generation_config.top_k>0&&(K=Math.min(this.generation_config.top_k,K));const[ne,oe]=await(0,ae.topk)(P,K),_e=(0,he.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},()=>{const F=this.randomSelect(_e);return[oe.data[F],Math.log(_e[F])]})}}class $ extends xe{async sample(P){let K=P.dims.at(-1);this.generation_config.top_k>0&&(K=Math.min(this.generation_config.top_k,K));const[ne,oe]=await(0,ae.topk)(P,K),_e=(0,he.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},(F,Q)=>[oe.data[Q],Math.log(_e[Q])])}}},"./src/generation/stopping_criteria.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{EosTokenCriteria:()=>be,InterruptableStoppingCriteria:()=>R,MaxLengthCriteria:()=>xe,StoppingCriteria:()=>ae,StoppingCriteriaList:()=>he});var I=N("./src/utils/generic.js");class ae extends I.Callable{_call(V,P){throw Error("StoppingCriteria needs to be subclassed")}}class he extends I.Callable{constructor(){super(),this.criteria=[]}push(V){this.criteria.push(V)}extend(V){V instanceof he?V=V.criteria:V instanceof ae&&(V=[V]),this.criteria.push(...V)}_call(V,P){const K=new Array(V.length).fill(!1);for(const ne of this.criteria){const oe=ne(V,P);for(let _e=0;_eP.length>=this.max_length)}}class be extends ae{constructor(V){super(),Array.isArray(V)||(V=[V]),this.eos_token_id=V}_call(V,P){return V.map(K=>{const ne=K.at(-1);return this.eos_token_id.some(oe=>ne==oe)})}}class R extends ae{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(V,P){return new Array(V.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{BaseStreamer:()=>xe,TextStreamer:()=>R,WhisperTextStreamer:()=>$});var I=N("./src/utils/core.js"),ae=N("./src/tokenizers.js"),he=N("./src/env.js");class xe{put(P){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const be=he.apis.IS_PROCESS_AVAILABLE?V=>process.stdout.write(V):V=>console.log(V);class R extends xe{constructor(P,{skip_prompt:K=!1,callback_function:ne=null,token_callback_function:oe=null,decode_kwargs:_e={},...F}={}){super(),this.tokenizer=P,this.skip_prompt=K,this.callback_function=ne??be,this.token_callback_function=oe,this.decode_kwargs={..._e,...F},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(P){if(P.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 K=P[0];this.token_callback_function?.(K),this.token_cache=(0,I.mergeArrays)(this.token_cache,K);const ne=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let oe;ne.endsWith(` `)?(oe=ne.slice(this.print_len),this.token_cache=[],this.print_len=0):ne.length>0&&(0,ae.is_chinese_char)(ne.charCodeAt(ne.length-1))?(oe=ne.slice(this.print_len),this.print_len+=oe.length):(oe=ne.slice(this.print_len,ne.lastIndexOf(" ")+1),this.print_len+=oe.length),this.on_finalized_text(oe,!1)}end(){let P;this.token_cache.length>0?(P=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):P="",this.next_tokens_are_prompt=!0,this.on_finalized_text(P,!0)}on_finalized_text(P,K){P.length>0&&this.callback_function?.(P),K&&this.callback_function===be&&he.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}}class $ extends R{constructor(P,{skip_prompt:K=!1,callback_function:ne=null,token_callback_function:oe=null,on_chunk_start:_e=null,on_chunk_end:F=null,on_finalize:Q=null,time_precision:se=.02,skip_special_tokens:le=!0,decode_kwargs:ie={}}={}){super(P,{skip_prompt:K,callback_function:ne,token_callback_function:oe,decode_kwargs:{skip_special_tokens:le,...ie}}),this.timestamp_begin=P.timestamp_begin,this.on_chunk_start=_e,this.on_chunk_end=F,this.on_finalize=Q,this.time_precision=se,this.waiting_for_timestamp=!1}put(P){if(P.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const K=P[0];if(K.length===1){const ne=Number(K[0])-this.timestamp_begin;if(ne>=0){const oe=ne*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(oe):this.on_chunk_start?.(oe),this.waiting_for_timestamp=!this.waiting_for_timestamp,P=[[]]}}return super.put(P)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{ASTForAudioClassification:()=>Gs,ASTModel:()=>Nt,ASTPreTrainedModel:()=>fn,AlbertForMaskedLM:()=>Kt,AlbertForQuestionAnswering:()=>ls,AlbertForSequenceClassification:()=>os,AlbertModel:()=>Yn,AlbertPreTrainedModel:()=>Fn,AutoModel:()=>ui,AutoModelForAudioClassification:()=>dd,AutoModelForAudioFrameClassification:()=>Hd,AutoModelForCTC:()=>ud,AutoModelForCausalLM:()=>rd,AutoModelForDepthEstimation:()=>Kd,AutoModelForDocumentQuestionAnswering:()=>pd,AutoModelForImageClassification:()=>id,AutoModelForImageFeatureExtraction:()=>_d,AutoModelForImageMatting:()=>hd,AutoModelForImageSegmentation:()=>ad,AutoModelForImageToImage:()=>fd,AutoModelForMaskGeneration:()=>ld,AutoModelForMaskedLM:()=>nd,AutoModelForNormalEstimation:()=>md,AutoModelForObjectDetection:()=>od,AutoModelForQuestionAnswering:()=>sd,AutoModelForSemanticSegmentation:()=>gu,AutoModelForSeq2SeqLM:()=>fu,AutoModelForSequenceClassification:()=>Zu,AutoModelForSpeechSeq2Seq:()=>ed,AutoModelForTextToSpectrogram:()=>td,AutoModelForTextToWaveform:()=>mu,AutoModelForTokenClassification:()=>Ju,AutoModelForVision2Seq:()=>_u,AutoModelForXVector:()=>cd,AutoModelForZeroShotObjectDetection:()=>qd,BartForConditionalGeneration:()=>m,BartForSequenceClassification:()=>z,BartModel:()=>we,BartPretrainedModel:()=>wn,BaseModelOutput:()=>ct,BeitForImageClassification:()=>Oo,BeitModel:()=>Fo,BeitPreTrainedModel:()=>Ri,BertForMaskedLM:()=>De,BertForQuestionAnswering:()=>Fe,BertForSequenceClassification:()=>at,BertForTokenClassification:()=>Et,BertModel:()=>ot,BertPreTrainedModel:()=>st,BlenderbotForConditionalGeneration:()=>bt,BlenderbotModel:()=>kt,BlenderbotPreTrainedModel:()=>vt,BlenderbotSmallForConditionalGeneration:()=>yr,BlenderbotSmallModel:()=>or,BlenderbotSmallPreTrainedModel:()=>fr,BloomForCausalLM:()=>_o,BloomModel:()=>ku,BloomPreTrainedModel:()=>Xs,CLIPModel:()=>za,CLIPPreTrainedModel:()=>Es,CLIPSegForImageSegmentation:()=>Va,CLIPSegModel:()=>ja,CLIPSegPreTrainedModel:()=>vi,CLIPTextModelWithProjection:()=>kn,CLIPVisionModelWithProjection:()=>Da,CamembertForMaskedLM:()=>B,CamembertForQuestionAnswering:()=>Re,CamembertForSequenceClassification:()=>ce,CamembertForTokenClassification:()=>Te,CamembertModel:()=>et,CamembertPreTrainedModel:()=>Bt,CausalLMOutput:()=>es,CausalLMOutputWithPast:()=>yd,ChineseCLIPModel:()=>Na,ChineseCLIPPreTrainedModel:()=>Ra,ClapAudioModelWithProjection:()=>Nl,ClapModel:()=>ma,ClapPreTrainedModel:()=>ai,ClapTextModelWithProjection:()=>Rl,CodeGenForCausalLM:()=>Ja,CodeGenModel:()=>xn,CodeGenPreTrainedModel:()=>Hs,CohereForCausalLM:()=>no,CohereModel:()=>ro,CoherePreTrainedModel:()=>Ci,ConvBertForMaskedLM:()=>M,ConvBertForQuestionAnswering:()=>te,ConvBertForSequenceClassification:()=>W,ConvBertForTokenClassification:()=>E,ConvBertModel:()=>St,ConvBertPreTrainedModel:()=>Tt,ConvNextForImageClassification:()=>il,ConvNextModel:()=>sl,ConvNextPreTrainedModel:()=>ea,ConvNextV2ForImageClassification:()=>ol,ConvNextV2Model:()=>al,ConvNextV2PreTrainedModel:()=>ta,DPTForDepthEstimation:()=>Yo,DPTModel:()=>Qo,DPTPreTrainedModel:()=>Yi,DebertaForMaskedLM:()=>ft,DebertaForQuestionAnswering:()=>gt,DebertaForSequenceClassification:()=>lt,DebertaForTokenClassification:()=>Ct,DebertaModel:()=>tt,DebertaPreTrainedModel:()=>ke,DebertaV2ForMaskedLM:()=>Ot,DebertaV2ForQuestionAnswering:()=>Ut,DebertaV2ForSequenceClassification:()=>Wt,DebertaV2ForTokenClassification:()=>zt,DebertaV2Model:()=>Rt,DebertaV2PreTrainedModel:()=>ze,DeiTForImageClassification:()=>Wo,DeiTModel:()=>Uo,DeiTPreTrainedModel:()=>Ui,DepthAnythingForDepthEstimation:()=>Zo,DepthAnythingPreTrainedModel:()=>Zi,DetrForObjectDetection:()=>Do,DetrForSegmentation:()=>Cs,DetrModel:()=>zo,DetrObjectDetectionOutput:()=>Ni,DetrPreTrainedModel:()=>Ys,DetrSegmentationOutput:()=>Zs,Dinov2ForImageClassification:()=>ll,Dinov2Model:()=>Fu,Dinov2PreTrainedModel:()=>ra,DistilBertForMaskedLM:()=>yt,DistilBertForQuestionAnswering:()=>Qe,DistilBertForSequenceClassification:()=>rr,DistilBertForTokenClassification:()=>wr,DistilBertModel:()=>ur,DistilBertPreTrainedModel:()=>Ht,DonutSwinModel:()=>nl,DonutSwinPreTrainedModel:()=>rl,EfficientNetForImageClassification:()=>Gl,EfficientNetModel:()=>Wl,EfficientNetPreTrainedModel:()=>wa,ElectraForMaskedLM:()=>He,ElectraForQuestionAnswering:()=>pt,ElectraForSequenceClassification:()=>Mt,ElectraForTokenClassification:()=>nt,ElectraModel:()=>Je,ElectraPreTrainedModel:()=>pe,EsmForMaskedLM:()=>Xn,EsmForSequenceClassification:()=>is,EsmForTokenClassification:()=>Hr,EsmModel:()=>Zr,EsmPreTrainedModel:()=>Ft,FalconForCausalLM:()=>Ll,FalconModel:()=>Bl,FalconPreTrainedModel:()=>Dl,FastViTForImageClassification:()=>Pu,FastViTModel:()=>xo,FastViTPreTrainedModel:()=>zi,Florence2ForConditionalGeneration:()=>bi,Florence2PreTrainedModel:()=>Oa,GLPNForDepthEstimation:()=>tl,GLPNModel:()=>Tn,GLPNPreTrainedModel:()=>Ji,GPT2LMHeadModel:()=>Wa,GPT2Model:()=>Ua,GPT2PreTrainedModel:()=>xi,GPTBigCodeForCausalLM:()=>qs,GPTBigCodeModel:()=>Za,GPTBigCodePreTrainedModel:()=>Mn,GPTJForCausalLM:()=>Cu,GPTJModel:()=>Ya,GPTJPreTrainedModel:()=>$i,GPTNeoForCausalLM:()=>Ka,GPTNeoModel:()=>Ha,GPTNeoPreTrainedModel:()=>Ti,GPTNeoXForCausalLM:()=>Qa,GPTNeoXModel:()=>Xa,GPTNeoXPreTrainedModel:()=>Si,Gemma2ForCausalLM:()=>oo,Gemma2Model:()=>ao,Gemma2PreTrainedModel:()=>vn,GemmaForCausalLM:()=>io,GemmaModel:()=>so,GemmaPreTrainedModel:()=>ki,HieraForImageClassification:()=>qo,HieraModel:()=>Go,HieraPreTrainedModel:()=>Wi,HubertForCTC:()=>$l,HubertForSequenceClassification:()=>zu,HubertModel:()=>Sl,HubertPreTrainedModel:()=>Wd,ImageMattingOutput:()=>wu,JAISLMHeadModel:()=>qa,JAISModel:()=>Ga,JAISPreTrainedModel:()=>bn,LlamaForCausalLM:()=>to,LlamaModel:()=>eo,LlamaPreTrainedModel:()=>Ei,LlavaForConditionalGeneration:()=>cs,LlavaPreTrainedModel:()=>Fa,LongT5ForConditionalGeneration:()=>Ss,LongT5Model:()=>Ts,LongT5PreTrainedModel:()=>us,M2M100ForConditionalGeneration:()=>ia,M2M100Model:()=>an,M2M100PreTrainedModel:()=>Dn,MBartForCausalLM:()=>xt,MBartForConditionalGeneration:()=>ve,MBartForSequenceClassification:()=>Be,MBartModel:()=>J,MBartPreTrainedModel:()=>Y,MPNetForMaskedLM:()=>ws,MPNetForQuestionAnswering:()=>Ms,MPNetForSequenceClassification:()=>ys,MPNetForTokenClassification:()=>bs,MPNetModel:()=>Us,MPNetPreTrainedModel:()=>In,MT5ForConditionalGeneration:()=>Nr,MT5Model:()=>$s,MT5PreTrainedModel:()=>ds,MarianMTModel:()=>sa,MarianModel:()=>qn,MarianPreTrainedModel:()=>zn,MaskedLMOutput:()=>rn,MistralForCausalLM:()=>Fl,MistralModel:()=>Il,MistralPreTrainedModel:()=>ha,MobileBertForMaskedLM:()=>Qn,MobileBertForQuestionAnswering:()=>Vn,MobileBertForSequenceClassification:()=>Lr,MobileBertModel:()=>Xr,MobileBertPreTrainedModel:()=>pn,MobileNetV1ForImageClassification:()=>ql,MobileNetV1Model:()=>ba,MobileNetV1PreTrainedModel:()=>fs,MobileNetV2ForImageClassification:()=>Kl,MobileNetV2Model:()=>Hl,MobileNetV2PreTrainedModel:()=>Ma,MobileNetV3ForImageClassification:()=>Ql,MobileNetV3Model:()=>Xl,MobileNetV3PreTrainedModel:()=>li,MobileNetV4ForImageClassification:()=>Yl,MobileNetV4Model:()=>Nu,MobileNetV4PreTrainedModel:()=>va,MobileViTForImageClassification:()=>$o,MobileViTModel:()=>Au,MobileViTPreTrainedModel:()=>Di,MobileViTV2ForImageClassification:()=>Co,MobileViTV2Model:()=>Eo,MobileViTV2PreTrainedModel:()=>br,ModelOutput:()=>Ue,Moondream1ForConditionalGeneration:()=>sr,MptForCausalLM:()=>wo,MptModel:()=>go,MptPreTrainedModel:()=>Oi,MusicgenForCausalLM:()=>Gd,MusicgenForConditionalGeneration:()=>Fs,MusicgenModel:()=>Ru,MusicgenPreTrainedModel:()=>ya,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>H,OPTForCausalLM:()=>bo,OPTModel:()=>yo,OPTPreTrainedModel:()=>hs,OpenELMForCausalLM:()=>uo,OpenELMModel:()=>lo,OpenELMPreTrainedModel:()=>Pi,OwlViTForObjectDetection:()=>Po,OwlViTModel:()=>ko,OwlViTPreTrainedModel:()=>Bi,Owlv2ForObjectDetection:()=>Io,Owlv2Model:()=>Ao,Owlv2PreTrainedModel:()=>Li,Phi3ForCausalLM:()=>mo,Phi3Model:()=>fo,Phi3PreTrainedModel:()=>Ks,PhiForCausalLM:()=>Fi,PhiModel:()=>ho,PhiPreTrainedModel:()=>Ii,PreTrainedModel:()=>X,PretrainedMixin:()=>Or,PyAnnoteForAudioFrameClassification:()=>_l,PyAnnoteModel:()=>oa,PyAnnotePreTrainedModel:()=>ks,QuestionAnsweringModelOutput:()=>on,Qwen2ForCausalLM:()=>po,Qwen2Model:()=>co,Qwen2PreTrainedModel:()=>Ai,RTDetrForObjectDetection:()=>Lo,RTDetrModel:()=>Bo,RTDetrObjectDetectionOutput:()=>Ro,RTDetrPreTrainedModel:()=>ji,ResNetForImageClassification:()=>qi,ResNetModel:()=>Ho,ResNetPreTrainedModel:()=>Gi,RoFormerForMaskedLM:()=>Ve,RoFormerForQuestionAnswering:()=>ht,RoFormerForSequenceClassification:()=>Ge,RoFormerForTokenClassification:()=>ut,RoFormerModel:()=>je,RoFormerPreTrainedModel:()=>qe,RobertaForMaskedLM:()=>yn,RobertaForQuestionAnswering:()=>On,RobertaForSequenceClassification:()=>Rr,RobertaForTokenClassification:()=>Ie,RobertaModel:()=>Cr,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Gn,SamModel:()=>Ou,SamPreTrainedModel:()=>pl,SapiensForDepthEstimation:()=>Iu,SapiensForNormalEstimation:()=>el,SapiensForSemanticSegmentation:()=>Jo,SapiensPreTrainedModel:()=>Js,SegformerForImageClassification:()=>Bu,SegformerForSemanticSegmentation:()=>Vl,SegformerModel:()=>Du,SegformerPreTrainedModel:()=>oi,Seq2SeqLMOutput:()=>gd,SequenceClassifierOutput:()=>lr,SiglipModel:()=>ps,SiglipPreTrainedModel:()=>Mi,SiglipTextModel:()=>Ba,SiglipVisionModel:()=>La,SpeechT5ForSpeechToText:()=>da,SpeechT5ForTextToSpeech:()=>ca,SpeechT5HifiGan:()=>Pl,SpeechT5Model:()=>ua,SpeechT5PreTrainedModel:()=>ii,SqueezeBertForMaskedLM:()=>as,SqueezeBertForQuestionAnswering:()=>Wn,SqueezeBertForSequenceClassification:()=>Cn,SqueezeBertModel:()=>Ws,SqueezeBertPreTrainedModel:()=>Un,StableLmForCausalLM:()=>Lu,StableLmModel:()=>Ul,StableLmPreTrainedModel:()=>ga,Starcoder2ForCausalLM:()=>fa,Starcoder2Model:()=>zl,Starcoder2PreTrainedModel:()=>Ol,Swin2SRForImageSuperResolution:()=>Xo,Swin2SRModel:()=>Ko,Swin2SRPreTrainedModel:()=>Qi,SwinForImageClassification:()=>Xi,SwinModel:()=>Ki,SwinPreTrainedModel:()=>Hi,T5ForConditionalGeneration:()=>xs,T5Model:()=>vs,T5PreTrainedModel:()=>Zn,TableTransformerForObjectDetection:()=>jo,TableTransformerModel:()=>No,TableTransformerObjectDetectionOutput:()=>Vo,TableTransformerPreTrainedModel:()=>Vi,TokenClassifierOutput:()=>en,TrOCRForCausalLM:()=>pa,TrOCRPreTrainedModel:()=>Al,UniSpeechForCTC:()=>wl,UniSpeechForSequenceClassification:()=>yl,UniSpeechModel:()=>ti,UniSpeechPreTrainedModel:()=>Ps,UniSpeechSatForAudioFrameClassification:()=>Ml,UniSpeechSatForCTC:()=>la,UniSpeechSatForSequenceClassification:()=>As,UniSpeechSatModel:()=>bl,UniSpeechSatPreTrainedModel:()=>ri,ViTForImageClassification:()=>vo,ViTModel:()=>Mo,ViTPreTrainedModel:()=>Qs,VisionEncoderDecoderModel:()=>yi,VitMatteForImageMatting:()=>So,VitMattePreTrainedModel:()=>To,VitsModel:()=>_a,VitsModelOutput:()=>yu,VitsPreTrainedModel:()=>jl,Wav2Vec2BertForCTC:()=>xl,Wav2Vec2BertForSequenceClassification:()=>Tl,Wav2Vec2BertModel:()=>vl,Wav2Vec2BertPreTrainedModel:()=>Is,Wav2Vec2ForAudioFrameClassification:()=>ml,Wav2Vec2ForCTC:()=>hl,Wav2Vec2ForSequenceClassification:()=>fl,Wav2Vec2Model:()=>aa,Wav2Vec2PreTrainedModel:()=>Pn,WavLMForAudioFrameClassification:()=>si,WavLMForCTC:()=>Cl,WavLMForSequenceClassification:()=>kl,WavLMForXVector:()=>ni,WavLMModel:()=>El,WavLMPreTrainedModel:()=>Jn,WeSpeakerResNetModel:()=>gl,WeSpeakerResNetPreTrainedModel:()=>ei,WhisperForConditionalGeneration:()=>wi,WhisperModel:()=>Vt,WhisperPreTrainedModel:()=>Ze,XLMForQuestionAnswering:()=>sn,XLMForSequenceClassification:()=>Xt,XLMForTokenClassification:()=>hn,XLMModel:()=>Jr,XLMPreTrainedModel:()=>xr,XLMRobertaForMaskedLM:()=>Pt,XLMRobertaForQuestionAnswering:()=>jr,XLMRobertaForSequenceClassification:()=>Sr,XLMRobertaForTokenClassification:()=>Fr,XLMRobertaModel:()=>Tr,XLMRobertaPreTrainedModel:()=>Er,XLMWithLMHeadModel:()=>dn,XVectorOutput:()=>wd,YolosForObjectDetection:()=>dl,YolosModel:()=>ul,YolosObjectDetectionOutput:()=>cl,YolosPreTrainedModel:()=>na});var I=N("./src/configs.js"),ae=N("./src/backends/onnx.js"),he=N("./src/utils/dtypes.js"),xe=N("./src/utils/generic.js"),be=N("./src/utils/core.js"),R=N("./src/utils/hub.js"),$=N("./src/generation/logits_process.js"),V=N("./src/generation/configuration_utils.js"),P=N("./src/utils/tensor.js"),K=N("./src/utils/maths.js"),ne=N("./src/generation/stopping_criteria.js"),oe=N("./src/generation/logits_sampler.js"),_e=N("./src/env.js"),F=N("./src/models/whisper/generation_whisper.js"),Q=N("./src/models/whisper/common_whisper.js");const se={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},le=new Map,ie=new Map,j=new Map;async function A(_,h,D){let re=D.device;re&&typeof re!="string"&&(re.hasOwnProperty(h)?re=re[h]:(console.warn(`device not specified for "${h}". Using the default device.`),re=null));const Oe=re??(_e.apis.IS_NODE_ENV?"cpu":"wasm"),Ye=(0,ae.deviceToExecutionProviders)(Oe);let wt=D.dtype;typeof wt!="string"&&(wt&&wt.hasOwnProperty(h)?wt=wt[h]:(wt=he.DEFAULT_DEVICE_DTYPE_MAPPING[Oe]??he.DATA_TYPES.fp32,console.warn(`dtype not specified for "${h}". Using the default dtype (${wt}) for this device (${Oe}).`)));const At=wt;if(he.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(At)){if(At===he.DATA_TYPES.fp16&&Oe==="webgpu"&&!await(0,he.isWebGpuFp16Supported)())throw new Error(`The device (${Oe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${At}. Should be one of: ${Object.keys(he.DATA_TYPES).join(", ")}`);const Zt=he.DEFAULT_DTYPE_SUFFIX_MAPPING[At],mr=`${D.subfolder??""}/${h}${Zt}.onnx`,kr={...D.session_options};kr.executionProviders??=Ye;const Ir=(0,R.getModelFile)(_,mr,!0,D);let pr=[];if(D.use_external_data_format&&(D.use_external_data_format===!0||typeof D.use_external_data_format=="object"&&D.use_external_data_format.hasOwnProperty(h)&&D.use_external_data_format[h]===!0)){if(_e.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const Dr=`${h}${Zt}.onnx_data`,ir=`${D.subfolder??""}/${Dr}`;pr.push(new Promise(async(Mr,qr)=>{const tn=await(0,R.getModelFile)(_,ir,!0,D);Mr({path:Dr,data:tn})}))}else kr.externalData!==void 0&&(pr=kr.externalData.map(async Dr=>{if(typeof Dr.data=="string"){const ir=await(0,R.getModelFile)(_,Dr.data,!0,D);return{...Dr,data:ir}}return Dr}));if(pr.length>0&&(kr.externalData=await Promise.all(pr)),Oe==="webgpu"){const Dr=(0,I.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(Dr).length>0&&!(0,ae.isONNXProxy)()){const ir={};for(const Mr in Dr)ir[Mr]="gpu-buffer";kr.preferredOutputLocation=ir}}return{buffer:await Ir,session_options:kr}}async function L(_,h,D){return Object.fromEntries(await Promise.all(Object.keys(h).map(async re=>{const{buffer:Oe,session_options:Ye}=await A(_,h[re],D),wt=await(0,ae.createInferenceSession)(Oe,Ye);return[re,wt]})))}function C(_,h){const D=Object.create(null),re=[];for(const wt of _.inputNames){const At=h[wt];if(!(At instanceof P.Tensor)){re.push(wt);continue}D[wt]=(0,ae.isONNXProxy)()?At.clone():At}if(re.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${re.join(", ")}.`);const Oe=Object.keys(h).length,Ye=_.inputNames.length;if(Oe>Ye){let wt=Object.keys(h).filter(At=>!_.inputNames.includes(At));console.warn(`WARNING: Too many inputs were provided (${Oe} > ${Ye}). The following inputs will be ignored: "${wt.join(", ")}".`)}return D}async function me(_,h){const D=C(_,h);try{const re=Object.fromEntries(Object.entries(D).map(([Ye,wt])=>[Ye,wt.ort_tensor]));let Oe=await _.run(re);return Oe=ye(Oe),Oe}catch(re){throw console.error(`An error occurred during model execution: "${re}".`),console.error("Inputs given to model:",D),re}}function ye(_){for(let h in _)(0,ae.isONNXTensor)(_[h])?_[h]=new P.Tensor(_[h]):typeof _[h]=="object"&&ye(_[h]);return _}function Se(_){if(_ instanceof P.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(h=>h.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 P.Tensor("int64",BigInt64Array.from(_.flat().map(h=>BigInt(h))),[_.length,_[0].length])}else return new P.Tensor("int64",BigInt64Array.from(_.map(h=>BigInt(h))),[1,_.length])}function Pe(_){return new P.Tensor("bool",[_],[1])}async function Ce(_,h){let{encoder_outputs:D,input_ids:re,decoder_input_ids:Oe,...Ye}=h;if(!D){const At=(0,be.pick)(h,_.sessions.model.inputNames);D=(await rt(_,At)).last_hidden_state}return Ye.input_ids=Oe,Ye.encoder_hidden_states=D,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Ye.encoder_attention_mask=h.attention_mask),await Xe(_,Ye,!0)}async function rt(_,h){const D=_.sessions.model,re=(0,be.pick)(h,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!re.inputs_embeds){if(!h.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");re.inputs_embeds=await _.encode_text({input_ids:h.input_ids})}return D.inputNames.includes("token_type_ids")&&!re.token_type_ids&&(re.token_type_ids=new P.Tensor("int64",new BigInt64Array(re.input_ids.data.length),re.input_ids.dims)),await me(D,re)}async function Xe(_,h,D=!1){const re=_.sessions[D?"decoder_model_merged":"model"],{past_key_values:Oe,...Ye}=h;re.inputNames.includes("use_cache_branch")&&(Ye.use_cache_branch=Pe(!!Oe)),re.inputNames.includes("position_ids")&&Ye.attention_mask&&!Ye.position_ids&&(Ye.position_ids=ge(Ye,Oe)),_.addPastKeyValues(Ye,Oe);const wt=(0,be.pick)(Ye,re.inputNames);return await me(re,wt)}async function dt(_,{input_ids:h=null,attention_mask:D=null,pixel_values:re=null,position_ids:Oe=null,inputs_embeds:Ye=null,past_key_values:wt=null,generation_config:At=null,logits_processor:Zt=null,...mr}){if(!Ye){if(Ye=await _.encode_text({input_ids:h}),re&&h.dims[1]!==1){const Ir=await _.encode_image({pixel_values:re});({inputs_embeds:Ye,attention_mask:D}=_._merge_input_ids_with_image_features({image_features:Ir,inputs_embeds:Ye,input_ids:h,attention_mask:D}))}else if(wt&&re&&h.dims[1]===1){const Ir=h.dims[1],pr=Object.values(wt)[0].dims.at(-2);D=(0,P.cat)([(0,P.ones)([h.dims[0],pr]),D.slice(null,[D.dims[1]-Ir,D.dims[1]])],1)}}return await Xe(_,{inputs_embeds:Ye,past_key_values:wt,attention_mask:D,position_ids:Oe,generation_config:At,logits_processor:Zt},!0)}function ge(_,h=null){const{input_ids:D,inputs_embeds:re,attention_mask:Oe}=_,[Ye,wt]=Oe.dims,At=new BigInt64Array(Oe.data.length);for(let mr=0;mrYe.dims[1])){if(OeAt==_.config.image_token_index)){const At=_.config.num_image_tokens;if(!At)throw new Error("`num_image_tokens` is missing in the model configuration.");const Zt=Ye.dims[1]-(Oe-At);D.input_ids=Ye.slice(null,[-Zt,null]),D.attention_mask=(0,P.ones)([1,Oe+Zt])}}}return D}function de(_,h,D,re){return D.past_key_values&&(h=h.map(Oe=>[Oe.at(-1)])),{...D,decoder_input_ids:Se(h)}}function $e(_,...h){return _.config.is_encoder_decoder?de(_,...h):U(_,...h)}class X extends xe.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(h,D){super(),this.config=h,this.sessions=D;const re=j.get(this.constructor),Oe=le.get(re);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Oe){case se.DecoderOnly:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=U;break;case se.Seq2Seq:case se.Vision2Seq:case se.Musicgen:this.can_generate=!0,this._forward=Ce,this._prepare_inputs_for_generation=de;break;case se.EncoderDecoder:this._forward=Ce;break;case se.ImageTextToText:this.can_generate=!0,this._forward=dt,this._prepare_inputs_for_generation=$e;break;default:this._forward=rt;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const h=[];for(const D of Object.values(this.sessions))D?.handler?.dispose&&h.push(D.handler.dispose());return await Promise.all(h)}static async from_pretrained(h,{progress_callback:D=null,config:re=null,cache_dir:Oe=null,local_files_only:Ye=!1,revision:wt="main",model_file_name:At=null,subfolder:Zt="onnx",device:mr=null,dtype:kr=null,use_external_data_format:Ir=null,session_options:pr={}}={}){let er={progress_callback:D,config:re,cache_dir:Oe,local_files_only:Ye,revision:wt,model_file_name:At,subfolder:Zt,device:mr,dtype:kr,use_external_data_format:Ir,session_options:pr};const Dr=j.get(this),ir=le.get(Dr);re=er.config=await I.AutoConfig.from_pretrained(h,er);let Mr;if(ir===se.DecoderOnly)Mr=await Promise.all([L(h,{model:er.model_file_name??"model"},er),(0,R.getModelJSON)(h,"generation_config.json",!1,er)]);else if(ir===se.Seq2Seq||ir===se.Vision2Seq)Mr=await Promise.all([L(h,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},er),(0,R.getModelJSON)(h,"generation_config.json",!1,er)]);else if(ir===se.MaskGeneration)Mr=await Promise.all([L(h,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},er)]);else if(ir===se.EncoderDecoder)Mr=await Promise.all([L(h,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},er)]);else if(ir===se.ImageTextToText){const qr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};re.is_encoder_decoder&&(qr.model="encoder_model"),Mr=await Promise.all([L(h,qr,er),(0,R.getModelJSON)(h,"generation_config.json",!1,er)])}else ir===se.Musicgen?Mr=await Promise.all([L(h,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},er),(0,R.getModelJSON)(h,"generation_config.json",!1,er)]):(ir!==se.EncoderOnly&&console.warn(`Model type for '${Dr??re?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Mr=await Promise.all([L(h,{model:er.model_file_name??"model"},er)]));return new this(re,...Mr)}async _call(h){return await this.forward(h)}async forward(h){return await this._forward(this,h)}_get_logits_warper(h){const D=new $.LogitsProcessorList;return h.temperature!==null&&h.temperature!==1&&D.push(new $.TemperatureLogitsWarper(h.temperature)),h.top_k!==null&&h.top_k!==0&&D.push(new $.TopKLogitsWarper(h.top_k)),h.top_p!==null&&h.top_p<1&&D.push(new $.TopPLogitsWarper(h.top_p)),D}_get_logits_processor(h,D,re=null){const Oe=new $.LogitsProcessorList;if(h.repetition_penalty!==null&&h.repetition_penalty!==1&&Oe.push(new $.RepetitionPenaltyLogitsProcessor(h.repetition_penalty)),h.no_repeat_ngram_size!==null&&h.no_repeat_ngram_size>0&&Oe.push(new $.NoRepeatNGramLogitsProcessor(h.no_repeat_ngram_size)),h.bad_words_ids!==null&&Oe.push(new $.NoBadWordsLogitsProcessor(h.bad_words_ids,h.eos_token_id)),h.min_length!==null&&h.eos_token_id!==null&&h.min_length>0&&Oe.push(new $.MinLengthLogitsProcessor(h.min_length,h.eos_token_id)),h.min_new_tokens!==null&&h.eos_token_id!==null&&h.min_new_tokens>0&&Oe.push(new $.MinNewTokensLengthLogitsProcessor(D,h.min_new_tokens,h.eos_token_id)),h.forced_bos_token_id!==null&&Oe.push(new $.ForcedBOSTokenLogitsProcessor(h.forced_bos_token_id)),h.forced_eos_token_id!==null&&Oe.push(new $.ForcedEOSTokenLogitsProcessor(h.max_length,h.forced_eos_token_id)),h.begin_suppress_tokens!==null){const Ye=D>1||h.forced_bos_token_id===null?D:D+1;Oe.push(new $.SuppressTokensAtBeginLogitsProcessor(h.begin_suppress_tokens,Ye))}return h.guidance_scale!==null&&h.guidance_scale>1&&Oe.push(new $.ClassifierFreeGuidanceLogitsProcessor(h.guidance_scale)),re!==null&&Oe.extend(re),Oe}_prepare_generation_config(h,D,re=V.GenerationConfig){const Oe={...this.config};for(const wt of["decoder","generator","text_config"])wt in Oe&&Object.assign(Oe,Oe[wt]);const Ye=new re(Oe);return"generation_config"in this&&Object.assign(Ye,this.generation_config),h&&Object.assign(Ye,h),D&&Object.assign(Ye,(0,be.pick)(D,Object.getOwnPropertyNames(Ye))),Ye}_get_stopping_criteria(h,D=null){const re=new ne.StoppingCriteriaList;return h.max_length!==null&&re.push(new ne.MaxLengthCriteria(h.max_length,this.config.max_position_embeddings??null)),h.eos_token_id!==null&&re.push(new ne.EosTokenCriteria(h.eos_token_id)),D&&re.extend(D),re}_validate_model_class(){if(!this.can_generate){const h=[Ta,Sa,xa,Zl],D=j.get(this.constructor),re=new Set,Oe=this.config.model_type;for(const wt of h){const At=wt.get(Oe);At&&re.add(At[0])}let Ye=`The current model class (${D}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw re.size>0&&(Ye+=` Please use the following class instead: ${[...re].join(", ")}`),Error(Ye)}}prepare_inputs_for_generation(...h){return this._prepare_inputs_for_generation(this,...h)}_update_model_kwargs_for_generation({generated_input_ids:h,outputs:D,model_inputs:re,is_encoder_decoder:Oe}){return re.past_key_values=this.getPastKeyValues(D,re.past_key_values),re.input_ids=new P.Tensor("int64",h.flat(),[h.length,1]),Oe||(re.attention_mask=(0,P.cat)([re.attention_mask,(0,P.ones)([re.attention_mask.dims[0],1])],1)),re.position_ids=null,re}_prepare_model_inputs({inputs:h,bos_token_id:D,model_kwargs:re}){const Oe=(0,be.pick)(re,this.forward_params),Ye=this.main_input_name;if(Ye in Oe){if(h)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Oe[Ye]=h;return{inputs_tensor:Oe[Ye],model_inputs:Oe,model_input_name:Ye}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:h,model_inputs:D,model_input_name:re,generation_config:Oe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!D.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:wt,pixel_values:At,attention_mask:Zt,...mr}=D,kr=await this._prepare_inputs_embeds(D);D={...mr,...(0,be.pick)(kr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ye}=await rt(this,D);if(Oe.guidance_scale!==null&&Oe.guidance_scale>1)Ye=(0,P.cat)([Ye,(0,P.full_like)(Ye,0)],0),"attention_mask"in D&&(D.attention_mask=(0,P.cat)([D.attention_mask,(0,P.zeros_like)(D.attention_mask)],0));else if(D.decoder_input_ids){const wt=Se(D.decoder_input_ids).dims[0];if(wt!==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 (${wt}).`);Ye=(0,P.cat)(Array.from({length:wt},()=>Ye),0)}}return D.encoder_outputs=Ye,D}_prepare_decoder_input_ids_for_generation({batch_size:h,model_input_name:D,model_kwargs:re,decoder_start_token_id:Oe,bos_token_id:Ye,generation_config:wt}){let{decoder_input_ids:At,...Zt}=re;if(At)Array.isArray(At[0])||(At=Array.from({length:h},()=>At));else if(Oe??=Ye,this.config.model_type==="musicgen")At=Array.from({length:h*this.config.decoder.num_codebooks},()=>[Oe]);else if(Array.isArray(Oe)){if(Oe.length!==h)throw new Error(`\`decoder_start_token_id\` expcted to have length ${h} but got ${Oe.length}`);At=Oe}else At=Array.from({length:h},()=>[Oe]);return At=Se(At),re.decoder_attention_mask=(0,P.ones_like)(At),{input_ids:At,model_inputs:Zt}}async generate({inputs:h=null,generation_config:D=null,logits_processor:re=null,stopping_criteria:Oe=null,streamer:Ye=null,...wt}){this._validate_model_class(),D=this._prepare_generation_config(D,wt);let{inputs_tensor:At,model_inputs:Zt,model_input_name:mr}=this._prepare_model_inputs({inputs:h,model_kwargs:wt});const kr=this.config.is_encoder_decoder;kr&&("encoder_outputs"in Zt||(Zt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:At,model_inputs:Zt,model_input_name:mr,generation_config:D})));let Ir;kr?{input_ids:Ir,model_inputs:Zt}=this._prepare_decoder_input_ids_for_generation({batch_size:Zt[mr].dims.at(0),model_input_name:mr,model_kwargs:Zt,decoder_start_token_id:D.decoder_start_token_id,bos_token_id:D.bos_token_id,generation_config:D}):Ir=Zt[mr];let pr=Ir.dims.at(-1);D.max_new_tokens!==null&&(D.max_length=pr+D.max_new_tokens);const er=this._get_logits_processor(D,pr,re),Dr=this._get_stopping_criteria(D,Oe),ir=Zt[mr].dims.at(0),Mr=oe.LogitsSampler.getSampler(D),qr=new Array(ir).fill(0),tn=Ir.tolist();Ye&&Ye.put(tn);let Hn=null,Sn={};for(;;){Zt=this.prepare_inputs_for_generation(tn,Zt,D);const Qr=await this.forward(Zt);if(D.output_attentions&&D.return_dict_in_generate){const Bn=this.getAttentions(Qr);for(const ms in Bn)ms in Sn||(Sn[ms]=[]),Sn[ms].push(Bn[ms])}const _n=Qr.logits.slice(null,-1,null),di=er(tn,_n),Os=[];for(let Bn=0;BnBn)){D.return_dict_in_generate&&(Hn=this.getPastKeyValues(Qr,Zt.past_key_values,!1));break}Zt=this._update_model_kwargs_for_generation({generated_input_ids:Os,outputs:Qr,model_inputs:Zt,is_encoder_decoder:kr})}Ye&&Ye.end();const mn=new P.Tensor("int64",tn.flat(),[tn.length,tn[0].length]);return D.return_dict_in_generate?{sequences:mn,past_key_values:Hn,...Sn}:mn}getPastKeyValues(h,D,re=!0){const Oe=Object.create(null);for(const Ye in h)if(Ye.startsWith("present")){const wt=Ye.replace("present","past_key_values");if(D&&Ye.includes("encoder"))Oe[wt]=D[wt];else{if(re&&D){const At=D[wt];At.location==="gpu-buffer"&&At.dispose()}Oe[wt]=h[Ye]}}return Oe}getAttentions(h){const D={};for(const re of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Oe in h)Oe.startsWith(re)&&(re in D||(D[re]=[]),D[re].push(h[Oe]));return D}addPastKeyValues(h,D){if(D)Object.assign(h,D);else{const re=this.custom_config.kv_cache_dtype??"float32",Oe=re==="float16"?new Uint16Array:[],Ye=(0,I.getKeyValueShapes)(this.config);for(const wt in Ye)h[wt]=new P.Tensor(re,Oe,Ye[wt])}}async encode_image({pixel_values:h}){const D=(await me(this.sessions.vision_encoder,{pixel_values:h})).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 (${D.dims[1]}).`),this.config.num_image_tokens=D.dims[1]),D}async encode_text({input_ids:h}){return(await me(this.sessions.embed_tokens,{input_ids:h})).inputs_embeds}}class Ue{}class ct extends Ue{constructor({last_hidden_state:h,hidden_states:D=null,attentions:re=null}){super(),this.last_hidden_state=h,this.hidden_states=D,this.attentions=re}}class st extends X{}class ot extends st{}class De extends st{async _call(h){return new rn(await super._call(h))}}class at extends st{async _call(h){return new lr(await super._call(h))}}class Et extends st{async _call(h){return new en(await super._call(h))}}class Fe extends st{async _call(h){return new on(await super._call(h))}}class H extends X{}class Ee extends H{}class qe extends X{}class je extends qe{}class Ve extends qe{async _call(h){return new rn(await super._call(h))}}class Ge extends qe{async _call(h){return new lr(await super._call(h))}}class ut extends qe{async _call(h){return new en(await super._call(h))}}class ht extends qe{async _call(h){return new on(await super._call(h))}}class Tt extends X{}class St extends Tt{}class M extends Tt{async _call(h){return new rn(await super._call(h))}}class W extends Tt{async _call(h){return new lr(await super._call(h))}}class E extends Tt{async _call(h){return new en(await super._call(h))}}class te extends Tt{async _call(h){return new on(await super._call(h))}}class pe extends X{}class Je extends pe{}class He extends pe{async _call(h){return new rn(await super._call(h))}}class Mt extends pe{async _call(h){return new lr(await super._call(h))}}class nt extends pe{async _call(h){return new en(await super._call(h))}}class pt extends pe{async _call(h){return new on(await super._call(h))}}class Bt extends X{}class et extends Bt{}class B extends Bt{async _call(h){return new rn(await super._call(h))}}class ce extends Bt{async _call(h){return new lr(await super._call(h))}}class Te extends Bt{async _call(h){return new en(await super._call(h))}}class Re extends Bt{async _call(h){return new on(await super._call(h))}}class ke extends X{}class tt extends ke{}class ft extends ke{async _call(h){return new rn(await super._call(h))}}class lt extends ke{async _call(h){return new lr(await super._call(h))}}class Ct extends ke{async _call(h){return new en(await super._call(h))}}class gt extends ke{async _call(h){return new on(await super._call(h))}}class ze extends X{}class Rt extends ze{}class Ot extends ze{async _call(h){return new rn(await super._call(h))}}class Wt extends ze{async _call(h){return new lr(await super._call(h))}}class zt extends ze{async _call(h){return new en(await super._call(h))}}class Ut extends ze{async _call(h){return new on(await super._call(h))}}class Ht extends X{}class ur extends Ht{}class rr extends Ht{async _call(h){return new lr(await super._call(h))}}class wr extends Ht{async _call(h){return new en(await super._call(h))}}class Qe extends Ht{async _call(h){return new on(await super._call(h))}}class yt extends Ht{async _call(h){return new rn(await super._call(h))}}class Ft extends X{}class Zr extends Ft{}class Xn extends Ft{async _call(h){return new rn(await super._call(h))}}class is extends Ft{async _call(h){return new lr(await super._call(h))}}class Hr extends Ft{async _call(h){return new en(await super._call(h))}}class pn extends X{}class Xr extends pn{}class Qn extends pn{async _call(h){return new rn(await super._call(h))}}class Lr extends pn{async _call(h){return new lr(await super._call(h))}}class Vn extends pn{async _call(h){return new on(await super._call(h))}}class In extends X{}class Us extends In{}class ws extends In{async _call(h){return new rn(await super._call(h))}}class ys extends In{async _call(h){return new lr(await super._call(h))}}class bs extends In{async _call(h){return new en(await super._call(h))}}class Ms extends In{async _call(h){return new on(await super._call(h))}}class Un extends X{}class Ws extends Un{}class as extends Un{async _call(h){return new rn(await super._call(h))}}class Cn extends Un{async _call(h){return new lr(await super._call(h))}}class Wn extends Un{async _call(h){return new on(await super._call(h))}}class Fn extends X{}class Yn extends Fn{}class os extends Fn{async _call(h){return new lr(await super._call(h))}}class ls extends Fn{async _call(h){return new on(await super._call(h))}}class Kt extends Fn{async _call(h){return new rn(await super._call(h))}}class Zn extends X{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(h,D,re){super(h,D),this.generation_config=re}}class vs extends Zn{}class xs extends Zn{}class us extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class Ts extends us{}class Ss extends us{}class ds extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class $s extends ds{}class Nr extends ds{}class wn extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class we extends wn{}class m extends wn{}class z extends wn{async _call(h){return new lr(await super._call(h))}}class Y extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class J extends Y{}class ve extends Y{}class Be extends Y{async _call(h){return new lr(await super._call(h))}}class xt extends Y{}class vt extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class kt extends vt{}class bt extends vt{}class fr extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class or extends fr{}class yr extends fr{}class qt extends X{}class Cr extends qt{}class yn extends qt{async _call(h){return new rn(await super._call(h))}}class Rr extends qt{async _call(h){return new lr(await super._call(h))}}class Ie extends qt{async _call(h){return new en(await super._call(h))}}class On extends qt{async _call(h){return new on(await super._call(h))}}class xr extends X{}class Jr extends xr{}class dn extends xr{async _call(h){return new rn(await super._call(h))}}class Xt extends xr{async _call(h){return new lr(await super._call(h))}}class hn extends xr{async _call(h){return new en(await super._call(h))}}class sn extends xr{async _call(h){return new on(await super._call(h))}}class Er extends X{}class Tr extends Er{}class Pt extends Er{async _call(h){return new rn(await super._call(h))}}class Sr extends Er{async _call(h){return new lr(await super._call(h))}}class Fr extends Er{async _call(h){return new en(await super._call(h))}}class jr extends Er{async _call(h){return new on(await super._call(h))}}class fn extends X{}class Nt extends fn{}class Gs extends fn{}class Ze extends X{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(h,D,re){super(h,D),this.generation_config=re}}class Vt extends Ze{}class wi extends Ze{_prepare_generation_config(h,D){return super._prepare_generation_config(h,D,F.WhisperGenerationConfig)}_retrieve_init_tokens(h){const D=[h.decoder_start_token_id];let re=h.language;const Oe=h.task;if(h.is_multilingual){re||(console.warn("No language specified - defaulting to English (en)."),re="en");const wt=`<|${(0,Q.whisper_language_to_code)(re)}|>`;D.push(h.lang_to_id[wt]),D.push(h.task_to_id[Oe??"transcribe"])}else if(re||Oe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!h.return_timestamps&&h.no_timestamps_token_id&&D.at(-1)!==h.no_timestamps_token_id?D.push(h.no_timestamps_token_id):h.return_timestamps&&D.at(-1)===h.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(Ye=>Ye!=null)}async generate({inputs:h=null,generation_config:D=null,logits_processor:re=null,stopping_criteria:Oe=null,...Ye}){D=this._prepare_generation_config(D,Ye);const wt=Ye.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(re??=new $.LogitsProcessorList,re.push(new $.WhisperTimeStampLogitsProcessor(D,wt))),D.begin_suppress_tokens&&(re??=new $.LogitsProcessorList,re.push(new $.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,wt.length))),D.return_token_timestamps){if(!D.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.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const At=await super.generate({inputs:h,generation_config:D,logits_processor:re,decoder_input_ids:wt,...Ye});return D.return_token_timestamps&&(At.token_timestamps=this._extract_token_timestamps(At,D.alignment_heads,D.num_frames)),At}_extract_token_timestamps(h,D,re=null,Oe=.02){if(!h.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`.");re==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 Ye=this.config.median_filter_width;Ye===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Ye=7);const wt=h.cross_attentions,At=Array.from({length:this.config.decoder_layers},(ir,Mr)=>(0,P.cat)(wt.map(qr=>qr[Mr]),2)),Zt=(0,P.stack)(D.map(([ir,Mr])=>{if(ir>=At.length)throw new Error(`Layer index ${ir} is out of bounds for cross attentions (length ${At.length}).`);return re?At[ir].slice(null,Mr,null,[0,re]):At[ir].slice(null,Mr)})).transpose(1,0,2,3),[mr,kr]=(0,P.std_mean)(Zt,-2,0,!0),Ir=Zt.clone();for(let ir=0;irqr[_n+1]-qr[_n]),Sn=(0,be.mergeArrays)([1],Hn).map(Qr=>!!Qr),mn=[];for(let Qr=0;Qrpr.findIndex(er=>er==Ye)),Zt=At.every(pr=>pr===-1),mr=At.every(pr=>pr!==-1);if(!Zt&&!mr)throw new Error("Every input should contain either 0 or 1 image token.");if(Zt)return{inputs_embeds:h,attention_mask:Oe};const kr=[],Ir=[];for(let pr=0;prYe*wt,1);h.input_labels=new P.Tensor("int64",new BigInt64Array(Oe).fill(1n),re)}const D={image_embeddings:h.image_embeddings,image_positional_embeddings:h.image_positional_embeddings};return h.input_points&&(D.input_points=h.input_points),h.input_labels&&(D.input_labels=h.input_labels),h.input_boxes&&(D.input_boxes=h.input_boxes),await me(this.sessions.prompt_encoder_mask_decoder,D)}async _call(h){return new Gn(await super._call(h))}}class Gn extends Ue{constructor({iou_scores:h,pred_masks:D}){super(),this.iou_scores=h,this.pred_masks=D}}class zn extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class qn extends zn{}class sa extends zn{}class Dn extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class an extends Dn{}class ia extends Dn{}class Pn extends X{}class aa extends Pn{}class hl extends Pn{async _call(h){return new es(await super._call(h))}}class fl extends Pn{async _call(h){return new lr(await super._call(h))}}class ml extends Pn{async _call(h){return new en(await super._call(h))}}class ks extends X{}class oa extends ks{}class _l extends ks{async _call(h){return new en(await super._call(h))}}class ei extends X{}class gl extends ei{}class Ps extends X{}class ti extends Ps{}class wl extends Ps{async _call(h){return new es(await super._call(h))}}class yl extends Ps{async _call(h){return new lr(await super._call(h))}}class ri extends X{}class bl extends ri{}class la extends ri{async _call(h){return new es(await super._call(h))}}class As extends ri{async _call(h){return new lr(await super._call(h))}}class Ml extends ri{async _call(h){return new en(await super._call(h))}}class Is extends X{}class vl extends Is{}class xl extends Is{async _call(h){return new es(await super._call(h))}}class Tl extends Is{async _call(h){return new lr(await super._call(h))}}class Wd extends X{}class Sl extends Pn{}class $l extends Pn{async _call(h){return new es(await super._call(h))}}class zu extends Pn{async _call(h){return new lr(await super._call(h))}}class Jn extends X{}class El extends Jn{}class Cl extends Jn{async _call(h){return new es(await super._call(h))}}class kl extends Jn{async _call(h){return new lr(await super._call(h))}}class ni extends Jn{async _call(h){return new wd(await super._call(h))}}class si extends Jn{async _call(h){return new en(await super._call(h))}}class ii extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class ua extends ii{}class da extends ii{}class ca extends ii{async generate_speech(h,D,{threshold:re=.5,minlenratio:Oe=0,maxlenratio:Ye=20,vocoder:wt=null}={}){const At={input_ids:h},{encoder_outputs:Zt,encoder_attention_mask:mr}=await rt(this,At),kr=Zt.dims[1]/this.config.reduction_factor,Ir=Math.floor(kr*Ye),pr=Math.floor(kr*Oe),er=this.config.num_mel_bins;let Dr=[],ir=null,Mr=null,qr=0;for(;;){++qr;const Sn=Pe(!!Mr);let mn;Mr?mn=Mr.output_sequence_out:mn=new P.Tensor("float32",new Float32Array(er),[1,1,er]);let Qr={use_cache_branch:Sn,output_sequence:mn,encoder_attention_mask:mr,speaker_embeddings:D,encoder_hidden_states:Zt};this.addPastKeyValues(Qr,ir),Mr=await me(this.sessions.decoder_model_merged,Qr),ir=this.getPastKeyValues(Mr,ir);const{prob:_n,spectrum:di}=Mr;if(Dr.push(di),qr>=pr&&(Array.from(_n.data).filter(Os=>Os>=re).length>0||qr>=Ir))break}const tn=(0,P.cat)(Dr),{waveform:Hn}=await me(wt.sessions.model,{spectrogram:tn});return{spectrogram:tn,waveform:Hn}}}class Pl extends X{main_input_name="spectrogram"}class Al extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class pa extends Al{}class ha extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class Il extends ha{}class Fl extends ha{}class Ol extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class zl extends Ol{}class fa extends Ol{}class Dl extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class Bl extends Dl{}class Ll extends Dl{}class ai extends X{}class ma extends ai{}class Rl extends ai{static async from_pretrained(h,D={}){return D.model_file_name??="text_model",super.from_pretrained(h,D)}}class Nl extends ai{static async from_pretrained(h,D={}){return D.model_file_name??="audio_model",super.from_pretrained(h,D)}}class jl extends X{}class _a extends jl{async _call(h){return new yu(await super._call(h))}}class oi extends X{}class Du extends oi{}class Bu extends oi{}class Vl extends oi{}class ga extends X{constructor(h,D,re){super(h,D),this.generation_config=re}}class Ul extends ga{}class Lu extends ga{}class wa extends X{}class Wl extends wa{}class Gl extends wa{async _call(h){return new lr(await super._call(h))}}class ya extends X{}class Ru extends ya{}class Gd extends ya{}class Fs extends X{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(h,D,re){super(h,D),this.generation_config=re}_apply_and_filter_by_delay_pattern_mask(h){const[D,re]=h.dims,Oe=this.config.decoder.num_codebooks,Ye=re-Oe;let wt=0;for(let mr=0;mr0&&pr<=Ye&&(h.data[wt++]=h.data[mr])}const At=Math.floor(D/Oe),Zt=wt/(At*Oe);return new P.Tensor(h.type,h.data.slice(0,wt),[At,Oe,Zt])}prepare_inputs_for_generation(h,D,re){let Oe=structuredClone(h);for(let wt=0;wt=At&&(Oe[wt][At]=BigInt(this.config.decoder.pad_token_id));return re.guidance_scale!==null&&re.guidance_scale>1&&(Oe=Oe.concat(Oe)),super.prepare_inputs_for_generation(Oe,D,re)}async generate(h){const D=await super.generate(h),re=this._apply_and_filter_by_delay_pattern_mask(D).unsqueeze_(0),{audio_values:Oe}=await me(this.sessions.encodec_decode,{audio_codes:re});return Oe}}class fs extends X{}class ba extends fs{}class ql extends fs{async _call(h){return new lr(await super._call(h))}}class Ma extends X{}class Hl extends Ma{}class Kl extends Ma{async _call(h){return new lr(await super._call(h))}}class li extends X{}class Xl extends li{}class Ql extends li{async _call(h){return new lr(await super._call(h))}}class va extends X{}class Nu extends va{}class Yl extends va{async _call(h){return new lr(await super._call(h))}}class Or{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(h,{progress_callback:D=null,config:re=null,cache_dir:Oe=null,local_files_only:Ye=!1,revision:wt="main",model_file_name:At=null,subfolder:Zt="onnx",device:mr=null,dtype:kr=null,use_external_data_format:Ir=null,session_options:pr={}}={}){let er={progress_callback:D,config:re,cache_dir:Oe,local_files_only:Ye,revision:wt,model_file_name:At,subfolder:Zt,device:mr,dtype:kr,use_external_data_format:Ir,session_options:pr};if(er.config=await I.AutoConfig.from_pretrained(h,er),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let Dr of this.MODEL_CLASS_MAPPINGS){const ir=Dr.get(er.config.model_type);if(ir)return await ir[1].from_pretrained(h,er)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${er.config.model_type}", attempting to construct from base class.`),await X.from_pretrained(h,er);throw Error(`Unsupported model type: ${er.config.model_type}`)}}const ju=new Map([["bert",["BertModel",ot]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",je]],["electra",["ElectraModel",Je]],["esm",["EsmModel",Zr]],["convbert",["ConvBertModel",St]],["camembert",["CamembertModel",et]],["deberta",["DebertaModel",tt]],["deberta-v2",["DebertaV2Model",Rt]],["mpnet",["MPNetModel",Us]],["albert",["AlbertModel",Yn]],["distilbert",["DistilBertModel",ur]],["roberta",["RobertaModel",Cr]],["xlm",["XLMModel",Jr]],["xlm-roberta",["XLMRobertaModel",Tr]],["clap",["ClapModel",ma]],["clip",["CLIPModel",za]],["clipseg",["CLIPSegModel",ja]],["chinese_clip",["ChineseCLIPModel",Na]],["siglip",["SiglipModel",ps]],["mobilebert",["MobileBertModel",Xr]],["squeezebert",["SqueezeBertModel",Ws]],["wav2vec2",["Wav2Vec2Model",aa]],["wav2vec2-bert",["Wav2Vec2BertModel",vl]],["unispeech",["UniSpeechModel",ti]],["unispeech-sat",["UniSpeechSatModel",bl]],["hubert",["HubertModel",Sl]],["wavlm",["WavLMModel",El]],["audio-spectrogram-transformer",["ASTModel",Nt]],["vits",["VitsModel",_a]],["pyannote",["PyAnnoteModel",oa]],["wespeaker-resnet",["WeSpeakerResNetModel",gl]],["detr",["DetrModel",zo]],["rt_detr",["RTDetrModel",Bo]],["table-transformer",["TableTransformerModel",No]],["vit",["ViTModel",Mo]],["fastvit",["FastViTModel",xo]],["mobilevit",["MobileViTModel",Au]],["mobilevitv2",["MobileViTV2Model",Eo]],["owlvit",["OwlViTModel",ko]],["owlv2",["Owlv2Model",Ao]],["beit",["BeitModel",Fo]],["deit",["DeiTModel",Uo]],["hiera",["HieraModel",Go]],["convnext",["ConvNextModel",sl]],["convnextv2",["ConvNextV2Model",al]],["dinov2",["Dinov2Model",Fu]],["resnet",["ResNetModel",Ho]],["swin",["SwinModel",Ki]],["swin2sr",["Swin2SRModel",Ko]],["donut-swin",["DonutSwinModel",nl]],["yolos",["YolosModel",ul]],["dpt",["DPTModel",Qo]],["glpn",["GLPNModel",Tn]],["hifigan",["SpeechT5HifiGan",Pl]],["efficientnet",["EfficientNetModel",Wl]],["mobilenet_v1",["MobileNetV1Model",ba]],["mobilenet_v2",["MobileNetV2Model",Hl]],["mobilenet_v3",["MobileNetV3Model",Xl]],["mobilenet_v4",["MobileNetV4Model",Nu]]]),Vu=new Map([["t5",["T5Model",vs]],["longt5",["LongT5Model",Ts]],["mt5",["MT5Model",$s]],["bart",["BartModel",we]],["mbart",["MBartModel",J]],["marian",["MarianModel",qn]],["whisper",["WhisperModel",Vt]],["m2m_100",["M2M100Model",an]],["blenderbot",["BlenderbotModel",kt]],["blenderbot-small",["BlenderbotSmallModel",or]]]),Uu=new Map([["bloom",["BloomModel",ku]],["jais",["JAISModel",Ga]],["gpt2",["GPT2Model",Ua]],["gptj",["GPTJModel",Ya]],["gpt_bigcode",["GPTBigCodeModel",Za]],["gpt_neo",["GPTNeoModel",Ha]],["gpt_neox",["GPTNeoXModel",Xa]],["codegen",["CodeGenModel",xn]],["llama",["LlamaModel",eo]],["cohere",["CohereModel",ro]],["gemma",["GemmaModel",so]],["gemma2",["Gemma2Model",ao]],["openelm",["OpenELMModel",lo]],["qwen2",["Qwen2Model",co]],["phi",["PhiModel",ho]],["phi3",["Phi3Model",fo]],["mpt",["MptModel",go]],["opt",["OPTModel",yo]],["mistral",["MistralModel",Il]],["starcoder2",["Starcoder2Model",zl]],["falcon",["FalconModel",Bl]],["stablelm",["StableLmModel",Ul]]]),Zl=new Map([["speecht5",["SpeechT5ForSpeechToText",da]],["whisper",["WhisperForConditionalGeneration",wi]]]),Jl=new Map([["speecht5",["SpeechT5ForTextToSpeech",ca]]]),eu=new Map([["vits",["VitsModel",_a]],["musicgen",["MusicgenForConditionalGeneration",Fs]]]),Wu=new Map([["bert",["BertForSequenceClassification",at]],["roformer",["RoFormerForSequenceClassification",Ge]],["electra",["ElectraForSequenceClassification",Mt]],["esm",["EsmForSequenceClassification",is]],["convbert",["ConvBertForSequenceClassification",W]],["camembert",["CamembertForSequenceClassification",ce]],["deberta",["DebertaForSequenceClassification",lt]],["deberta-v2",["DebertaV2ForSequenceClassification",Wt]],["mpnet",["MPNetForSequenceClassification",ys]],["albert",["AlbertForSequenceClassification",os]],["distilbert",["DistilBertForSequenceClassification",rr]],["roberta",["RobertaForSequenceClassification",Rr]],["xlm",["XLMForSequenceClassification",Xt]],["xlm-roberta",["XLMRobertaForSequenceClassification",Sr]],["bart",["BartForSequenceClassification",z]],["mbart",["MBartForSequenceClassification",Be]],["mobilebert",["MobileBertForSequenceClassification",Lr]],["squeezebert",["SqueezeBertForSequenceClassification",Cn]]]),tu=new Map([["bert",["BertForTokenClassification",Et]],["roformer",["RoFormerForTokenClassification",ut]],["electra",["ElectraForTokenClassification",nt]],["esm",["EsmForTokenClassification",Hr]],["convbert",["ConvBertForTokenClassification",E]],["camembert",["CamembertForTokenClassification",Te]],["deberta",["DebertaForTokenClassification",Ct]],["deberta-v2",["DebertaV2ForTokenClassification",zt]],["mpnet",["MPNetForTokenClassification",bs]],["distilbert",["DistilBertForTokenClassification",wr]],["roberta",["RobertaForTokenClassification",Ie]],["xlm",["XLMForTokenClassification",hn]],["xlm-roberta",["XLMRobertaForTokenClassification",Fr]]]),xa=new Map([["t5",["T5ForConditionalGeneration",xs]],["longt5",["LongT5ForConditionalGeneration",Ss]],["mt5",["MT5ForConditionalGeneration",Nr]],["bart",["BartForConditionalGeneration",m]],["mbart",["MBartForConditionalGeneration",ve]],["marian",["MarianMTModel",sa]],["m2m_100",["M2M100ForConditionalGeneration",ia]],["blenderbot",["BlenderbotForConditionalGeneration",bt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",yr]]]),Ta=new Map([["bloom",["BloomForCausalLM",_o]],["gpt2",["GPT2LMHeadModel",Wa]],["jais",["JAISLMHeadModel",qa]],["gptj",["GPTJForCausalLM",Cu]],["gpt_bigcode",["GPTBigCodeForCausalLM",qs]],["gpt_neo",["GPTNeoForCausalLM",Ka]],["gpt_neox",["GPTNeoXForCausalLM",Qa]],["codegen",["CodeGenForCausalLM",Ja]],["llama",["LlamaForCausalLM",to]],["cohere",["CohereForCausalLM",no]],["gemma",["GemmaForCausalLM",io]],["gemma2",["Gemma2ForCausalLM",oo]],["openelm",["OpenELMForCausalLM",uo]],["qwen2",["Qwen2ForCausalLM",po]],["phi",["PhiForCausalLM",Fi]],["phi3",["Phi3ForCausalLM",mo]],["mpt",["MptForCausalLM",wo]],["opt",["OPTForCausalLM",bo]],["mbart",["MBartForCausalLM",xt]],["mistral",["MistralForCausalLM",Fl]],["starcoder2",["Starcoder2ForCausalLM",fa]],["falcon",["FalconForCausalLM",Ll]],["trocr",["TrOCRForCausalLM",pa]],["stablelm",["StableLmForCausalLM",Lu]]]),ru=new Map([["bert",["BertForMaskedLM",De]],["roformer",["RoFormerForMaskedLM",Ve]],["electra",["ElectraForMaskedLM",He]],["esm",["EsmForMaskedLM",Xn]],["convbert",["ConvBertForMaskedLM",M]],["camembert",["CamembertForMaskedLM",B]],["deberta",["DebertaForMaskedLM",ft]],["deberta-v2",["DebertaV2ForMaskedLM",Ot]],["mpnet",["MPNetForMaskedLM",ws]],["albert",["AlbertForMaskedLM",Kt]],["distilbert",["DistilBertForMaskedLM",yt]],["roberta",["RobertaForMaskedLM",yn]],["xlm",["XLMWithLMHeadModel",dn]],["xlm-roberta",["XLMRobertaForMaskedLM",Pt]],["mobilebert",["MobileBertForMaskedLM",Qn]],["squeezebert",["SqueezeBertForMaskedLM",as]]]),Gu=new Map([["bert",["BertForQuestionAnswering",Fe]],["roformer",["RoFormerForQuestionAnswering",ht]],["electra",["ElectraForQuestionAnswering",pt]],["convbert",["ConvBertForQuestionAnswering",te]],["camembert",["CamembertForQuestionAnswering",Re]],["deberta",["DebertaForQuestionAnswering",gt]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ut]],["mpnet",["MPNetForQuestionAnswering",Ms]],["albert",["AlbertForQuestionAnswering",ls]],["distilbert",["DistilBertForQuestionAnswering",Qe]],["roberta",["RobertaForQuestionAnswering",On]],["xlm",["XLMForQuestionAnswering",sn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",jr]],["mobilebert",["MobileBertForQuestionAnswering",Vn]],["squeezebert",["SqueezeBertForQuestionAnswering",Wn]]]),Sa=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",yi]]]),qu=new Map([["llava",["LlavaForConditionalGeneration",cs]],["moondream1",["Moondream1ForConditionalGeneration",sr]],["florence2",["Florence2ForConditionalGeneration",bi]]]),Hu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",yi]]]),nu=new Map([["vit",["ViTForImageClassification",vo]],["fastvit",["FastViTForImageClassification",Pu]],["mobilevit",["MobileViTForImageClassification",$o]],["mobilevitv2",["MobileViTV2ForImageClassification",Co]],["beit",["BeitForImageClassification",Oo]],["deit",["DeiTForImageClassification",Wo]],["hiera",["HieraForImageClassification",qo]],["convnext",["ConvNextForImageClassification",il]],["convnextv2",["ConvNextV2ForImageClassification",ol]],["dinov2",["Dinov2ForImageClassification",ll]],["resnet",["ResNetForImageClassification",qi]],["swin",["SwinForImageClassification",Xi]],["segformer",["SegformerForImageClassification",Bu]],["efficientnet",["EfficientNetForImageClassification",Gl]],["mobilenet_v1",["MobileNetV1ForImageClassification",ql]],["mobilenet_v2",["MobileNetV2ForImageClassification",Kl]],["mobilenet_v3",["MobileNetV3ForImageClassification",Ql]],["mobilenet_v4",["MobileNetV4ForImageClassification",Yl]]]),Ku=new Map([["detr",["DetrForObjectDetection",Do]],["rt_detr",["RTDetrForObjectDetection",Lo]],["table-transformer",["TableTransformerForObjectDetection",jo]],["yolos",["YolosForObjectDetection",dl]]]),su=new Map([["owlvit",["OwlViTForObjectDetection",Po]],["owlv2",["Owlv2ForObjectDetection",Io]]]),iu=new Map([["detr",["DetrForSegmentation",Cs]],["clipseg",["CLIPSegForImageSegmentation",Va]]]),au=new Map([["segformer",["SegformerForSemanticSegmentation",Vl]],["sapiens",["SapiensForSemanticSegmentation",Jo]]]),ou=new Map([["sam",["SamModel",Ou]]]),Xu=new Map([["wav2vec2",["Wav2Vec2ForCTC",hl]],["wav2vec2-bert",["Wav2Vec2BertForCTC",xl]],["unispeech",["UniSpeechForCTC",wl]],["unispeech-sat",["UniSpeechSatForCTC",la]],["wavlm",["WavLMForCTC",Cl]],["hubert",["HubertForCTC",$l]]]),lu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",fl]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Tl]],["unispeech",["UniSpeechForSequenceClassification",yl]],["unispeech-sat",["UniSpeechSatForSequenceClassification",As]],["wavlm",["WavLMForSequenceClassification",kl]],["hubert",["HubertForSequenceClassification",zu]],["audio-spectrogram-transformer",["ASTForAudioClassification",Gs]]]),uu=new Map([["wavlm",["WavLMForXVector",ni]]]),du=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ml]],["wavlm",["WavLMForAudioFrameClassification",si]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ml]],["pyannote",["PyAnnoteForAudioFrameClassification",_l]]]),cu=new Map([["vitmatte",["VitMatteForImageMatting",So]]]),Qu=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Xo]]]),ln=new Map([["dpt",["DPTForDepthEstimation",Yo]],["depth_anything",["DepthAnythingForDepthEstimation",Zo]],["glpn",["GLPNForDepthEstimation",tl]],["sapiens",["SapiensForDepthEstimation",Iu]]]),pu=new Map([["sapiens",["SapiensForNormalEstimation",el]]]),hu=new Map([["clip",["CLIPVisionModelWithProjection",Da]],["siglip",["SiglipVisionModel",La]]]),$a=[[ju,se.EncoderOnly],[Vu,se.EncoderDecoder],[Uu,se.DecoderOnly],[Wu,se.EncoderOnly],[tu,se.EncoderOnly],[xa,se.Seq2Seq],[Zl,se.Seq2Seq],[Ta,se.DecoderOnly],[ru,se.EncoderOnly],[Gu,se.EncoderOnly],[Sa,se.Vision2Seq],[qu,se.ImageTextToText],[nu,se.EncoderOnly],[iu,se.EncoderOnly],[au,se.EncoderOnly],[cu,se.EncoderOnly],[Qu,se.EncoderOnly],[ln,se.EncoderOnly],[pu,se.EncoderOnly],[Ku,se.EncoderOnly],[su,se.EncoderOnly],[ou,se.MaskGeneration],[Xu,se.EncoderOnly],[lu,se.EncoderOnly],[Jl,se.Seq2Seq],[eu,se.EncoderOnly],[uu,se.EncoderOnly],[du,se.EncoderOnly],[hu,se.EncoderOnly]];for(const[_,h]of $a)for(const[D,re]of _.values())le.set(D,h),j.set(re,D),ie.set(D,re);const Yu=[["MusicgenForConditionalGeneration",Fs,se.Musicgen],["CLIPTextModelWithProjection",kn,se.EncoderOnly],["SiglipTextModel",Ba,se.EncoderOnly],["ClapTextModelWithProjection",Rl,se.EncoderOnly],["ClapAudioModelWithProjection",Nl,se.EncoderOnly]];for(const[_,h,D]of Yu)le.set(_,D),j.set(h,_),ie.set(_,h);class ui extends Or{static MODEL_CLASS_MAPPINGS=$a.map(h=>h[0]);static BASE_IF_FAIL=!0}class Zu extends Or{static MODEL_CLASS_MAPPINGS=[Wu]}class Ju extends Or{static MODEL_CLASS_MAPPINGS=[tu]}class fu extends Or{static MODEL_CLASS_MAPPINGS=[xa]}class ed extends Or{static MODEL_CLASS_MAPPINGS=[Zl]}class td extends Or{static MODEL_CLASS_MAPPINGS=[Jl]}class mu extends Or{static MODEL_CLASS_MAPPINGS=[eu]}class rd extends Or{static MODEL_CLASS_MAPPINGS=[Ta]}class nd extends Or{static MODEL_CLASS_MAPPINGS=[ru]}class sd extends Or{static MODEL_CLASS_MAPPINGS=[Gu]}class _u extends Or{static MODEL_CLASS_MAPPINGS=[Sa]}class id extends Or{static MODEL_CLASS_MAPPINGS=[nu]}class ad extends Or{static MODEL_CLASS_MAPPINGS=[iu]}class gu extends Or{static MODEL_CLASS_MAPPINGS=[au]}class od extends Or{static MODEL_CLASS_MAPPINGS=[Ku]}class qd extends Or{static MODEL_CLASS_MAPPINGS=[su]}class ld extends Or{static MODEL_CLASS_MAPPINGS=[ou]}class ud extends Or{static MODEL_CLASS_MAPPINGS=[Xu]}class dd extends Or{static MODEL_CLASS_MAPPINGS=[lu]}class cd extends Or{static MODEL_CLASS_MAPPINGS=[uu]}class Hd extends Or{static MODEL_CLASS_MAPPINGS=[du]}class pd extends Or{static MODEL_CLASS_MAPPINGS=[Hu]}class hd extends Or{static MODEL_CLASS_MAPPINGS=[cu]}class fd extends Or{static MODEL_CLASS_MAPPINGS=[Qu]}class Kd extends Or{static MODEL_CLASS_MAPPINGS=[ln]}class md extends Or{static MODEL_CLASS_MAPPINGS=[pu]}class _d extends Or{static MODEL_CLASS_MAPPINGS=[hu]}class gd extends Ue{constructor({logits:h,past_key_values:D,encoder_outputs:re,decoder_attentions:Oe=null,cross_attentions:Ye=null}){super(),this.logits=h,this.past_key_values=D,this.encoder_outputs=re,this.decoder_attentions=Oe,this.cross_attentions=Ye}}class lr extends Ue{constructor({logits:h}){super(),this.logits=h}}class wd extends Ue{constructor({logits:h,embeddings:D}){super(),this.logits=h,this.embeddings=D}}class en extends Ue{constructor({logits:h}){super(),this.logits=h}}class rn extends Ue{constructor({logits:h}){super(),this.logits=h}}class on extends Ue{constructor({start_logits:h,end_logits:D}){super(),this.start_logits=h,this.end_logits=D}}class es extends Ue{constructor({logits:h}){super(),this.logits=h}}class yd extends Ue{constructor({logits:h,past_key_values:D}){super(),this.logits=h,this.past_key_values=D}}class wu extends Ue{constructor({alphas:h}){super(),this.alphas=h}}class yu extends Ue{constructor({waveform:h,spectrogram:D}){super(),this.waveform=h,this.spectrogram=D}}},"./src/models/whisper/common_whisper.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{WHISPER_LANGUAGE_MAPPING:()=>ae,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>he,whisper_language_to_code:()=>xe});const I=[["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"]],ae=new Map(I),he=new Map([...I.map(([be,R])=>[R,be]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function xe(be){be=be.toLowerCase();let R=he.get(be);if(R===void 0)if(ae.has(be))R=be;else{const V=be.length===2?ae.keys():ae.values();throw new Error(`Language "${be}" is not supported. Must be one of: ${JSON.stringify(V)}`)}return R}},"./src/models/whisper/generation_whisper.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{WhisperGenerationConfig:()=>ae});var I=N("./src/generation/configuration_utils.js");class ae extends I.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}},"./src/ops/registry.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{TensorOpRegistry:()=>xe});var I=N("./src/backends/onnx.js"),ae=N("./src/utils/tensor.js");const he=async(be,R,$)=>{const V=await(0,I.createInferenceSession)(new Uint8Array(be),R);return async P=>{const K=Object.fromEntries(Object.entries(P).map(([oe,_e])=>[oe,_e.ort_tensor])),ne=await V.run(K);return Array.isArray($)?$.map(oe=>new ae.Tensor(ne[oe])):new ae.Tensor(ne[$])}};class xe{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=he([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=he([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=he([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=he([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=he([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=he([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}}},"./src/pipelines.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{AudioClassificationPipeline:()=>Pe,AutomaticSpeechRecognitionPipeline:()=>rt,DepthEstimationPipeline:()=>st,DocumentQuestionAnsweringPipeline:()=>X,FeatureExtractionPipeline:()=>ye,FillMaskPipeline:()=>le,ImageClassificationPipeline:()=>dt,ImageFeatureExtractionPipeline:()=>Se,ImageSegmentationPipeline:()=>ge,ImageToImagePipeline:()=>ct,ImageToTextPipeline:()=>Xe,ObjectDetectionPipeline:()=>de,Pipeline:()=>_e,QuestionAnsweringPipeline:()=>se,SummarizationPipeline:()=>j,Text2TextGenerationPipeline:()=>ie,TextClassificationPipeline:()=>F,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>Ue,TokenClassificationPipeline:()=>Q,TranslationPipeline:()=>A,ZeroShotAudioClassificationPipeline:()=>Ce,ZeroShotClassificationPipeline:()=>me,ZeroShotImageClassificationPipeline:()=>U,ZeroShotObjectDetectionPipeline:()=>$e,pipeline:()=>at});var I=N("./src/tokenizers.js"),ae=N("./src/models.js"),he=N("./src/processors.js"),xe=N("./src/utils/generic.js"),be=N("./src/utils/core.js"),R=N("./src/utils/maths.js"),$=N("./src/utils/audio.js"),V=N("./src/utils/tensor.js"),P=N("./src/utils/image.js");async function K(Fe){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(H=>P.RawImage.read(H)))}async function ne(Fe,H){return Array.isArray(Fe)||(Fe=[Fe]),await Promise.all(Fe.map(Ee=>typeof Ee=="string"||Ee instanceof URL?(0,$.read_audio)(Ee,H):Ee instanceof Float64Array?new Float32Array(Ee):Ee))}function oe(Fe,H){H&&(Fe=Fe.map(Ge=>Ge|0));const[Ee,qe,je,Ve]=Fe;return{xmin:Ee,ymin:qe,xmax:je,ymax:Ve}}class _e extends xe.Callable{constructor({task:H,model:Ee,tokenizer:qe=null,processor:je=null}){super(),this.task=H,this.model=Ee,this.tokenizer=qe,this.processor=je}async dispose(){await this.model.dispose()}}class F extends _e{constructor(H){super(H)}async _call(H,{top_k:Ee=1}={}){const qe=this.tokenizer(H,{padding:!0,truncation:!0}),je=await this.model(qe),Ve=this.model.config.problem_type==="multi_label_classification"?ht=>ht.sigmoid():ht=>new V.Tensor("float32",(0,R.softmax)(ht.data),ht.dims),Ge=this.model.config.id2label,ut=[];for(const ht of je.logits){const Tt=Ve(ht),St=await(0,V.topk)(Tt,Ee),M=St[0].tolist(),E=St[1].tolist().map((te,pe)=>({label:Ge?Ge[te]:`LABEL_${te}`,score:M[pe]}));Ee===1?ut.push(...E):ut.push(E)}return Array.isArray(H)||Ee===1?ut:ut[0]}}class Q extends _e{constructor(H){super(H)}async _call(H,{ignore_labels:Ee=["O"]}={}){const qe=Array.isArray(H),je=this.tokenizer(qe?H:[H],{padding:!0,truncation:!0}),Ge=(await this.model(je)).logits,ut=this.model.config.id2label,ht=[];for(let Tt=0;Ttnt==this.tokenizer.sep_token_id);ht[M].map((nt,pt)=>nt==1&&(pt===0||pt>E&&Tt.findIndex(Bt=>Bt==W[pt])===-1));const te=Ve[M].tolist(),pe=Ge[M].tolist();for(let nt=1;ntpt==W[nt])!==-1)&&(te[nt]=-1/0,pe[nt]=-1/0);const Je=(0,R.softmax)(te).map((nt,pt)=>[nt,pt]),He=(0,R.softmax)(pe).map((nt,pt)=>[nt,pt]);Je[0][0]=0,He[0][0]=0;const Mt=(0,be.product)(Je,He).filter(nt=>nt[0][1]<=nt[1][1]).map(nt=>[nt[0][1],nt[1][1],nt[0][0]*nt[1][0]]).sort((nt,pt)=>pt[2]-nt[2]);for(let nt=0;ntte==this.tokenizer.mask_token_id);if(Tt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const St=je[ut][Tt],M=await(0,V.topk)(new V.Tensor("float32",(0,R.softmax)(St.data),St.dims),Ee),W=M[0].tolist(),E=M[1].tolist();Ve.push(E.map((te,pe)=>{const Je=ht.slice();return Je[Tt]=te,{score:W[pe],token:Number(te),token_str:this.tokenizer.model.vocab[te],sequence:this.tokenizer.decode(Je,{skip_special_tokens:!0})}}))}return Array.isArray(H)?Ve:Ve[0]}}class ie extends _e{_key="generated_text";constructor(H){super(H)}async _call(H,Ee={}){Array.isArray(H)||(H=[H]),this.model.config.prefix&&(H=H.map(ht=>this.model.config.prefix+ht));const qe=this.model.config.task_specific_params;qe&&qe[this.task]&&qe[this.task].prefix&&(H=H.map(ht=>qe[this.task].prefix+ht));const je=this.tokenizer,Ve={padding:!0,truncation:!0};let Ge;this instanceof A&&"_build_translation_inputs"in je?Ge=je._build_translation_inputs(H,Ve,Ee):Ge=je(H,Ve);const ut=await this.model.generate({...Ge,...Ee});return je.batch_decode(ut,{skip_special_tokens:!0}).map(ht=>({[this._key]:ht}))}}class j extends ie{_key="summary_text";constructor(H){super(H)}}class A extends ie{_key="translation_text";constructor(H){super(H)}}function L(Fe){return Array.isArray(Fe)&&Fe.every(H=>"role"in H&&"content"in H)}class C extends _e{constructor(H){super(H)}async _call(H,Ee={}){let qe=!1,je=!1,Ve;if(typeof H=="string")Ve=H=[H];else if(Array.isArray(H)&&H.every(E=>typeof E=="string"))qe=!0,Ve=H;else{if(L(H))H=[H];else if(Array.isArray(H)&&H.every(L))qe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");je=!0,Ve=H.map(E=>this.tokenizer.apply_chat_template(E,{tokenize:!1,add_generation_prompt:!0}))}const Ge=Ee.add_special_tokens??!1,ut=je?!1:Ee.return_full_text??!0;this.tokenizer.padding_side="left";const ht=this.tokenizer(Ve,{add_special_tokens:Ge,padding:!0,truncation:!0}),Tt=await this.model.generate({...ht,...Ee}),St=this.tokenizer.batch_decode(Tt,{skip_special_tokens:!0});let M;!ut&&ht.input_ids.dims.at(-1)>0&&(M=this.tokenizer.batch_decode(ht.input_ids,{skip_special_tokens:!0}).map(E=>E.length));const W=Array.from({length:H.length},E=>[]);for(let E=0;E[Ee.toLowerCase(),qe])),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(H,Ee,{hypothesis_template:qe="This example is {}.",multi_label:je=!1}={}){const Ve=Array.isArray(H);Ve||(H=[H]),Array.isArray(Ee)||(Ee=[Ee]);const Ge=Ee.map(Tt=>qe.replace("{}",Tt)),ut=je||Ee.length===1,ht=[];for(const Tt of H){const St=[];for(const E of Ge){const te=this.tokenizer(Tt,{text_pair:E,padding:!0,truncation:!0}),pe=await this.model(te);ut?St.push([pe.logits.data[this.contradiction_id],pe.logits.data[this.entailment_id]]):St.push(pe.logits.data[this.entailment_id])}const W=(ut?St.map(E=>(0,R.softmax)(E)[1]):(0,R.softmax)(St)).map((E,te)=>[E,te]).sort((E,te)=>te[0]-E[0]);ht.push({sequence:Tt,labels:W.map(E=>Ee[E[1]]),scores:W.map(E=>E[0])})}return Ve?ht:ht[0]}}class ye extends _e{constructor(H){super(H)}async _call(H,{pooling:Ee="none",normalize:qe=!1,quantize:je=!1,precision:Ve="binary"}={}){const Ge=this.tokenizer(H,{padding:!0,truncation:!0}),ut=await this.model(Ge);let ht=ut.last_hidden_state??ut.logits??ut.token_embeddings;if(Ee!=="none")if(Ee==="mean")ht=(0,V.mean_pooling)(ht,Ge.attention_mask);else if(Ee==="cls")ht=ht.slice(null,0);else throw Error(`Pooling method '${Ee}' not supported.`);return qe&&(ht=ht.normalize(2,-1)),je&&(ht=(0,V.quantize_embeddings)(ht,Ve)),ht}}class Se extends _e{constructor(H){super(H)}async _call(H,{pool:Ee=null}={}){const qe=await K(H),{pixel_values:je}=await this.processor(qe),Ve=await this.model({pixel_values:je});let Ge;if(Ee){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.");Ge=Ve.pooler_output}else Ge=Ve.last_hidden_state??Ve.logits??Ve.image_embeds;return Ge}}class Pe extends _e{constructor(H){super(H)}async _call(H,{top_k:Ee=5}={}){const qe=this.processor.feature_extractor.config.sampling_rate,je=await ne(H,qe),Ve=this.model.config.id2label,Ge=[];for(const ut of je){const ht=await this.processor(ut),St=(await this.model(ht)).logits[0],M=await(0,V.topk)(new V.Tensor("float32",(0,R.softmax)(St.data),St.dims),Ee),W=M[0].tolist(),te=M[1].tolist().map((pe,Je)=>({label:Ve?Ve[pe]:`LABEL_${pe}`,score:W[Je]}));Ge.push(te)}return Array.isArray(H)?Ge:Ge[0]}}class Ce extends _e{constructor(H){super(H)}async _call(H,Ee,{hypothesis_template:qe="This is a sound of {}."}={}){const je=!Array.isArray(H);je&&(H=[H]);const Ve=Ee.map(St=>qe.replace("{}",St)),Ge=this.tokenizer(Ve,{padding:!0,truncation:!0}),ut=this.processor.feature_extractor.config.sampling_rate,ht=await ne(H,ut),Tt=[];for(const St of ht){const M=await this.processor(St),W=await this.model({...Ge,...M}),E=(0,R.softmax)(W.logits_per_audio.data);Tt.push([...E].map((te,pe)=>({score:te,label:Ee[pe]})))}return je?Tt[0]:Tt}}class rt extends _e{constructor(H){super(H)}async _call(H,Ee={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(H,Ee);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(H,Ee);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(H,Ee){Ee.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ee.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const qe=!Array.isArray(H);qe&&(H=[H]);const je=this.processor.feature_extractor.config.sampling_rate,Ve=await ne(H,je),Ge=[];for(const ut of Ve){const ht=await this.processor(ut),St=(await this.model(ht)).logits[0],M=[];for(const E of St)M.push((0,R.max)(E.data)[1]);const W=this.tokenizer.decode(M);Ge.push({text:W})}return qe?Ge[0]:Ge}async _call_whisper(H,Ee){const qe=Ee.return_timestamps??!1,je=Ee.chunk_length_s??0,Ve=Ee.force_full_sequences??!1;let Ge=Ee.stride_length_s??null;const ut={...Ee};qe==="word"&&(ut.return_token_timestamps=!0,ut.return_timestamps=!1);const ht=!Array.isArray(H);ht&&(H=[H]);const Tt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,St=this.processor.feature_extractor.config.hop_length,M=this.processor.feature_extractor.config.sampling_rate,W=await ne(H,M),E=[];for(const te of W){let pe=[];if(je>0){if(Ge===null)Ge=je/6;else if(je<=Ge)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Mt=M*je,nt=M*Ge,pt=Mt-2*nt;let Bt=0;for(;;){const et=Bt+Mt,B=te.subarray(Bt,et),ce=await this.processor(B),Te=Bt===0,Re=et>=te.length;if(pe.push({stride:[B.length,Te?0:nt,Re?0:nt],input_features:ce.input_features,is_last:Re}),Re)break;Bt+=pt}}else pe=[{stride:[te.length,0,0],input_features:(await this.processor(te)).input_features,is_last:!0}];for(const Mt of pe){ut.num_frames=Math.floor(Mt.stride[0]/St);const nt=await this.model.generate({inputs:Mt.input_features,...ut});qe==="word"?(Mt.tokens=nt.sequences.tolist()[0],Mt.token_timestamps=nt.token_timestamps.tolist()[0].map(pt=>(0,R.round)(pt,2))):Mt.tokens=nt[0].tolist(),Mt.stride=Mt.stride.map(pt=>pt/M)}const[Je,He]=this.tokenizer._decode_asr(pe,{time_precision:Tt,return_timestamps:qe,force_full_sequences:Ve});E.push({text:Je,...He})}return ht?E[0]:E}}class Xe extends _e{constructor(H){super(H)}async _call(H,Ee={}){const qe=Array.isArray(H),je=await K(H),{pixel_values:Ve}=await this.processor(je),Ge=[];for(const ut of Ve){ut.dims=[1,...ut.dims];const ht=await this.model.generate({inputs:ut,...Ee}),Tt=this.tokenizer.batch_decode(ht,{skip_special_tokens:!0}).map(St=>({generated_text:St.trim()}));Ge.push(Tt)}return qe?Ge:Ge[0]}}class dt extends _e{constructor(H){super(H)}async _call(H,{top_k:Ee=5}={}){const qe=await K(H),{pixel_values:je}=await this.processor(qe),Ve=await this.model({pixel_values:je}),Ge=this.model.config.id2label,ut=[];for(const ht of Ve.logits){const Tt=await(0,V.topk)(new V.Tensor("float32",(0,R.softmax)(ht.data),ht.dims),Ee),St=Tt[0].tolist(),W=Tt[1].tolist().map((E,te)=>({label:Ge?Ge[E]:`LABEL_${E}`,score:St[te]}));ut.push(W)}return Array.isArray(H)?ut:ut[0]}}class ge extends _e{constructor(H){super(H),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(H,{threshold:Ee=.5,mask_threshold:qe=.5,overlap_mask_area_threshold:je=.8,label_ids_to_fuse:Ve=null,target_sizes:Ge=null,subtask:ut=null}={}){if(Array.isArray(H)&&H.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Tt=await K(H),St=Tt.map(He=>[He.height,He.width]),{pixel_values:M,pixel_mask:W}=await this.processor(Tt),E=await this.model({pixel_values:M,pixel_mask:W});let te=null;if(ut!==null)te=this.subtasks_mapping[ut];else for(let[He,Mt]of Object.entries(this.subtasks_mapping))if(Mt in this.processor.feature_extractor){te=this.processor.feature_extractor[Mt].bind(this.processor.feature_extractor),ut=He;break}const pe=this.model.config.id2label,Je=[];if(ut==="panoptic"||ut==="instance"){const He=te(E,Ee,qe,je,Ve,Ge??St)[0],Mt=He.segmentation;for(const nt of He.segments_info){const pt=new Uint8ClampedArray(Mt.data.length);for(let et=0;etqe.replace("{}",W)),ut=this.tokenizer(Ge,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ht}=await this.processor(Ve),Tt=await this.model({...ut,pixel_values:ht}),St=this.model.config.model_type==="siglip"?W=>W.sigmoid().data:W=>(0,R.softmax)(W.data),M=[];for(const W of Tt.logits_per_image){const te=[...St(W)].map((pe,Je)=>({score:pe,label:Ee[Je]}));te.sort((pe,Je)=>Je.score-pe.score),M.push(te)}return je?M:M[0]}}class de extends _e{constructor(H){super(H)}async _call(H,{threshold:Ee=.9,percentage:qe=!1}={}){const je=Array.isArray(H);if(je&&H.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ve=await K(H),Ge=qe?null:Ve.map(E=>[E.height,E.width]),{pixel_values:ut,pixel_mask:ht}=await this.processor(Ve),Tt=await this.model({pixel_values:ut,pixel_mask:ht}),St=this.processor.feature_extractor.post_process_object_detection(Tt,Ee,Ge),M=this.model.config.id2label,W=St.map(E=>E.boxes.map((te,pe)=>({score:E.scores[pe],label:M[E.classes[pe]],box:oe(te,!qe)})));return je?W:W[0]}}class $e extends _e{constructor(H){super(H)}async _call(H,Ee,{threshold:qe=.1,top_k:je=null,percentage:Ve=!1}={}){const Ge=Array.isArray(H),ut=await K(H),ht=this.tokenizer(Ee,{padding:!0,truncation:!0}),Tt=await this.processor(ut),St=[];for(let M=0;M({score:Je.scores[nt],label:Ee[Je.classes[nt]],box:oe(Mt,!Ve)})).sort((Mt,nt)=>nt.score-Mt.score);je!==null&&(He=He.slice(0,je)),St.push(He)}return Ge?St:St[0]}}class X extends _e{constructor(H){super(H)}async _call(H,Ee,qe={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class Ue extends _e{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(H){super(H),this.vocoder=H.vocoder??null}async _call(H,{speaker_embeddings:Ee=null}={}){return this.processor?this._call_text_to_spectrogram(H,{speaker_embeddings:Ee}):this._call_text_to_waveform(H)}async _call_text_to_waveform(H){const Ee=this.tokenizer(H,{padding:!0,truncation:!0}),{waveform:qe}=await this.model(Ee),je=this.model.config.sampling_rate;return{audio:qe.data,sampling_rate:je}}async _call_text_to_spectrogram(H,{speaker_embeddings:Ee}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await ae.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ee=="string"||Ee instanceof URL)&&(Ee=new Float32Array(await(await fetch(Ee)).arrayBuffer())),Ee instanceof Float32Array)Ee=new V.Tensor("float32",Ee,[1,Ee.length]);else if(!(Ee instanceof V.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:qe}=this.tokenizer(H,{padding:!0,truncation:!0}),{waveform:je}=await this.model.generate_speech(qe,Ee,{vocoder:this.vocoder}),Ve=this.processor.feature_extractor.config.sampling_rate;return{audio:je.data,sampling_rate:Ve}}}class ct extends _e{constructor(H){super(H)}async _call(H){const Ee=await K(H),qe=await this.processor(Ee),je=await this.model(qe),Ve=[];for(const Ge of je.reconstruction){const ut=Ge.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ve.push(P.RawImage.fromTensor(ut))}return Ve.length>1?Ve:Ve[0]}}class st extends _e{constructor(H){super(H)}async _call(H){const Ee=await K(H),qe=await this.processor(Ee),{predicted_depth:je}=await this.model(qe),Ve=[];for(let Ge=0;Ge1?Ve:Ve[0]}}const ot=Object.freeze({"text-classification":{tokenizer:I.AutoTokenizer,pipeline:F,model:ae.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:I.AutoTokenizer,pipeline:Q,model:ae.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:I.AutoTokenizer,pipeline:se,model:ae.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:I.AutoTokenizer,pipeline:le,model:ae.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:I.AutoTokenizer,pipeline:j,model:ae.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:I.AutoTokenizer,pipeline:A,model:ae.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:I.AutoTokenizer,pipeline:ie,model:ae.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:I.AutoTokenizer,pipeline:C,model:ae.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:I.AutoTokenizer,pipeline:me,model:ae.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Pe,model:ae.AutoModelForAudioClassification,processor:he.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:I.AutoTokenizer,pipeline:Ce,model:ae.AutoModel,processor:he.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:I.AutoTokenizer,pipeline:rt,model:[ae.AutoModelForSpeechSeq2Seq,ae.AutoModelForCTC],processor:he.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:I.AutoTokenizer,pipeline:Ue,model:[ae.AutoModelForTextToWaveform,ae.AutoModelForTextToSpectrogram],processor:[he.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:I.AutoTokenizer,pipeline:Xe,model:ae.AutoModelForVision2Seq,processor:he.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:dt,model:ae.AutoModelForImageClassification,processor:he.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ge,model:[ae.AutoModelForImageSegmentation,ae.AutoModelForSemanticSegmentation],processor:he.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:I.AutoTokenizer,pipeline:U,model:ae.AutoModel,processor:he.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:de,model:ae.AutoModelForObjectDetection,processor:he.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:I.AutoTokenizer,pipeline:$e,model:ae.AutoModelForZeroShotObjectDetection,processor:he.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:I.AutoTokenizer,pipeline:X,model:ae.AutoModelForDocumentQuestionAnswering,processor:he.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ct,model:ae.AutoModelForImageToImage,processor:he.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:st,model:ae.AutoModelForDepthEstimation,processor:he.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:I.AutoTokenizer,pipeline:ye,model:ae.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:he.AutoProcessor,pipeline:Se,model:[ae.AutoModelForImageFeatureExtraction,ae.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),De=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function at(Fe,H=null,{progress_callback:Ee=null,config:qe=null,cache_dir:je=null,local_files_only:Ve=!1,revision:Ge="main",device:ut=null,dtype:ht=null,model_file_name:Tt=null,session_options:St={}}={}){Fe=De[Fe]??Fe;const M=ot[Fe.split("_",1)[0]];if(!M)throw Error(`Unsupported pipeline: ${Fe}. Must be one of [${Object.keys(ot)}]`);H||(H=M.default.model,console.log(`No model specified. Using default model: "${H}".`));const W={progress_callback:Ee,config:qe,cache_dir:je,local_files_only:Ve,revision:Ge,device:ut,dtype:ht,model_file_name:Tt,session_options:St},E=new Map([["tokenizer",M.tokenizer],["model",M.model],["processor",M.processor]]),te=await Et(E,H,W);te.task=Fe,(0,be.dispatchCallback)(Ee,{status:"ready",task:Fe,model:H});const pe=M.pipeline;return new pe(te)}async function Et(Fe,H,Ee){const qe=Object.create(null),je=[];for(let[Ve,Ge]of Fe.entries()){if(!Ge)continue;let ut;Array.isArray(Ge)?ut=new Promise(async(ht,Tt)=>{let St;for(let M of Ge){if(M===null){ht(null);return}try{ht(await M.from_pretrained(H,Ee));return}catch(W){if(W.message?.includes("Unsupported model type"))St=W;else if(W.message?.includes("Could not locate file"))St=W;else{Tt(W);return}}}Tt(St)}):ut=Ge.from_pretrained(H,Ee),qe[Ve]=ut,je.push(ut)}await Promise.all(je);for(let[Ve,Ge]of Object.entries(qe))qe[Ve]=await Ge;return qe}},"./src/processors.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{ASTFeatureExtractor:()=>ht,AutoProcessor:()=>Bt,BeitFeatureExtractor:()=>De,BitImageProcessor:()=>j,CLIPFeatureExtractor:()=>L,CLIPImageProcessor:()=>C,ChineseCLIPFeatureExtractor:()=>me,ClapFeatureExtractor:()=>Tt,ConvNextFeatureExtractor:()=>Se,ConvNextImageProcessor:()=>Pe,DPTFeatureExtractor:()=>le,DPTImageProcessor:()=>ie,DeiTFeatureExtractor:()=>ot,DetrFeatureExtractor:()=>Fe,DonutFeatureExtractor:()=>at,EfficientNetImageProcessor:()=>Xe,FeatureExtractor:()=>_e,Florence2Processor:()=>pt,GLPNFeatureExtractor:()=>A,ImageFeatureExtractor:()=>F,MobileNetV1FeatureExtractor:()=>dt,MobileNetV2FeatureExtractor:()=>ge,MobileNetV3FeatureExtractor:()=>U,MobileNetV4FeatureExtractor:()=>de,MobileViTFeatureExtractor:()=>$e,MobileViTImageProcessor:()=>X,NougatImageProcessor:()=>Et,OwlViTFeatureExtractor:()=>Ue,OwlViTProcessor:()=>nt,Owlv2ImageProcessor:()=>ct,Processor:()=>E,PyAnnoteFeatureExtractor:()=>St,PyAnnoteProcessor:()=>He,RTDetrImageProcessor:()=>st,SamImageProcessor:()=>Ee,SamProcessor:()=>te,SapiensFeatureExtractor:()=>Q,SeamlessM4TFeatureExtractor:()=>ut,SegformerFeatureExtractor:()=>se,SiglipImageProcessor:()=>ye,SpeechT5FeatureExtractor:()=>W,SpeechT5Processor:()=>Mt,Swin2SRImageProcessor:()=>qe,ViTFeatureExtractor:()=>Ce,ViTImageProcessor:()=>rt,VitMatteImageProcessor:()=>je,Wav2Vec2FeatureExtractor:()=>Ge,Wav2Vec2ProcessorWithLM:()=>Je,WeSpeakerFeatureExtractor:()=>M,WhisperFeatureExtractor:()=>Ve,WhisperProcessor:()=>pe,YolosFeatureExtractor:()=>H});var I=N("./src/utils/generic.js"),ae=N("./src/utils/core.js"),he=N("./src/utils/hub.js"),xe=N("./src/utils/maths.js"),be=N("./src/utils/tensor.js");N("./src/utils/image.js");var R=N("./src/utils/audio.js");function $([et,B,ce,Te]){return[et-ce/2,B-Te/2,et+ce/2,B+Te/2]}function V(et,B=.5,ce=null,Te=!1){const Re=et.logits,ke=et.pred_boxes,[tt,ft,lt]=Re.dims;if(ce!==null&&ce.length!==tt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Ct=[];for(let gt=0;gtB&&Ht.push(rr)}else{let rr=(0,xe.max)(Ut.data)[1];if(rr===lt-1||(ur=(0,xe.softmax)(Ut.data),ur[rr]Qe*ze[(yt+1)%2])),Rt.boxes.push(wr),Rt.classes.push(rr),Rt.scores.push(ur[rr])}}Ct.push(Rt)}return Ct}function P(et,B=null){const ce=et.logits,Te=ce.dims[0];if(B!==null&&B.length!==Te)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Re=[];for(let ke=0;keze[Ht]&&(ze[Ht]=Ut[Ht],Rt[Ht]=zt)}const Ot=new Array(ft.dims[0]);for(let zt=0;ztzt!==void 0);Re.push({segmentation:gt,labels:Wt})}return Re}function K(et,B){if(!(et instanceof Float32Array||et instanceof Float64Array))throw new Error(`${B} expects input to be a Float32Array or a Float64Array, but got ${et?.constructor?.name??typeof et} 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.`)}function ne(et,B,ce=0,Te=null){const Re=et/B;let ke=(0,xe.bankers_round)(Re)*B;return Te!==null&&ke>Te&&(ke=Math.floor(Re)*B),keke?Ct=Math.floor(ke*lt/Re):ke>Re&&(lt=Math.floor(Re*Ct/ke)),await B.resize(Ct,lt,{resample:Te}))}async crop_margin(B,ce=200){const Te=B.clone().grayscale(),Re=(0,xe.min)(Te.data)[0],tt=(0,xe.max)(Te.data)[0]-Re;if(tt===0)return B;const ft=ce/255;let lt=Te.width,Ct=Te.height,gt=0,ze=0;const Rt=Te.data;for(let Ot=0;Otthis.preprocess(ke)));return{pixel_values:(0,be.stack)(Te.map(ke=>ke.pixel_values),0),original_sizes:Te.map(ke=>ke.original_size),reshaped_input_sizes:Te.map(ke=>ke.reshaped_input_size)}}}class Q extends F{post_process_semantic_segmentation(...B){return P(...B)}}class se extends F{post_process_semantic_segmentation(...B){return P(...B)}}class le extends F{}class ie extends le{}class j extends F{}class A extends F{}class L extends F{}class C extends L{}class me extends F{}class ye extends F{}class Se extends F{constructor(B){super(B),this.crop_pct=this.config.crop_pct??224/256}async resize(B){const ce=this.size?.shortest_edge;if(ce===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ce<384){const Te=Math.floor(ce/this.crop_pct),[Re,ke]=this.get_resize_output_image_size(B,{shortest_edge:Te});B=await B.resize(Re,ke,{resample:this.resample}),B=await B.center_crop(ce,ce)}else B=await B.resize(ce,ce,{resample:this.resample});return B}}class Pe extends Se{}class Ce extends F{}class rt extends F{}class Xe extends F{constructor(B){super(B),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ce=>ce*ce))}}class dt extends F{}class ge extends F{}class U extends F{}class de extends F{}class $e extends F{}class X extends $e{}class Ue extends F{post_process_object_detection(...B){return V(...B)}}class ct extends Ue{}class st extends F{post_process_object_detection(...B){return V(...B)}}class ot extends F{}class De extends F{}class at extends F{pad_image(B,ce,Te,Re={}){const[ke,tt,ft]=ce;let lt=this.image_mean;Array.isArray(this.image_mean)||(lt=new Array(ft).fill(lt));let Ct=this.image_std;Array.isArray(Ct)||(Ct=new Array(ft).fill(lt));const gt=lt.map((ze,Rt)=>-ze/Ct[Rt]);return super.pad_image(B,ce,Te,{center:!0,constant_values:gt,...Re})}}class Et extends at{}class Fe extends F{async _call(B){const ce=await super._call(B),Te=[ce.pixel_values.dims[0],64,64],Re=new be.Tensor("int64",new BigInt64Array(Te.reduce((ke,tt)=>ke*tt)).fill(1n),Te);return{...ce,pixel_mask:Re}}post_process_object_detection(...B){return V(...B)}remove_low_and_no_objects(B,ce,Te,Re){let ke=[],tt=[],ft=[];for(let lt=0;ltTe&&(ke.push(gt),tt.push(Ot),ft.push(ze))}return[ke,tt,ft]}check_segment_validity(B,ce,Te,Re=.5,ke=.8){let tt=[],ft=0,lt=0;const Ct=ce[Te].data;for(let ze=0;ze=Re&&++lt;let gt=ft>0&<>0;return gt&&(gt=ft/lt>ke),[gt,tt]}compute_segments(B,ce,Te,Re,ke,tt=null,ft=null){let[lt,Ct]=ft??B[0].dims,gt=new be.Tensor("int32",new Int32Array(lt*Ct),[lt,Ct]),ze=[];if(ft!==null)for(let Ut=0;UtOt[rr]&&(Rt[rr]=Ut,Ot[rr]=ur[rr])}let Wt=0;const zt=gt.data;for(let Ut=0;UtRe!==ce.dims[ke]))throw Error(`The first ${Te.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new be.Tensor("int64",B.flat(1/0).map(BigInt),Te)}async _call(B,{input_points:ce=null,input_labels:Te=null,input_boxes:Re=null}={}){const ke=await super._call(B);if(ce&&(ke.input_points=this.reshape_input_points(ce,ke.original_sizes,ke.reshaped_input_sizes)),Te){if(!ke.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");ke.input_labels=this.add_input_labels(Te,ke.input_points)}return Re&&(ke.input_boxes=this.reshape_input_points(Re,ke.original_sizes,ke.reshaped_input_sizes,!0)),ke}async post_process_masks(B,ce,Te,{mask_threshold:Re=0,binarize:ke=!0,pad_size:tt=null}={}){const ft=[];tt=tt??this.pad_size;const lt=[tt.height,tt.width];for(let Ct=0;CtRe&&(Wt[zt]=1);Rt=new be.Tensor("bool",Wt,Rt.dims)}ft.push(Rt)}return ft}generate_crop_boxes(B,ce,{crop_n_layers:Te=0,overlap_ratio:Re=512/1500,points_per_crop:ke=32,crop_n_points_downscale_factor:tt=1}={}){}}class qe extends F{pad_image(B,ce,Te,Re={}){const[ke,tt,ft]=ce;return super.pad_image(B,ce,{width:tt+(Te-tt%Te)%Te,height:ke+(Te-ke%Te)%Te},{mode:"symmetric",center:!1,constant_values:-1,...Re})}}class je extends F{async _call(B,ce){Array.isArray(B)||(B=[B]),Array.isArray(ce)||(ce=[ce]);const Te=await Promise.all(B.map(tt=>this.preprocess(tt))),Re=await Promise.all(ce.map(tt=>this.preprocess(tt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,be.stack)(Te.map((tt,ft)=>(0,be.cat)([tt.pixel_values,Re[ft].pixel_values],0)),0),original_sizes:Te.map(tt=>tt.original_size),reshaped_input_sizes:Te.map(tt=>tt.reshaped_input_size)}}}class Ve extends _e{constructor(B){super(B),this.config.mel_filters??=(0,R.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,R.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(B){const ce=await(0,R.spectrogram)(B,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}),Te=ce.data,Re=(0,xe.max)(Te)[0];for(let ke=0;kethis.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`."),ce=B.slice(0,this.config.n_samples)):(ce=new Float32Array(this.config.n_samples),ce.set(B)),{input_features:(await this._extract_fbank_features(ce)).unsqueeze_(0)}}}class Ge extends _e{_zero_mean_unit_var_norm(B){const Te=B.reduce((ke,tt)=>ke+tt,0)/B.length,Re=B.reduce((ke,tt)=>ke+(tt-Te)**2,0)/B.length;return B.map(ke=>(ke-Te)/Math.sqrt(Re+1e-7))}async _call(B){K(B,"Wav2Vec2FeatureExtractor"),B instanceof Float64Array&&(B=new Float32Array(B));let ce=B;this.config.do_normalize&&(ce=this._zero_mean_unit_var_norm(ce));const Te=[1,ce.length];return{input_values:new be.Tensor("float32",ce,Te),attention_mask:new be.Tensor("int64",new BigInt64Array(ce.length).fill(1n),Te)}}}class ut extends _e{constructor(B){super(B);const ce=this.config.sampling_rate,Te=(0,R.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ce/2),ce,null,"kaldi",!0);for(let Re=0;ReTe*32768),(0,R.spectrogram)(B,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:ce,transpose:!0})}async _call(B,{padding:ce=!0,pad_to_multiple_of:Te=2,do_normalize_per_mel_bins:Re=!0,return_attention_mask:ke=!0}={}){K(B,"SeamlessM4TFeatureExtractor");let tt=await this._extract_fbank_features(B,this.config.max_length);if(Re){const[Wt,zt]=tt.dims,Ut=tt.data;for(let Ht=0;Ht0){const ur=new Float32Array(zt*(Wt+Ht));ur.set(Ut),ur.fill(this.config.padding_value,Ut.length);const rr=Wt+Ht;tt=new be.Tensor(tt.type,ur,[rr,zt]),ke&&(ft=new be.Tensor("int64",new BigInt64Array(rr),[1,rr]),ft.data.fill(1n,0,Wt))}}const[lt,Ct]=tt.dims,gt=this.config.stride;if(lt%gt!==0)throw new Error(`The number of frames (${lt}) must be a multiple of the stride (${gt}).`);const Rt=tt.view(1,Math.floor(lt/gt),Ct*gt),Ot={input_features:Rt};if(ke){const Wt=Rt.dims[1],zt=new BigInt64Array(Wt);if(ft){const Ut=ft.data;for(let Ht=1,ur=0;Ht0)if(Te==="rand_trunc"){const ft=Math.floor(Math.random()*(tt+1));B=B.subarray(ft,ft+ce),ke=await this._extract_fbank_features(B,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Te}" not implemented`);else{if(tt<0){let ft=new Float64Array(ce);if(ft.set(B),Re==="repeat")for(let lt=B.length;lt({id:lt,start:Ct*Te,end:gt*Te,confidence:ze/(gt-Ct)})))}return Re}}class M extends _e{constructor(B){super(B);const ce=this.config.sampling_rate,Te=(0,R.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ce/2),ce,null,"kaldi",!0);for(let Re=0;Rece*32768),(0,R.spectrogram)(B,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(B){K(B,"WeSpeakerFeatureExtractor");const ce=(await this._extract_fbank_features(B)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Te=ce.mean(1).data,Re=ce.data,[ke,tt,ft]=ce.dims;for(let lt=0;lt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(B){typeof B=="string"&&(B=[B]);const ce=[];for(const Te of B)if(this.task_prompts_without_inputs.has(Te))ce.push(this.task_prompts_without_inputs.get(Te));else{for(const[Re,ke]of this.task_prompts_with_input)if(Te.includes(Re)){ce.push(ke.replaceAll("{input}",Te).replaceAll(Re,""));break}ce.length!==B.length&&ce.push(Te)}return ce}post_process_generation(B,ce,Te){const Re=this.tasks_answer_post_processing_type.get(ce)??"pure_text";B=B.replaceAll("","").replaceAll("","");let ke;switch(Re){case"pure_text":ke=B;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const tt=Re==="ocr"?"quad_boxes":"bboxes",ft=B.matchAll(this.regexes[tt]),lt=[],Ct=[];for(const[gt,ze,...Rt]of ft)lt.push(ze?ze.trim():lt.at(-1)??""),Ct.push(Rt.map((Ot,Wt)=>(Number(Ot)+.5)/this.size_per_bin*Te[Wt%2]));ke={labels:lt,[tt]:Ct};break;default:throw new Error(`Task "${ce}" (of type "${Re}") not yet implemented.`)}return{[ce]:ke}}}class Bt{static FEATURE_EXTRACTOR_CLASS_MAPPING={ImageFeatureExtractor:F,WhisperFeatureExtractor:Ve,ViTFeatureExtractor:Ce,MobileViTFeatureExtractor:$e,MobileViTImageProcessor:X,MobileNetV1FeatureExtractor:dt,MobileNetV2FeatureExtractor:ge,MobileNetV3FeatureExtractor:U,MobileNetV4FeatureExtractor:de,OwlViTFeatureExtractor:Ue,Owlv2ImageProcessor:ct,CLIPFeatureExtractor:L,CLIPImageProcessor:C,Florence2Processor:pt,ChineseCLIPFeatureExtractor:me,SiglipImageProcessor:ye,ConvNextFeatureExtractor:Se,ConvNextImageProcessor:Pe,SegformerFeatureExtractor:se,SapiensFeatureExtractor:Q,BitImageProcessor:j,DPTImageProcessor:ie,DPTFeatureExtractor:le,GLPNFeatureExtractor:A,BeitFeatureExtractor:De,DeiTFeatureExtractor:ot,DetrFeatureExtractor:Fe,RTDetrImageProcessor:st,YolosFeatureExtractor:H,DonutFeatureExtractor:at,NougatImageProcessor:Et,EfficientNetImageProcessor:Xe,ViTImageProcessor:rt,VitMatteImageProcessor:je,SamImageProcessor:Ee,Swin2SRImageProcessor:qe,Wav2Vec2FeatureExtractor:Ge,SeamlessM4TFeatureExtractor:ut,SpeechT5FeatureExtractor:W,ASTFeatureExtractor:ht,ClapFeatureExtractor:Tt,PyAnnoteFeatureExtractor:St,WeSpeakerFeatureExtractor:M};static PROCESSOR_CLASS_MAPPING={WhisperProcessor:pe,Wav2Vec2ProcessorWithLM:Je,PyAnnoteProcessor:He,SamProcessor:te,SpeechT5Processor:Mt,OwlViTProcessor:nt,Florence2Processor:pt};static async from_pretrained(B,{progress_callback:ce=null,config:Te=null,cache_dir:Re=null,local_files_only:ke=!1,revision:tt="main"}={}){let ft=Te??await(0,he.getModelJSON)(B,"preprocessor_config.json",!0,{progress_callback:ce,config:Te,cache_dir:Re,local_files_only:ke,revision:tt}),lt=ft.feature_extractor_type??ft.image_processor_type,Ct=this.FEATURE_EXTRACTOR_CLASS_MAPPING[lt];if(!Ct)if(ft.size!==void 0)console.warn(`Feature extractor type "${lt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Ct=F;else throw new Error(`Unknown Feature Extractor type: ${lt}`);let gt=this.PROCESSOR_CLASS_MAPPING[ft.processor_class]??E,ze=new Ct(ft);return new gt(ze)}}},"./src/tokenizers.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{AlbertTokenizer:()=>Ot,AutoTokenizer:()=>wn,BartTokenizer:()=>Hr,BertTokenizer:()=>Rt,BlenderbotSmallTokenizer:()=>Ts,BlenderbotTokenizer:()=>us,BloomTokenizer:()=>Lr,CLIPTokenizer:()=>Kt,CamembertTokenizer:()=>yt,CodeGenTokenizer:()=>ls,CodeLlamaTokenizer:()=>Us,CohereTokenizer:()=>Nr,ConvBertTokenizer:()=>rr,DebertaTokenizer:()=>Ut,DebertaV2Tokenizer:()=>Ht,DistilBertTokenizer:()=>Qe,ElectraTokenizer:()=>Zr,EsmTokenizer:()=>Un,FalconTokenizer:()=>bs,GPT2Tokenizer:()=>is,GPTNeoXTokenizer:()=>Ms,GemmaTokenizer:()=>as,Grok1Tokenizer:()=>Cn,HerbertTokenizer:()=>ur,LlamaTokenizer:()=>In,M2M100Tokenizer:()=>Yn,MBart50Tokenizer:()=>Xr,MBartTokenizer:()=>pn,MPNetTokenizer:()=>ys,MarianTokenizer:()=>vs,MobileBertTokenizer:()=>Wt,NllbTokenizer:()=>Fn,NougatTokenizer:()=>ds,PreTrainedTokenizer:()=>ze,Qwen2Tokenizer:()=>Ws,RoFormerTokenizer:()=>wr,RobertaTokenizer:()=>Qn,SiglipTokenizer:()=>Zn,SpeechT5Tokenizer:()=>Ss,SqueezeBertTokenizer:()=>zt,T5Tokenizer:()=>Xn,TokenizerModel:()=>Se,VitsTokenizer:()=>$s,Wav2Vec2CTCTokenizer:()=>xs,WhisperTokenizer:()=>os,XLMRobertaTokenizer:()=>ws,XLMTokenizer:()=>Ft,is_chinese_char:()=>ie});var I=N("./src/utils/generic.js"),ae=N("./src/utils/core.js"),he=N("./src/utils/hub.js"),xe=N("./src/utils/maths.js"),be=N("./src/utils/tensor.js"),R=N("./src/utils/data-structures.js"),$=N("./node_modules/@huggingface/jinja/dist/index.js"),V=N("./src/models/whisper/common_whisper.js"),P=N("./src/utils/constants.js");async function K(we,m){const z=await Promise.all([(0,he.getModelJSON)(we,"tokenizer.json",!0,m),(0,he.getModelJSON)(we,"tokenizer_config.json",!0,m)]);return m.legacy!==null&&(z[1].legacy=m.legacy),z}function ne(we,m){const z=[];let Y=0;for(const J of we.matchAll(m)){const ve=J[0];Y0&&z.push(ve),Y=J.index+ve.length}return Y=19968&&we<=40959||we>=13312&&we<=19903||we>=131072&&we<=173791||we>=173824&&we<=177983||we>=177984&&we<=178207||we>=178208&&we<=183983||we>=63744&&we<=64255||we>=194560&&we<=195103}function j(we,m,z){const Y=[];let J=0;for(;Jthis.tokens_to_ids.get(z)??this.unk_token_id)}convert_ids_to_tokens(m){return m.map(z=>this.vocab[z]??this.unk_token)}}class Pe extends Se{constructor(m){super(m),this.tokens_to_ids=_e(m.vocab),this.unk_token_id=this.tokens_to_ids.get(m.unk_token),this.unk_token=m.unk_token,this.max_input_chars_per_word=m.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[z,Y]of this.tokens_to_ids)this.vocab[Y]=z}encode(m){const z=[];for(const Y of m){const J=[...Y];if(J.length>this.max_input_chars_per_word){z.push(this.unk_token);continue}let ve=!1,Be=0;const xt=[];for(;Be0&&(bt=this.config.continuing_subword_prefix+bt),this.tokens_to_ids.has(bt)){kt=bt;break}--vt}if(kt===null){ve=!0;break}xt.push(kt),Be=vt}ve?z.push(this.unk_token):z.push(...xt)}return z}}class Ce extends Se{constructor(m,z){super(m);const Y=m.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let J=0;J[J,ve])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=z.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,xe.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new R.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(m){const z=m.sentence,Y=z.length;let J=0;for(;J{const we=[...Array.from({length:94},(J,ve)=>ve+33),...Array.from({length:12},(J,ve)=>ve+161),...Array.from({length:82},(J,ve)=>ve+174)],m=we.slice();let z=0;for(let J=0;J<256;++J)we.includes(J)||(we.push(J),m.push(256+z),z+=1);const Y=m.map(J=>String.fromCharCode(J));return Object.fromEntries(we.map((J,ve)=>[J,Y[ve]]))})(),Xe=(0,ae.reverseDictionary)(rt);class dt extends Se{constructor(m){super(m),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=_e(m.vocab),this.unk_token_id=this.tokens_to_ids.get(m.unk_token),this.unk_token=m.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[z,Y]of this.tokens_to_ids)this.vocab[Y]=z;this.bpe_ranks=new Map(m.merges.map((z,Y)=>[z,Y])),this.merges=m.merges.map(z=>z.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=m.end_of_word_suffix,this.continuing_subword_suffix=m.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(m){if(m.length===0)return[];const z=this.cache.get(m);if(z!==void 0)return z;const Y=Array.from(m);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let J=[];if(Y.length>1){const ve=new R.PriorityQueue((vt,kt)=>vt.score`<0x${Be.toString(16).toUpperCase().padStart(2,"0")}>`)):z.push(this.unk_token)}return z}}class ge extends Se{constructor(m,z){super(m),this.tokens_to_ids=_e(z.target_lang?m.vocab[z.target_lang]:m.vocab),this.bos_token=z.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=z.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=z.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=z.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[Y,J]of this.tokens_to_ids)this.vocab[J]=Y}encode(m){return m}}class U extends I.Callable{constructor(m){super(),this.config=m}static fromConfig(m){if(m===null)return null;switch(m.type){case"BertNormalizer":return new Et(m);case"Precompiled":return new Te(m);case"Sequence":return new at(m);case"Replace":return new de(m);case"NFC":return new $e(m);case"NFKC":return new X(m);case"NFKD":return new Ue(m);case"Strip":return new ct(m);case"StripAccents":return new st(m);case"Lowercase":return new ot(m);case"Prepend":return new De(m);default:throw new Error(`Unknown Normalizer type: ${m.type}`)}}normalize(m){throw Error("normalize should be implemented in subclass.")}_call(m){return this.normalize(m)}}class de extends U{normalize(m){const z=oe(this.config.pattern);return z===null?m:m.replaceAll(z,this.config.content)}}class $e extends U{normalize(m){return m=m.normalize("NFC"),m}}class X extends U{normalize(m){return m=m.normalize("NFKC"),m}}class Ue extends U{normalize(m){return m=m.normalize("NFKD"),m}}class ct extends U{normalize(m){return this.config.strip_left&&this.config.strip_right?m=m.trim():(this.config.strip_left&&(m=m.trimStart()),this.config.strip_right&&(m=m.trimEnd())),m}}class st extends U{normalize(m){return m=se(m),m}}class ot extends U{normalize(m){return m=m.toLowerCase(),m}}class De extends U{normalize(m){return m=this.config.prepend+m,m}}class at extends U{constructor(m){super(m),this.normalizers=m.normalizers.map(z=>U.fromConfig(z))}normalize(m){return this.normalizers.reduce((z,Y)=>Y.normalize(z),m)}}class Et extends U{_tokenize_chinese_chars(m){const z=[];for(let Y=0;Ythis.pre_tokenize_text(Y,z)):this.pre_tokenize_text(m,z)).flat()}_call(m,z){return this.pre_tokenize(m,z)}}class H extends Fe{constructor(m){super(),this.pattern=new RegExp(`[^\\s${L}]+|[${L}]`,"gu")}pre_tokenize_text(m,z){return m.trim().match(this.pattern)||[]}}class Ee extends Fe{constructor(m){super(),this.config=m,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=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=rt,this.text_encoder=new TextEncoder}pre_tokenize_text(m,z){return this.add_prefix_space&&!m.startsWith(" ")&&(m=" "+m),(this.use_regex?m.match(this.pattern)||[]:[m]).map(J=>Array.from(this.text_encoder.encode(J),ve=>this.byte_encoder[ve]).join(""))}}class qe extends Fe{constructor(m){super(),this.config=m,this.pattern=oe(this.config.pattern,this.config.invert)}pre_tokenize_text(m,z){return this.pattern===null?[]:this.config.invert?m.match(this.pattern)||[]:ne(m,this.pattern)}}class je extends Fe{constructor(m){super(),this.config=m,this.pattern=new RegExp(`[^${L}]+|[${L}]+`,"gu")}pre_tokenize_text(m,z){return m.match(this.pattern)||[]}}class Ve extends Fe{constructor(m){super(),this.config=m;const z=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(z,"gu")}pre_tokenize_text(m,z){return m.match(this.pattern)||[]}}class Ge extends I.Callable{constructor(m){super(),this.config=m}static fromConfig(m){if(m===null)return null;switch(m.type){case"TemplateProcessing":return new Tt(m);case"ByteLevel":return new St(m);case"RobertaProcessing":return new ht(m);case"BertProcessing":return new ut(m);case"Sequence":return new M(m);default:throw new Error(`Unknown PostProcessor type: ${m.type}`)}}post_process(m,...z){throw Error("post_process should be implemented in subclass.")}_call(m,...z){return this.post_process(m,...z)}}class ut extends Ge{constructor(m){super(m),this.cls=m.cls[0],this.sep=m.sep[0]}post_process(m,z=null,{add_special_tokens:Y=!0}={}){Y&&(m=(0,ae.mergeArrays)([this.cls],m,[this.sep]));let J=new Array(m.length).fill(0);if(z!==null){const ve=Y&&this instanceof ht?[this.sep]:[],Be=Y?[this.sep]:[];m=(0,ae.mergeArrays)(m,ve,z,Be),J=(0,ae.mergeArrays)(J,new Array(z.length+ve.length+Be.length).fill(1))}return{tokens:m,token_type_ids:J}}}class ht extends ut{}class Tt extends Ge{constructor(m){super(m),this.single=m.single,this.pair=m.pair}post_process(m,z=null,{add_special_tokens:Y=!0}={}){const J=z===null?this.single:this.pair;let ve=[],Be=[];for(const xt of J)"SpecialToken"in xt?Y&&(ve.push(xt.SpecialToken.id),Be.push(xt.SpecialToken.type_id)):"Sequence"in xt&&(xt.Sequence.id==="A"?(ve=(0,ae.mergeArrays)(ve,m),Be=(0,ae.mergeArrays)(Be,new Array(m.length).fill(xt.Sequence.type_id))):xt.Sequence.id==="B"&&(ve=(0,ae.mergeArrays)(ve,z),Be=(0,ae.mergeArrays)(Be,new Array(z.length).fill(xt.Sequence.type_id))));return{tokens:ve,token_type_ids:Be}}}class St extends Ge{post_process(m,z=null){return z&&(m=(0,ae.mergeArrays)(m,z)),{tokens:m}}}class M extends Ge{constructor(m){super(m),this.processors=m.processors.map(z=>Ge.fromConfig(z))}post_process(m,z=null,Y={}){let J;for(const ve of this.processors)if(ve instanceof St)m=ve.post_process(m).tokens,z&&(z=ve.post_process(z).tokens);else{const Be=ve.post_process(m,z,Y);m=Be.tokens,J=Be.token_type_ids}return{tokens:m,token_type_ids:J}}}class W extends I.Callable{constructor(m){super(),this.config=m,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=m.trim_offsets}static fromConfig(m){if(m===null)return null;switch(m.type){case"WordPiece":return new He(m);case"Metaspace":return new ce(m);case"ByteLevel":return new Mt(m);case"Replace":return new E(m);case"ByteFallback":return new te(m);case"Fuse":return new pe(m);case"Strip":return new Je(m);case"Sequence":return new pt(m);case"CTC":return new nt(m);case"BPEDecoder":return new Bt(m);default:throw new Error(`Unknown Decoder type: ${m.type}`)}}_call(m){return this.decode(m)}decode(m){return this.decode_chain(m).join("")}decode_chain(m){throw Error("`decode_chain` should be implemented in subclass.")}}class E extends W{decode_chain(m){const z=oe(this.config.pattern);return z===null?m:m.map(Y=>Y.replaceAll(z,this.config.content))}}class te extends W{constructor(m){super(m),this.text_decoder=new TextDecoder}decode_chain(m){const z=[];let Y=[];for(const J of m){let ve=null;if(J.length===6&&J.startsWith("<0x")&&J.endsWith(">")){const Be=parseInt(J.slice(3,5),16);isNaN(Be)||(ve=Be)}if(ve!==null)Y.push(ve);else{if(Y.length>0){const Be=this.text_decoder.decode(Uint8Array.from(Y));z.push(Be),Y=[]}z.push(J)}}if(Y.length>0){const J=this.text_decoder.decode(Uint8Array.from(Y));z.push(J),Y=[]}return z}}class pe extends W{decode_chain(m){return[m.join("")]}}class Je extends W{constructor(m){super(m),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(m){return m.map(z=>{let Y=0;for(let ve=0;ve(Y!==0&&(z.startsWith(this.config.prefix)?z=z.replace(this.config.prefix,""):z=" "+z),this.cleanup&&(z=Q(z)),z))}}class Mt extends W{constructor(m){super(m),this.byte_decoder=Xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(m){const z=m.join(""),Y=new Uint8Array([...z].map(ve=>this.byte_decoder[ve]));return this.text_decoder.decode(Y)}decode_chain(m){const z=[];let Y=[];for(const J of m)this.added_tokens.find(ve=>ve.content===J)!==void 0?(Y.length>0&&(z.push(this.convert_tokens_to_string(Y)),Y=[]),z.push(J)):Y.push(J);return Y.length>0&&z.push(this.convert_tokens_to_string(Y)),z}}class nt extends W{constructor(m){super(m),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(m){if(m.length===0)return"";const z=[m[0]];for(let ve=1;veve!==this.pad_token).join("");return this.cleanup&&(J=Q(J).replaceAll(this.word_delimiter_token," ").trim()),J}decode_chain(m){return[this.convert_tokens_to_string(m)]}}class pt extends W{constructor(m){super(m),this.decoders=m.decoders.map(z=>W.fromConfig(z))}decode_chain(m){return this.decoders.reduce((z,Y)=>Y.decode_chain(z),m)}}class Bt extends W{constructor(m){super(m),this.suffix=this.config.suffix}decode_chain(m){return m.map((z,Y)=>z.replaceAll(this.suffix,Y===m.length-1?"":" "))}}class et extends W{decode_chain(m){let z="";for(let Y=1;YY.normalize("NFKC")).join("~"):m=m.normalize("NFKC"),m}}class Re extends Fe{constructor(m){super(),this.tokenizers=m.pretokenizers.map(z=>Fe.fromConfig(z))}pre_tokenize_text(m,z){return this.tokenizers.reduce((Y,J)=>J.pre_tokenize(Y,z),[m])}}class ke extends Fe{constructor(m){super()}pre_tokenize_text(m,z){return m.match(/\w+|[^\w\s]+/g)||[]}}class tt extends Fe{constructor(m){super()}pre_tokenize_text(m,z){return A(m)}}class ft extends Fe{constructor(m){super(),this.config=m,this.pattern=oe(this.config.pattern),this.content=this.config.content}pre_tokenize_text(m,z){return this.pattern===null?[m]:[m.replaceAll(this.pattern,this.config.content)]}}const lt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ct(we,m,z,Y){for(const J of Object.keys(we)){const ve=m-we[J].length,Be=z(J),xt=new Array(ve).fill(Be);we[J]=Y==="right"?(0,ae.mergeArrays)(we[J],xt):(0,ae.mergeArrays)(xt,we[J])}}function gt(we,m){for(const z of Object.keys(we))we[z].length=m}class ze extends I.Callable{return_token_type_ids=!1;padding_side="right";constructor(m,z){super(),this._tokenizer_config=z,this.normalizer=U.fromConfig(m.normalizer),this.pre_tokenizer=Fe.fromConfig(m.pre_tokenizer),this.model=Se.fromConfig(m.model,z),this.post_processor=Ge.fromConfig(m.post_processor),this.decoder=W.fromConfig(m.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Y of m.added_tokens){const J=new ye(Y);this.added_tokens.push(J),this.model.tokens_to_ids.set(J.content,J.id),this.model.vocab[J.id]=J.content,J.special&&(this.special_tokens.push(J.content),this.all_special_ids.push(J.id))}if(this.additional_special_tokens=z.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.toSorted((Y,J)=>J.content.length-Y.content.length).map(Y=>`${Y.lstrip?"\\s*":""}(${(0,ae.escapeRegExp)(Y.content)})${Y.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.model_max_length=z.model_max_length,this.remove_space=z.remove_space,this.clean_up_tokenization_spaces=z.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=z.do_lowercase_and_remove_accent??!1,z.padding_side&&(this.padding_side=z.padding_side),this.legacy=!1,this.chat_template=z.chat_template??null,Array.isArray(this.chat_template)){const Y=Object.create(null);for(const{name:J,template:ve}of this.chat_template){if(typeof J!="string"||typeof ve!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Y[J]=ve}this.chat_template=Y}this._compiled_template_cache=new Map}getToken(...m){for(const z of m){const Y=this._tokenizer_config[z];if(Y)if(typeof Y=="object"){if(Y.__type==="AddedToken")return Y.content;throw Error(`Unknown token: ${Y}`)}else return Y}return null}static async from_pretrained(m,{progress_callback:z=null,config:Y=null,cache_dir:J=null,local_files_only:ve=!1,revision:Be="main",legacy:xt=null}={}){const vt=await K(m,{progress_callback:z,config:Y,cache_dir:J,local_files_only:ve,revision:Be,legacy:xt});return new this(...vt)}_call(m,{text_pair:z=null,add_special_tokens:Y=!0,padding:J=!1,truncation:ve=null,max_length:Be=null,return_tensor:xt=!0,return_token_type_ids:vt=null}={}){const kt=Array.isArray(m);let bt;if(kt){if(m.length===0)throw Error("text array must be non-empty");if(z!==null){if(Array.isArray(z)){if(m.length!==z.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");bt=m.map((or,yr)=>this._encode_plus(or,{text_pair:z[yr],add_special_tokens:Y,return_token_type_ids:vt}))}else bt=m.map(or=>this._encode_plus(or,{add_special_tokens:Y,return_token_type_ids:vt}))}else{if(m==null)throw Error("text may not be null or undefined");if(Array.isArray(z))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");bt=[this._encode_plus(m,{text_pair:z,add_special_tokens:Y,return_token_type_ids:vt})]}if(Be===null?J==="max_length"?Be=this.model_max_length:Be=(0,xe.max)(bt.map(or=>or.input_ids.length))[0]:ve||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."),Be=Math.min(Be,this.model_max_length??1/0),J||ve)for(let or=0;orBe?ve&>(bt[or],Be):J&&Ct(bt[or],Be,yr=>yr==="input_ids"?this.pad_token_id:0,this.padding_side));const fr={};if(xt){if(!(J&&ve)&&bt.some(yr=>{for(const qt of Object.keys(yr))if(yr[qt].length!==bt[0][qt]?.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 or=[bt.length,bt[0].input_ids.length];for(const yr of Object.keys(bt[0]))fr[yr]=new be.Tensor("int64",BigInt64Array.from(bt.flatMap(qt=>qt[yr]).map(BigInt)),or)}else{for(const or of Object.keys(bt[0]))fr[or]=bt.map(yr=>yr[or]);if(!kt)for(const or of Object.keys(fr))fr[or]=fr[or][0]}return fr}_encode_text(m){return m===null?null:(this.added_tokens_regex?m.split(this.added_tokens_regex).filter(J=>J):[m]).map((J,ve)=>{if(this.added_tokens.find(xt=>xt.content===J)!==void 0)return J;{if(this.remove_space===!0&&(J=J.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(J=le(J)),this.normalizer!==null&&(J=this.normalizer(J)),J.length===0)return[];const xt=this.pre_tokenizer!==null?this.pre_tokenizer(J,{section_index:ve}):[J];return this.model(xt)}}).flat()}_encode_plus(m,{text_pair:z=null,add_special_tokens:Y=!0,return_token_type_ids:J=null}={}){const{tokens:ve,token_type_ids:Be}=this._tokenize_helper(m,{pair:z,add_special_tokens:Y}),xt=this.model.convert_tokens_to_ids(ve),vt={input_ids:xt,attention_mask:new Array(xt.length).fill(1)};return(J??this.return_token_type_ids)&&Be&&(vt.token_type_ids=Be),vt}_tokenize_helper(m,{pair:z=null,add_special_tokens:Y=!1}={}){const J=this._encode_text(m),ve=this._encode_text(z);return this.post_processor?this.post_processor(J,ve,{add_special_tokens:Y}):{tokens:(0,ae.mergeArrays)(J??[],ve??[])}}tokenize(m,{pair:z=null,add_special_tokens:Y=!1}={}){return this._tokenize_helper(m,{pair:z,add_special_tokens:Y}).tokens}encode(m,{text_pair:z=null,add_special_tokens:Y=!0,return_token_type_ids:J=null}={}){return this._encode_plus(m,{text_pair:z,add_special_tokens:Y,return_token_type_ids:J}).input_ids}batch_decode(m,z={}){return m instanceof be.Tensor&&(m=m.tolist()),m.map(Y=>this.decode(Y,z))}decode(m,z={}){if(m instanceof be.Tensor&&(m=F(m)),!Array.isArray(m)||m.length===0||!(0,ae.isIntegralNumber)(m[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(m,z)}decode_single(m,{skip_special_tokens:z=!1,clean_up_tokenization_spaces:Y=null}){let J=this.model.convert_ids_to_tokens(m);z&&(J=J.filter(Be=>!this.special_tokens.includes(Be)));let ve=this.decoder?this.decoder(J):J.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ve=ve.replaceAll(this.decoder.end_of_word_suffix," "),z&&(ve=ve.trim())),(Y??this.clean_up_tokenization_spaces)&&(ve=Q(ve)),ve}apply_chat_template(m,{tools:z=null,documents:Y=null,chat_template:J=null,add_generation_prompt:ve=!1,tokenize:Be=!0,padding:xt=!1,truncation:vt=!1,max_length:kt=null,return_tensor:bt=!0,return_dict:fr=!1,tokenizer_kwargs:or={},...yr}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const Rr=this.chat_template;if(J!==null&&Object.hasOwn(Rr,J))J=Rr[J];else if(J===null&&"default"in Rr)J=Rr.default;else if(J===null)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(Rr).sort()}.`)}else if(this.chat_template)J=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");if(typeof J!="string")throw Error(`chat_template must be a string, but got ${typeof J}`);let qt=this._compiled_template_cache.get(J);qt===void 0&&(qt=new $.Template(J),this._compiled_template_cache.set(J,qt));const Cr=Object.create(null);for(const Rr of lt){const Ie=this.getToken(Rr);Ie&&(Cr[Rr]=Ie)}const yn=qt.render({messages:m,add_generation_prompt:ve,tools:z,documents:Y,...Cr,...yr});if(Be){const Rr=this._call(yn,{add_special_tokens:!1,padding:xt,truncation:vt,max_length:kt,return_tensor:bt,...or});return fr?Rr:Rr.input_ids}return yn}}class Rt extends ze{return_token_type_ids=!0}class Ot extends ze{return_token_type_ids=!0}class Wt extends ze{return_token_type_ids=!0}class zt extends ze{return_token_type_ids=!0}class Ut extends ze{return_token_type_ids=!0}class Ht extends ze{return_token_type_ids=!0}class ur extends ze{return_token_type_ids=!0}class rr extends ze{return_token_type_ids=!0}class wr extends ze{return_token_type_ids=!0}class Qe extends ze{}class yt extends ze{}class Ft extends ze{return_token_type_ids=!0;constructor(m,z){super(m,z),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Zr extends ze{return_token_type_ids=!0}class Xn extends ze{}class is extends ze{}class Hr extends ze{}class pn extends ze{constructor(m,z){super(m,z),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(m,z,Y){return Wn(this,m,z,Y)}}class Xr extends pn{}class Qn extends ze{}class Lr extends ze{constructor(m,z){const Y=".,!?…。,、।۔،",J=m.pre_tokenizer?.pretokenizers[0]?.pattern;J&&J.Regex===` ?[^(\\s|[${Y}])]+`&&(J.Regex=` ?[^\\s${Y}]+`),super(m,z)}}const Vn="▁";class In extends ze{padding_side="left";constructor(m,z){super(m,z),this.legacy=z.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new B({replacement:Vn,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(m){if(m===null)return null;if(this.legacy||m.length===0)return super._encode_text(m);let z=super._encode_text(Vn+m.replaceAll(Vn," "));return z.length>1&&z[0]===Vn&&this.special_tokens.includes(z[1])&&(z=z.slice(1)),z}}class Us extends ze{}class ws extends ze{}class ys extends ze{}class bs extends ze{}class Ms extends ze{}class Un extends ze{}class Ws extends ze{}class as extends ze{}class Cn extends ze{}function Wn(we,m,z,Y){if(!("language_codes"in we)||!Array.isArray(we.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in we)||!(we.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in we)||typeof we.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const J=Y.src_lang,ve=Y.tgt_lang;if(!we.language_codes.includes(ve))throw new Error(`Target language code "${ve}" is not valid. Must be one of: {${we.language_codes.join(", ")}}`);if(J!==void 0){if(!we.language_codes.includes(J))throw new Error(`Source language code "${J}" is not valid. Must be one of: {${we.language_codes.join(", ")}}`);for(const Be of we.post_processor.config.single)if("SpecialToken"in Be&&we.languageRegex.test(Be.SpecialToken.id)){Be.SpecialToken.id=we.lang_to_token(J);break}}return Y.forced_bos_token_id=we.model.convert_tokens_to_ids([we.lang_to_token(ve)])[0],we._call(m,z)}class Fn extends ze{constructor(m,z){super(m,z),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(m,z,Y){return Wn(this,m,z,Y)}}class Yn extends ze{constructor(m,z){super(m,z),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)).map(Y=>Y.slice(2,-2)),this.lang_to_token=Y=>`__${Y}__`}_build_translation_inputs(m,z,Y){return Wn(this,m,z,Y)}}class os extends ze{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(m,{return_timestamps:z=!1,return_language:Y=!1,time_precision:J=null,force_full_sequences:ve=!0}={}){if(J===null)throw Error("Must specify time_precision");let Be=null;const xt=z==="word";function vt(){return{language:Be,timestamp:[null,null],text:""}}const kt=[];let bt=vt(),fr=0;const or=this.timestamp_begin;let yr=[],qt=[],Cr=!1,yn=null;const Rr=new Set(this.all_special_ids);for(const xr of m){const Jr=xr.tokens,dn=xt?xr.token_timestamps:null;let Xt=null,hn=or;if("stride"in xr){const[Tr,Pt,Sr]=xr.stride;if(fr-=Pt,yn=Tr-Sr,Pt&&(hn=Pt/J+or),Sr)for(let Fr=Jr.length-1;Fr>=0;--Fr){const jr=Number(Jr[Fr]);if(jr>=or){if(Xt!==null&&(jr-or)*J=or){const Sr=(Pt-or)*J+fr,Fr=(0,xe.round)(Sr,2);if(Xt!==null&&Pt>=Xt)Cr=!0;else if(Cr||yr.length>0&&Pt0?(yr.push(sn),xt&&qt.push(Er)):yr.every(Tr=>Tr.length===0)&&(bt=vt(),yr=[],sn=[],qt=[],Er=[])}if(yr.length>0){if(ve&&z)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[xr,Jr]=this.findLongestCommonSequence(yr,qt),dn=this.decode(xr);bt.text=dn,xt&&(bt.words=this.collateWordTimestamps(xr,Jr,Be)),kt.push(bt)}let Ie=Object.create(null);const On=kt.map(xr=>xr.text).join("");if(z||Y){for(let xr=0;xr0;let xt=Be?[]:null,vt=Be?z[0]:null;for(let kt=1;ktFr===Er[jr]&&vt[Jr+jr]<=z[kt][hn+jr]).length:Tr=Xt.filter((Fr,jr)=>Fr===Er[jr]).length;const Pt=xr/1e4,Sr=Tr/xr+Pt;Tr>1&&Sr>fr&&(fr=Sr,or=[Jr,dn,hn,sn])}const[qt,Cr,yn,Rr]=or,Ie=Math.floor((Cr+qt)/2),On=Math.floor((Rr+yn)/2);ve.push(...Y.slice(0,Ie)),Y=bt.slice(On),J=Y.length,Be&&(xt.push(...vt.slice(0,Ie)),vt=z[kt].slice(On))}return ve.push(...Y),Be?(xt.push(...vt),[ve,xt]):[ve,[]]}collateWordTimestamps(m,z,Y){const[J,ve,Be]=this.combineTokensIntoWords(m,Y),xt=[];for(let vt=0;vt=J){const xt=((Be-J)*Y).toFixed(2);ve.push(`<|${xt}|>`),ve.push([])}else ve[ve.length-1].push(Be);return ve=ve.map(Be=>typeof Be=="string"?Be:super.decode(Be,z)),ve.join("")}splitTokensOnUnicode(m){const z=this.decode(m,{decode_with_timestamps:!0}),Y="�",J=[],ve=[],Be=[];let xt=[],vt=[],kt=0;for(let bt=0;bt=this.model.tokens_to_ids.get("<|endoftext|>"),qt=bt.startsWith(" "),Cr=bt.trim(),yn=vt.test(Cr);if(yr||qt||yn||ve.length===0)ve.push(bt),Be.push(fr),xt.push(or);else{const Rr=ve.length-1;ve[Rr]+=bt,Be[Rr].push(...fr),xt[Rr].push(...or)}}return[ve,Be,xt]}mergePunctuations(m,z,Y,J,ve){const Be=structuredClone(m),xt=structuredClone(z),vt=structuredClone(Y);let kt=Be.length-2,bt=Be.length-1;for(;kt>=0;)Be[kt].startsWith(" ")&&J.includes(Be[kt].trim())?(Be[bt]=Be[kt]+Be[bt],xt[bt]=(0,ae.mergeArrays)(xt[kt],xt[bt]),vt[bt]=(0,ae.mergeArrays)(vt[kt],vt[bt]),Be[kt]="",xt[kt]=[],vt[kt]=[]):bt=kt,--kt;for(kt=0,bt=1;btfr),xt.filter(fr=>fr.length>0),vt.filter(fr=>fr.length>0)]}get_decoder_prompt_ids({language:m=null,task:z=null,no_timestamps:Y=!0}={}){const J=[];if(m){const ve=(0,V.whisper_language_to_code)(m),Be=this.model.tokens_to_ids.get(`<|${ve}|>`);if(Be===void 0)throw new Error(`Unable to find language "${ve}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);J.push(Be)}else J.push(null);if(z){if(z=z.toLowerCase(),z!=="transcribe"&&z!=="translate")throw new Error(`Task "${z}" is not supported. Must be one of: ["transcribe", "translate"]`);const ve=this.model.tokens_to_ids.get(`<|${z}|>`);if(ve===void 0)throw new Error(`Unable to find task "${z}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);J.push(ve)}else J.push(null);if(Y){const ve=this.model.tokens_to_ids.get("<|notimestamps|>");if(ve===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);J.push(ve)}return J.map((ve,Be)=>[Be+1,ve]).filter(ve=>ve[1]!==null)}}class ls extends ze{}class Kt extends ze{}class Zn extends ze{}class vs extends ze{constructor(m,z){super(m,z),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Y=>this.languageRegex.test(Y)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(m){if(m===null)return null;const[z,...Y]=m.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(z);if(Y.length===2){const[J,ve]=Y;return this.supported_language_codes.includes(J)||console.warn(`Unsupported language code "${J}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,ae.mergeArrays)([J],super._encode_text(ve))}}}class xs extends ze{}class us extends ze{}class Ts extends ze{}class Ss extends ze{}class ds extends ze{}class $s extends ze{constructor(m,z){super(m,z),this.decoder=new et({})}}class Nr extends ze{}class wn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:Xn,DistilBertTokenizer:Qe,CamembertTokenizer:yt,DebertaTokenizer:Ut,DebertaV2Tokenizer:Ht,BertTokenizer:Rt,HerbertTokenizer:ur,ConvBertTokenizer:rr,RoFormerTokenizer:wr,XLMTokenizer:Ft,ElectraTokenizer:Zr,MobileBertTokenizer:Wt,SqueezeBertTokenizer:zt,AlbertTokenizer:Ot,GPT2Tokenizer:is,BartTokenizer:Hr,MBartTokenizer:pn,MBart50Tokenizer:Xr,RobertaTokenizer:Qn,WhisperTokenizer:os,CodeGenTokenizer:ls,CLIPTokenizer:Kt,SiglipTokenizer:Zn,MarianTokenizer:vs,BloomTokenizer:Lr,NllbTokenizer:Fn,M2M100Tokenizer:Yn,LlamaTokenizer:In,CodeLlamaTokenizer:Us,XLMRobertaTokenizer:ws,MPNetTokenizer:ys,FalconTokenizer:bs,GPTNeoXTokenizer:Ms,EsmTokenizer:Un,Wav2Vec2CTCTokenizer:xs,BlenderbotTokenizer:us,BlenderbotSmallTokenizer:Ts,SpeechT5Tokenizer:Ss,NougatTokenizer:ds,VitsTokenizer:$s,Qwen2Tokenizer:Ws,GemmaTokenizer:as,Grok1Tokenizer:Cn,CohereTokenizer:Nr,PreTrainedTokenizer:ze};static async from_pretrained(m,{progress_callback:z=null,config:Y=null,cache_dir:J=null,local_files_only:ve=!1,revision:Be="main",legacy:xt=null}={}){const[vt,kt]=await K(m,{progress_callback:z,config:Y,cache_dir:J,local_files_only:ve,revision:Be,legacy:xt}),bt=kt.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let fr=this.TOKENIZER_CLASS_MAPPING[bt];return fr||(console.warn(`Unknown tokenizer class "${bt}", attempting to construct from base class.`),fr=ze),new fr(vt,kt)}}},"./src/utils/audio.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{hamming:()=>V,hanning:()=>$,mel_filter_bank:()=>Q,read_audio:()=>be,spectrogram:()=>A,window_function:()=>L});var I=N("./src/utils/hub.js"),ae=N("./src/utils/maths.js"),he=N("./src/utils/core.js"),xe=N("./src/utils/tensor.js");async function be(C,me){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 ye=await(await(0,I.getFile)(C)).arrayBuffer(),Se=new AudioContext({sampleRate:me});typeof me>"u"&&console.warn(`No sampling rate provided, using default of ${Se.sampleRate}Hz.`);const Pe=await Se.decodeAudioData(ye);let Ce;if(Pe.numberOfChannels===2){const rt=Math.sqrt(2),Xe=Pe.getChannelData(0),dt=Pe.getChannelData(1);Ce=new Float32Array(Xe.length);for(let ge=0;ge2595*Math.log10(1+C/700),kaldi:C=>1127*Math.log(1+C/700),slaney:(C,me=1e3,ye=15,Se=27/Math.log(6.4))=>C>=me?ye+Math.log(C/me)*Se:3*C/200};function K(C,me="htk"){const ye=P[me];if(!ye)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof C=="number"?ye(C):C.map(Se=>ye(Se))}const ne={htk:C=>700*(10**(C/2595)-1),kaldi:C=>700*(Math.exp(C/1127)-1),slaney:(C,me=1e3,ye=15,Se=Math.log(6.4)/27)=>C>=ye?me*Math.exp(Se*(C-ye)):200*C/3};function oe(C,me="htk"){const ye=ne[me];if(!ye)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof C=="number"?ye(C):C.map(Se=>ye(Se))}function _e(C,me){const ye=Float64Array.from({length:me.length-1},(rt,Xe)=>me[Xe+1]-me[Xe]),Se=Array.from({length:C.length},()=>new Array(me.length));for(let rt=0;rtnew Array(C.length));for(let rt=0;rtC+Se*Ce)}function Q(C,me,ye,Se,Pe,Ce=null,rt="htk",Xe=!1){if(Ce!==null&&Ce!=="slaney")throw new Error('norm must be one of null or "slaney"');const dt=K(ye,rt),ge=K(Se,rt),U=F(dt,ge,me+2);let de=oe(U,rt),$e;if(Xe){const Ue=Pe/(C*2);$e=K(Float64Array.from({length:C},(ct,st)=>st*Ue),rt),de=U}else $e=F(0,Math.floor(Pe/2),C);const X=_e($e,de);if(Ce!==null&&Ce==="slaney")for(let Ue=0;UePe)throw Error(`frame_length (${ye}) may not be larger than fft_length (${Pe})`);if(Fe!==ye)throw new Error(`Length of the window (${Fe}) must equal frame_length (${ye})`);if(Se<=0)throw new Error("hop_length must be greater than zero");if(Ce===null&&U!==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(rt){if(Xe!=="reflect")throw new Error(`pad_mode="${Xe}" not implemented yet.`);const W=Math.floor((Pe-1)/2)+1;C=se(C,W,W)}let H=Math.floor(1+Math.floor((C.length-ye)/Se));ot!==null&&HH?at&&(je=De):je=qe=De);const Ve=new ae.FFT(Pe),Ge=new Float64Array(Pe),ut=new Float64Array(Ve.outputBufferSize),ht=new Float32Array(Ee*je);for(let W=0;W=1;--pe)Ge[pe]-=ge*Ge[pe-1];Ge[0]*=1-ge}for(let pe=0;peMath.pow(Xe,.85));break;default:throw new Error(`Unknown window type ${me}.`)}if(ye&&(rt=rt.subarray(0,C)),Se===null)return rt;if(C>Se)throw new Error(`Length of the window (${C}) may not be larger than frame_length (${Se})`);return rt}},"./src/utils/constants.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{GITHUB_ISSUE_URL:()=>I});const I="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{calculateDimensions:()=>R,calculateReflectOffset:()=>K,dispatchCallback:()=>I,escapeRegExp:()=>he,isIntegralNumber:()=>be,isTypedArray:()=>xe,mergeArrays:()=>V,pick:()=>ne,pop:()=>$,product:()=>P,reverseDictionary:()=>ae});function I(oe,_e){oe&&oe(_e)}function ae(oe){return Object.fromEntries(Object.entries(oe).map(([_e,F])=>[F,_e]))}function he(oe){return oe.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xe(oe){return oe?.prototype?.__proto__?.constructor?.name==="TypedArray"}function be(oe){return Number.isInteger(oe)||typeof oe=="bigint"}function R(oe){const _e=[];let F=oe;for(;Array.isArray(F);)_e.push(F.length),F=F[0];return _e}function $(oe,_e,F=void 0){const Q=oe[_e];if(Q!==void 0)return delete oe[_e],Q;if(F===void 0)throw Error(`Key ${_e} does not exist in object.`);return F}function V(...oe){return Array.prototype.concat.apply([],oe)}function P(...oe){return oe.reduce((_e,F)=>_e.flatMap(Q=>F.map(se=>[Q,se])))}function K(oe,_e){return Math.abs((oe+_e)%(2*_e)-_e)}function ne(oe,_e){return Object.assign({},..._e.map(F=>{if(oe[F]!==void 0)return{[F]:oe[F]}}))}},"./src/utils/data-structures.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{CharTrie:()=>ae,PriorityQueue:()=>I,TokenLattice:()=>xe});class I{constructor($=(P,K)=>P>K,V=1/0){this._heap=[],this._comparator=$,this._maxSize=V}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...$){return this.extend($)}extend($){for(const V of $)if(this.size0&&this._swap(0,V),this._heap.pop(),this._siftDown(),$}replace($){const V=this.peek();return this._heap[0]=$,this._siftDown(),V}_parent($){return($+1>>>1)-1}_left($){return($<<1)+1}_right($){return $+1<<1}_greater($,V){return this._comparator(this._heap[$],this._heap[V])}_swap($,V){const P=this._heap[$];this._heap[$]=this._heap[V],this._heap[V]=P}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom($){for(;$>0&&this._greater($,this._parent($));)this._swap($,this._parent($)),$=this._parent($)}_siftDown(){let $=0;for(;this._left($)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const K=new be(this.bosTokenId,0,0,0,0),ne=new be(this.eosTokenId,1,this.len,0,0);this.nodes.push(K.clone()),this.nodes.push(ne.clone()),this.beginNodes[this.len].push(ne),this.endNodes[0].push(K)}insert($,V,P,K){const ne=this.nodes.length,oe=new be(K,ne,$,V,P);this.beginNodes[$].push(oe),this.endNodes[$+V].push(oe),this.nodes.push(oe)}viterbi(){const $=this.len;let V=0;for(;V<=$;){if(this.beginNodes[V].length==0)return[];for(let _e of this.beginNodes[V]){_e.prev=null;let F=0,Q=null;for(let se of this.endNodes[V]){const le=se.backtraceScore+_e.score;(Q===null||le>F)&&(Q=se.clone(),F=le)}if(Q!==null)_e.prev=Q,_e.backtraceScore=F;else return[]}++V}const P=[],ne=this.beginNodes[$][0].prev;if(ne===null)return[];let oe=ne.clone();for(;oe.prev!==null;)P.push(oe.clone()),oe=oe.clone().prev.clone();return P.reverse(),P}piece($){return this.sentence.slice($.pos,$.pos+$.length)}tokens(){return this.viterbi().map(V=>this.piece(V))}tokenIds(){return this.viterbi().map(V=>V.tokenId)}}class be{constructor($,V,P,K,ne){this.tokenId=$,this.nodeId=V,this.pos=P,this.length=K,this.score=ne,this.prev=null,this.backtraceScore=0}clone(){const $=new be(this.tokenId,this.nodeId,this.pos,this.length,this.score);return $.prev=this.prev,$.backtraceScore=this.backtraceScore,$}}},"./src/utils/devices.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{DEVICE_TYPES:()=>I});const I=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":(_t,Me,N)=>{N.r(Me),N.d(Me,{DATA_TYPES:()=>xe,DEFAULT_DEVICE_DTYPE_MAPPING:()=>be,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>R,isWebGpuFp16Supported:()=>he});var I=N("./src/env.js"),ae=N("./src/utils/devices.js");const he=function(){let $;return async function(){if($===void 0)if(!I.apis.IS_WEBGPU_AVAILABLE)$=!1;else try{$=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{$=!1}return $}}(),xe=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),be=Object.freeze({[ae.DEVICE_TYPES.wasm]:xe.q8}),R=Object.freeze({[xe.fp32]:"",[xe.fp16]:"_fp16",[xe.int8]:"_int8",[xe.uint8]:"_uint8",[xe.q8]:"_quantized",[xe.q4]:"_q4",[xe.q4f16]:"_q4f16",[xe.bnb4]:"_bnb4"})},"./src/utils/generic.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{Callable:()=>I});const I=class{constructor(){let ae=function(...he){return ae._call(...he)};return Object.setPrototypeOf(ae,new.target.prototype)}_call(...ae){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{getFile:()=>V,getModelFile:()=>_e,getModelJSON:()=>F});var I=N("?7a2c"),ae=N("?a42a"),he=N("./src/env.js"),xe=N("./src/utils/core.js");const be={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 R{constructor(ie){if(this.filePath=ie,this.headers=new Headers,this.exists=I.existsSync(ie),this.exists){this.status=200,this.statusText="OK";let j=I.statSync(ie);this.headers.set("content-length",j.size.toString()),this.updateContentType();let A=this;this.body=new ReadableStream({start(L){A.arrayBuffer().then(C=>{L.enqueue(new Uint8Array(C)),L.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const ie=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",be[ie]??"application/octet-stream")}clone(){let ie=new R(this.filePath);return ie.exists=this.exists,ie.status=this.status,ie.statusText=this.statusText,ie.headers=new Headers(this.headers),ie}async arrayBuffer(){return(await I.promises.readFile(this.filePath)).buffer}async blob(){const ie=await I.promises.readFile(this.filePath);return new Blob([ie],{type:this.headers.get("content-type")})}async text(){return await I.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function $(le,ie=null,j=null){let A;try{A=new URL(le)}catch{return!1}return!(ie&&!ie.includes(A.protocol)||j&&!j.includes(A.hostname))}async function V(le){if(he.env.useFS&&!$(le,["http:","https:","blob:"]))return new R(le);if(typeof process<"u"&&process?.release?.name==="node"){const ie=!!Ic?.TESTING_REMOTELY,j=he.env.version,A=new Headers;if(A.set("User-Agent",`transformers.js/${j}; is_ci/${ie};`),$(le,["http:","https:"],["huggingface.co","hf.co"])){const C=Ic?.HF_TOKEN??Ic?.HF_ACCESS_TOKEN;C&&A.set("Authorization",`Bearer ${C}`)}return fetch(le,{headers:A})}else return fetch(le)}const P={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 K(le,ie,j){if(!j)return null;const A=P[le]??`Error (${le}) occurred while trying to load file`;throw Error(`${A}: "${ie}".`)}class ne{constructor(ie){this.path=ie}async match(ie){let j=ae.join(this.path,ie),A=new R(j);if(A.exists)return A}async put(ie,j){const A=Buffer.from(await j.arrayBuffer());let L=ae.join(this.path,ie);try{await I.promises.mkdir(ae.dirname(L),{recursive:!0}),await I.promises.writeFile(L,A)}catch(C){console.warn("An error occurred while writing the file to cache:",C)}}}async function oe(le,...ie){for(let j of ie)try{let A=await le.match(j);if(A)return A}catch{continue}}async function _e(le,ie,j=!0,A={}){if(!he.env.allowLocalModels){if(A.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(!he.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,xe.dispatchCallback)(A.progress_callback,{status:"initiate",name:le,file:ie});let L;if(!L&&he.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{L=await caches.open("transformers-cache")}catch($e){console.warn("An error occurred while opening the browser cache:",$e)}}if(!L&&he.env.useFSCache&&(L=new ne(A.cache_dir??he.env.cacheDir)),!L&&he.env.useCustomCache){if(!he.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!he.env.customCache.match||!he.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");L=he.env.customCache}const C=A.revision??"main";let me=se(le,ie),ye=se(he.env.localModelPath,me),Se=se(he.env.remoteHost,he.env.remotePathTemplate.replaceAll("{model}",le).replaceAll("{revision}",encodeURIComponent(C)),ie),Pe=C==="main"?me:se(le,C,ie),Ce,rt=L instanceof ne?Pe:Se,Xe=!1,dt;L&&(dt=await oe(L,ye,rt));const ge=dt!==void 0;if(dt===void 0){if(he.env.allowLocalModels)if($(me,["http:","https:"])){if(A.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${me}.`);if(!he.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${me}.`)}else try{dt=await V(ye),Ce=ye}catch(X){console.warn(`Unable to load from local path "${ye}": "${X}"`)}if(dt===void 0||dt.status===404){if(A.local_files_only||!he.env.allowRemoteModels){if(j)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ye}".`);return null}if(dt=await V(Se),dt.status!==200)return K(dt.status,Se,j);Ce=rt}Xe=L&&typeof Response<"u"&&dt instanceof Response&&dt.status===200}(0,xe.dispatchCallback)(A.progress_callback,{status:"download",name:le,file:ie});const U={status:"progress",name:le,file:ie};let de;return A.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(de=new Uint8Array(await dt.arrayBuffer()),(0,xe.dispatchCallback)(A.progress_callback,{...U,progress:100,loaded:de.length,total:de.length})):de=await Q(dt,$e=>{(0,xe.dispatchCallback)(A.progress_callback,{...U,...$e})}):de=new Uint8Array(await dt.arrayBuffer()),Xe&&Ce&&await L.match(Ce)===void 0&&await L.put(Ce,new Response(de,{headers:dt.headers})).catch($e=>{console.warn(`Unable to add response to browser cache: ${$e}.`)}),(0,xe.dispatchCallback)(A.progress_callback,{status:"done",name:le,file:ie}),de}async function F(le,ie,j=!0,A={}){let L=await _e(le,ie,j,A);if(L===null)return{};let me=new TextDecoder("utf-8").decode(L);return JSON.parse(me)}async function Q(le,ie){const j=le.headers.get("Content-Length");j===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let A=parseInt(j??"0"),L=new Uint8Array(A),C=0;const me=le.body.getReader();async function ye(){const{done:Se,value:Pe}=await me.read();if(Se)return;let Ce=C+Pe.length;if(Ce>A){A=Ce;let Xe=new Uint8Array(A);Xe.set(L),L=Xe}L.set(Pe,C),C=Ce;const rt=C/A*100;return ie({progress:rt,loaded:C,total:A}),ye()}return await ye(),L}function se(...le){return le=le.map((ie,j)=>(j&&(ie=ie.replace(new RegExp("^/"),"")),j!==le.length-1&&(ie=ie.replace(new RegExp("/$"),"")),ie)),le.join("/")}},"./src/utils/image.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{RawImage:()=>oe});var I=N("./src/utils/hub.js"),ae=N("./src/env.js"),he=N("./src/utils/tensor.js"),xe=N("?2b25");const be=typeof self<"u",R=be&&self.constructor.name==="DedicatedWorkerGlobalScope";let $,V,P;if(be)$=(_e,F)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(_e,F)},P=self.createImageBitmap,V=self.ImageData;else if(xe)P=async _e=>{const Q=(await _e.metadata()).channels,{data:se,info:le}=await _e.rotate().raw().toBuffer({resolveWithObject:!0}),ie=new oe(new Uint8ClampedArray(se),le.width,le.height,le.channels);return Q!==void 0&&Q!==le.channels&&ie.convert(Q),ie};else throw new Error("Unable to load image processing library.");const K={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ne=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class oe{constructor(F,Q,se,le){this.data=F,this.width=Q,this.height=se,this.channels=le}get size(){return[this.width,this.height]}static async read(F){if(F instanceof oe)return F;if(typeof F=="string"||F instanceof URL)return await this.fromURL(F);throw new Error(`Unsupported input type: ${typeof F}`)}static fromCanvas(F){if(!be)throw new Error("fromCanvas() is only supported in browser environments.");const se=F.getContext("2d").getImageData(0,0,F.width,F.height).data;return new oe(se,F.width,F.height,4)}static async fromURL(F){const Q=await(0,I.getFile)(F);if(Q.status!==200)throw new Error(`Unable to read image from "${F}" (${Q.status} ${Q.statusText})`);const se=await Q.blob();return this.fromBlob(se)}static async fromBlob(F){if(be){const Q=await P(F),se=$(Q.width,Q.height).getContext("2d");return se.drawImage(Q,0,0),new this(se.getImageData(0,0,Q.width,Q.height).data,Q.width,Q.height,4)}else{const Q=xe(await F.arrayBuffer());return await P(Q)}}static fromTensor(F,Q="CHW"){if(F.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${F.dims.length} dimensions.`);if(Q==="CHW")F=F.transpose(1,2,0);else if(Q!=="HWC")throw new Error(`Unsupported channel format: ${Q}`);if(!(F.data instanceof Uint8ClampedArray||F.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${F.type}`);switch(F.dims[2]){case 1:case 2:case 3:case 4:return new oe(F.data,F.dims[1],F.dims[0],F.dims[2]);default:throw new Error(`Unsupported number of channels: ${F.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const F=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let Q=0,se=0;Q=0?L=se:me=-se,le>=0?C=le:ye=-le,A.drawImage(j,L,C,F,Q,me,ye,F,Q),new oe(A.getImageData(0,0,F,Q).data,F,Q,4).convert(ie)}else{let ie=this.toSharp();if(se>=0&&le>=0)ie=ie.extract({left:Math.floor(se),top:Math.floor(le),width:F,height:Q});else if(se<=0&&le<=0){const j=Math.floor(-le),A=Math.floor(-se);ie=ie.extend({top:j,left:A,right:F-this.width-A,bottom:Q-this.height-j})}else{let j=[0,0],A=0;le<0?(j[0]=Math.floor(-le),j[1]=Q-this.height-j[0]):A=Math.floor(le);let L=[0,0],C=0;se<0?(L[0]=Math.floor(-se),L[1]=F-this.width-L[0]):C=Math.floor(se),ie=ie.extend({top:j[0],bottom:j[1],left:L[0],right:L[1]}).extract({left:C,top:A,width:F,height:Q})}return await P(ie)}}async toBlob(F="image/png",Q=1){if(!be)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:F,quality:Q})}toTensor(F="CHW"){let Q=new he.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(F!=="HWC")if(F==="CHW")Q=Q.permute(2,0,1);else throw new Error(`Unsupported channel format: ${F}`);return Q}toCanvas(){if(!be)throw new Error("toCanvas() is only supported in browser environments.");const F=this.clone().rgba(),Q=$(F.width,F.height),se=new V(F.data,F.width,F.height);return Q.getContext("2d").putImageData(se,0,0),Q}_update(F,Q,se,le=null){return this.data=F,this.width=Q,this.height=se,le!==null&&(this.channels=le),this}clone(){return new oe(this.data.slice(),this.width,this.height,this.channels)}convert(F){if(this.channels===F)return this;switch(F){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(F){if(be){if(R)throw new Error("Unable to save an image from a Web Worker.");const Q=F.split(".").pop().toLowerCase(),se=ne.get(Q)??"image/png",le=await this.toBlob(se),ie=URL.createObjectURL(le),j=document.createElement("a");j.href=ie,j.download=F,j.click(),j.remove()}else{if(ae.env.useFS)return await this.toSharp().toFile(F);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(be)throw new Error("toSharp() is only supported in server-side environments.");return xe(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{FFT:()=>_e,bankers_round:()=>se,cos_sim:()=>R,dot:()=>be,dynamic_time_warping:()=>le,interpolate_data:()=>I,log_softmax:()=>xe,magnitude:()=>$,max:()=>P,medianFilter:()=>F,min:()=>V,permute_data:()=>ae,round:()=>Q,softmax:()=>he});function I(ie,[j,A,L],[C,me],ye="bilinear",Se=!1){const Pe=me/L,Ce=C/A,rt=new ie.constructor(C*me*j),Xe=A*L,dt=C*me;for(let ge=0;ge=0;--Se)C[Se]=Pe,L[Se]=j[A[Se]],Pe*=L[Se];const me=A.map((Se,Pe)=>C[A.indexOf(Pe)]),ye=new ie.constructor(ie.length);for(let Se=0;Se=0;--Ce)Pe+=rt%j[Ce]*me[Ce],rt=Math.floor(rt/j[Ce]);ye[Pe]=ie[Se]}return[ye,L]}function he(ie){const j=P(ie)[0],A=ie.map(me=>Math.exp(me-j)),L=A.reduce((me,ye)=>me+ye,0);return A.map(me=>me/L)}function xe(ie){return he(ie).map(L=>Math.log(L))}function be(ie,j){let A=0;for(let L=0;Lj+A*A,0))}function V(ie){if(ie.length===0)throw Error("Array must not be empty");let j=ie[0],A=0;for(let L=1;Lj&&(j=ie[L],A=L);return[Number(j),A]}function K(ie){return ie>0&&(ie&ie-1)===0}class ne{constructor(j){if(this.size=j|0,this.size<=1||!K(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=j<<1,this.table=new Float64Array(this.size*2);for(let L=0;LL;L<<=1)++A;this._width=A%2===0?A-1:A,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=j[C];return L}toComplexArray(j,A){const L=A||this.createComplexArray();for(let C=0;C>>1],L[C+1]=0;return L}transform(j,A){if(j===A)throw new Error("Input and output buffers must be different");this._transform4(j,A,1)}realTransform(j,A){if(j===A)throw new Error("Input and output buffers must be different");this._realTransform4(j,A,1)}inverseTransform(j,A){if(j===A)throw new Error("Input and output buffers must be different");this._transform4(j,A,-1);for(let L=0;L>=2;ye>=2;ye>>=2){Se=C/ye<<1;const dt=Se>>>2;for(Pe=0;Pe>>1,ye>>>1)}else for(Pe=0,Ce=0;Pe>>1,ye>>>1,L)}const Xe=this.table;for(ye>>=2;ye>=2;ye>>=2){Se=C/ye<<1;const ge=Se>>>1,U=ge>>>1,de=U>>>1;for(Pe=0;Pe>>1;for(let ge=2;ge>1;++rt){const Xe=(rt+1-j)**2/2,dt=Math.sqrt(Pe**2+Ce**2)**Xe,ge=Xe*Math.atan2(Ce,Pe),U=2*rt;me[U]=dt*Math.cos(ge),me[U+1]=dt*Math.sin(ge),ye[U]=me[U],ye[U+1]=-me[U+1]}this._slicedChirpBuffer=me.subarray(A,L),this._f=new ne(C>>1),this._f.transform(this._chirpBuffer,ye)}_transform(j,A,L){const C=this._buffer1,me=this._buffer2,ye=this._outBuffer1,Se=this._outBuffer2,Pe=this._chirpBuffer,Ce=this._slicedChirpBuffer,rt=this._a;if(L)for(let Xe=0;Xe>1,U=A[ge];C[Xe]=U*Ce[Xe],C[dt]=U*Ce[dt]}else for(let Xe=0;Xe=ie.length&&(Pe=2*(ie.length-1)-Pe),L[ye++]=ie[Pe]}L.sort(),A[me]=L[C]}return A}function Q(ie,j){const A=Math.pow(10,j);return Math.round(ie*A)/A}function se(ie){const j=Math.round(ie);return Math.abs(ie)%1===.5?j%2===0?j:j-1:j}function le(ie){const j=ie.length,A=ie[0].length,L=[j+1,A+1],C=Array.from({length:L[0]},()=>Array(L[1]).fill(1/0));C[0][0]=0;const me=Array.from({length:L[0]},()=>Array(L[1]).fill(-1));for(let rt=1;rt0||Se>0;)switch(Pe.push(ye-1),Ce.push(Se-1),me[ye][Se]){case 0:--ye,--Se;break;case 1:--ye;break;case 2:--Se;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ye}, ${Se}]. Please file a bug report.`)}return Pe.reverse(),Ce.reverse(),[Pe,Ce]}},"./src/utils/tensor.js":(_t,Me,N)=>{N.r(Me),N.d(Me,{Tensor:()=>be,cat:()=>ie,full:()=>ye,full_like:()=>Se,interpolate:()=>V,interpolate_4d:()=>P,layer_norm:()=>F,matmul:()=>K,mean:()=>L,mean_pooling:()=>_e,ones:()=>Pe,ones_like:()=>Ce,permute:()=>$,quantize_embeddings:()=>dt,rfft:()=>ne,stack:()=>j,std_mean:()=>A,topk:()=>oe,zeros:()=>rt,zeros_like:()=>Xe});var I=N("./src/utils/maths.js"),ae=N("./src/backends/onnx.js"),he=N("./src/ops/registry.js");const xe=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});class be{get dims(){return this.ort_tensor.dims}set dims(U){this.ort_tensor.dims=U}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}ort_tensor;constructor(...U){return(0,ae.isONNXTensor)(U[0])?this.ort_tensor=U[0]:this.ort_tensor=new ae.Tensor(U[0],U[1],U[2]),new Proxy(this,{get:(de,$e)=>{if(typeof $e=="string"){let X=Number($e);if(Number.isInteger(X))return de._getitem(X)}return de[$e]},set:(de,$e,X)=>de[$e]=X})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[U,...de]=this.dims;if(de.length>0){const $e=de.reduce((X,Ue)=>X*Ue);for(let X=0;X0){const X=$e.reduce((Ue,ct)=>Ue*ct);return this._subarray(U,X,$e)}else return new be(this.type,[this.data[U]],$e)}indexOf(U){const de=this.data;for(let $e=0;$eFe)throw new Error(`Invalid slice: ${at}`);const H=[Math.max(Et,0),Math.min(Fe,this.dims[De])];$e.push(H),de.push(H[1]-H[0])}else throw new Error(`Invalid slice: ${at}`)}const X=$e.map(([De,at])=>at-De),Ue=X.reduce((De,at)=>De*at),ct=this.data,st=new ct.constructor(Ue),ot=this.stride();for(let De=0;De=0;--Et){const H=X[Et];at+=(Fe%H+$e[Et][0])*ot[Et],Fe=Math.floor(Fe/H)}st[De]=ct[at]}return new be(this.type,st,de)}permute(...U){return $(this,U)}transpose(...U){return this.permute(...U)}sum(U=null,de=!1){return this.norm(1,U,de)}norm(U="fro",de=null,$e=!1){if(U==="fro")U=2;else if(typeof U=="string")throw Error(`Unsupported norm: ${U}`);const X=this.data;if(de===null){let st=X.reduce((ot,De)=>ot+De**U,0)**(1/U);return new be(this.type,[st],[])}de=le(de,this.dims.length);const Ue=this.dims.slice();Ue[de]=1;const ct=new X.constructor(X.length/this.dims[de]);for(let st=0;st=0;--De){const Fe=this.dims[De];if(De!==de){const H=at%Fe;ot+=H*Et,Et*=Ue[De]}at=Math.floor(at/Fe)}ct[ot]+=X[st]**U}if(U!==1)for(let st=0;st=0;--ot){const Et=this.dims[ot];if(ot!==de){const Fe=De%Et;st+=Fe*at,at*=this.dims[ot]}De=Math.floor(De/Et)}X[ct]/=Ue[st]}return this}normalize(U=2,de=1){return this.clone().normalize_(U,de)}stride(){return C(this.dims)}squeeze(U=null){return new be(this.type,this.data,Q(this.dims,U))}squeeze_(U=null){return this.dims=Q(this.dims,U),this}unsqueeze(U=null){return new be(this.type,this.data,se(this.dims,U))}unsqueeze_(U=null){return this.dims=se(this.dims,U),this}flatten_(U=0,de=-1){de=(de+this.dims.length)%this.dims.length;let $e=this.dims.slice(0,U),X=this.dims.slice(U,de+1),Ue=this.dims.slice(de+1);return this.dims=[...$e,X.reduce((ct,st)=>ct*st,1),...Ue],this}flatten(U=0,de=-1){return this.clone().flatten_(U,de)}view(...U){let de=-1;for(let X=0;Xst!==de?Ue*ct:Ue,1);U[de]=$e.length/X}return new be(this.type,$e,U)}neg_(){const U=this.data;for(let de=0;deUe*ct);if(de!==$e)throw Error(`cannot reshape array of size ${de} into shape (${U})`);let X=ge;for(let Ue=U.length-1;Ue>=0;Ue--)X=X.reduce((ct,st)=>{let ot=ct[ct.length-1];return ot.lengthde!==1):typeof U=="number"?ge[U]===1&&ge.splice(U,1):Array.isArray(U)&&(ge=ge.filter((de,$e)=>de!==1||!U.includes($e))),ge}function se(ge,U){return U=le(U,ge.length+1),ge=ge.slice(),ge.splice(U,0,1),ge}function le(ge,U,de=null,$e=!0){if($e&&(ge<-U||ge>=U))throw new Error(`IndexError: index ${ge} is out of bounds for dimension${de===null?"":" "+de} with size ${U}`);return ge<0&&(ge=(ge%U+U)%U),ge}function ie(ge,U=0){U=le(U,ge[0].dims.length);const de=ge[0].dims.slice();de[U]=ge.reduce((ct,st)=>ct+st.dims[U],0);const $e=de.reduce((ct,st)=>ct*st,1),X=new ge[0].data.constructor($e),Ue=ge[0].type;if(U===0){let ct=0;for(const st of ge){const ot=st.data;X.set(ot,ct),ct+=ot.length}}else{let ct=0;for(let st=0;st=0;--Fe){const qe=De[Fe];let je=H%qe;Fe===U&&(je+=ct),Et+=je*Ee,Ee*=de[Fe],H=Math.floor(H/qe)}X[Et]=ot[at]}ct+=De[U]}}return new be(Ue,X,de)}function j(ge,U=0){return ie(ge.map(de=>de.unsqueeze(U)),U)}function A(ge,U=null,de=1,$e=!1){const X=ge.data,Ue=ge.dims;if(U===null){const Fe=X.reduce((je,Ve)=>je+Ve,0)/X.length,H=Math.sqrt(X.reduce((je,Ve)=>je+(Ve-Fe)**2,0)/(X.length-de)),Ee=new be(ge.type,[Fe],[]);return[new be(ge.type,[H],[]),Ee]}U=le(U,Ue.length);const ct=L(ge,U,$e),st=ct.data,ot=Ue.slice();ot[U]=1;const De=new X.constructor(X.length/Ue[U]);for(let Et=0;Et=0;--H){const je=Ue[H];if(H!==U){const Ve=Ee%je;Fe+=Ve*qe,qe*=ot[H]}Ee=Math.floor(Ee/je)}De[Fe]+=(X[Et]-st[Fe])**2}for(let Et=0;Etot+De,0);return new be(ge.type,[st/$e.length],[])}const X=ge.dims;U=le(U,X.length);const Ue=X.slice();Ue[U]=1;const ct=new $e.constructor($e.length/X[U]);for(let st=0;st<$e.length;++st){let ot=0;for(let De=X.length-1,at=st,Et=1;De>=0;--De){const Fe=X[De];if(De!==U){const H=at%Fe;ot+=H*Et,Et*=Ue[De]}at=Math.floor(at/Fe)}ct[ot]+=$e[st]}if(X[U]!==1)for(let st=0;st=0;--de)U[de]=$e,$e*=ge[de];return U}function me(ge,U,de,$e){const X=ge.reduce((Ue,ct)=>Ue*ct,1);return new be(de,new $e(X).fill(U),ge)}function ye(ge,U){let de,$e;if(typeof U=="number")de="float32",$e=Float32Array;else if(typeof U=="bigint")de="int64",$e=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof U}`);return me(ge,U,de,$e)}function Se(ge,U){return ye(ge.dims,U)}function Pe(ge){return me(ge,1n,"int64",BigInt64Array)}function Ce(ge){return Pe(ge.dims)}function rt(ge){return me(ge,0n,"int64",BigInt64Array)}function Xe(ge){return rt(ge.dims)}function dt(ge,U){if(ge.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ge.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(U))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=U==="binary",$e=de?"int8":"uint8",X=de?Int8Array:Uint8Array,Ue=ge.data,ct=new X(Ue.length/8);for(let st=0;st0?1:0,De=Math.floor(st/8),at=st%8;ct[De]|=ot<<7-at,de&&at===0&&(ct[De]-=128)}return new be($e,ct,[ge.dims[0],ge.dims[1]/8])}}},xf={};function Gr(_t){var Me=xf[_t];if(Me!==void 0)return Me.exports;var N=xf[_t]={exports:{}};return $f[_t](N,N.exports,Gr),N.exports}Gr.m=$f;(()=>{var _t=Object.getPrototypeOf?N=>Object.getPrototypeOf(N):N=>N.__proto__,Me;Gr.t=function(N,I){if(I&1&&(N=this(N)),I&8||typeof N=="object"&&N&&(I&4&&N.__esModule||I&16&&typeof N.then=="function"))return N;var ae=Object.create(null);Gr.r(ae);var he={};Me=Me||[null,_t({}),_t([]),_t(_t)];for(var xe=I&2&&N;typeof xe=="object"&&!~Me.indexOf(xe);xe=_t(xe))Object.getOwnPropertyNames(xe).forEach(be=>he[be]=()=>N[be]);return he.default=()=>N,Gr.d(ae,he),ae}})();Gr.d=(_t,Me)=>{for(var N in Me)Gr.o(Me,N)&&!Gr.o(_t,N)&&Object.defineProperty(_t,N,{enumerable:!0,get:Me[N]})};Gr.o=(_t,Me)=>Object.prototype.hasOwnProperty.call(_t,Me);Gr.r=_t=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(_t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(_t,"__esModule",{value:!0})};(()=>{var _t;if(typeof import.meta.url=="string"&&(_t=import.meta.url),!_t)throw new Error("Automatic publicPath is not supported in this browser");_t=_t.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Gr.p=_t})();Gr.b=new URL("./",import.meta.url);var p={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Gr.r(p);Gr.d(p,{ASTFeatureExtractor:()=>Jt.ASTFeatureExtractor,ASTForAudioClassification:()=>b.ASTForAudioClassification,ASTModel:()=>b.ASTModel,ASTPreTrainedModel:()=>b.ASTPreTrainedModel,AlbertForMaskedLM:()=>b.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>b.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>b.AlbertForSequenceClassification,AlbertModel:()=>b.AlbertModel,AlbertPreTrainedModel:()=>b.AlbertPreTrainedModel,AlbertTokenizer:()=>nr.AlbertTokenizer,AudioClassificationPipeline:()=>Wr.AudioClassificationPipeline,AutoConfig:()=>Fc.AutoConfig,AutoModel:()=>b.AutoModel,AutoModelForAudioClassification:()=>b.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>b.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>b.AutoModelForCTC,AutoModelForCausalLM:()=>b.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>b.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>b.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>b.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>b.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>b.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>b.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>b.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>b.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>b.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>b.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>b.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>b.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>b.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>b.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>b.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>b.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>b.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>b.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>b.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>b.AutoModelForVision2Seq,AutoModelForXVector:()=>b.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>b.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Jt.AutoProcessor,AutoTokenizer:()=>nr.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Wr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>b.BartForConditionalGeneration,BartForSequenceClassification:()=>b.BartForSequenceClassification,BartModel:()=>b.BartModel,BartPretrainedModel:()=>b.BartPretrainedModel,BartTokenizer:()=>nr.BartTokenizer,BaseModelOutput:()=>b.BaseModelOutput,BaseStreamer:()=>Oc.BaseStreamer,BeitFeatureExtractor:()=>Jt.BeitFeatureExtractor,BeitForImageClassification:()=>b.BeitForImageClassification,BeitModel:()=>b.BeitModel,BeitPreTrainedModel:()=>b.BeitPreTrainedModel,BertForMaskedLM:()=>b.BertForMaskedLM,BertForQuestionAnswering:()=>b.BertForQuestionAnswering,BertForSequenceClassification:()=>b.BertForSequenceClassification,BertForTokenClassification:()=>b.BertForTokenClassification,BertModel:()=>b.BertModel,BertPreTrainedModel:()=>b.BertPreTrainedModel,BertTokenizer:()=>nr.BertTokenizer,BitImageProcessor:()=>Jt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>b.BlenderbotForConditionalGeneration,BlenderbotModel:()=>b.BlenderbotModel,BlenderbotPreTrainedModel:()=>b.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>b.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>b.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>b.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>nr.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>nr.BlenderbotTokenizer,BloomForCausalLM:()=>b.BloomForCausalLM,BloomModel:()=>b.BloomModel,BloomPreTrainedModel:()=>b.BloomPreTrainedModel,BloomTokenizer:()=>nr.BloomTokenizer,CLIPFeatureExtractor:()=>Jt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Jt.CLIPImageProcessor,CLIPModel:()=>b.CLIPModel,CLIPPreTrainedModel:()=>b.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>b.CLIPSegForImageSegmentation,CLIPSegModel:()=>b.CLIPSegModel,CLIPSegPreTrainedModel:()=>b.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>b.CLIPTextModelWithProjection,CLIPTokenizer:()=>nr.CLIPTokenizer,CLIPVisionModelWithProjection:()=>b.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>b.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>b.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>b.CamembertForSequenceClassification,CamembertForTokenClassification:()=>b.CamembertForTokenClassification,CamembertModel:()=>b.CamembertModel,CamembertPreTrainedModel:()=>b.CamembertPreTrainedModel,CamembertTokenizer:()=>nr.CamembertTokenizer,CausalLMOutput:()=>b.CausalLMOutput,CausalLMOutputWithPast:()=>b.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Jt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>b.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>b.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>b.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Jt.ClapFeatureExtractor,ClapModel:()=>b.ClapModel,ClapPreTrainedModel:()=>b.ClapPreTrainedModel,ClapTextModelWithProjection:()=>b.ClapTextModelWithProjection,CodeGenForCausalLM:()=>b.CodeGenForCausalLM,CodeGenModel:()=>b.CodeGenModel,CodeGenPreTrainedModel:()=>b.CodeGenPreTrainedModel,CodeGenTokenizer:()=>nr.CodeGenTokenizer,CodeLlamaTokenizer:()=>nr.CodeLlamaTokenizer,CohereForCausalLM:()=>b.CohereForCausalLM,CohereModel:()=>b.CohereModel,CoherePreTrainedModel:()=>b.CoherePreTrainedModel,CohereTokenizer:()=>nr.CohereTokenizer,ConvBertForMaskedLM:()=>b.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>b.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>b.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>b.ConvBertForTokenClassification,ConvBertModel:()=>b.ConvBertModel,ConvBertPreTrainedModel:()=>b.ConvBertPreTrainedModel,ConvBertTokenizer:()=>nr.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Jt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>b.ConvNextForImageClassification,ConvNextImageProcessor:()=>Jt.ConvNextImageProcessor,ConvNextModel:()=>b.ConvNextModel,ConvNextPreTrainedModel:()=>b.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>b.ConvNextV2ForImageClassification,ConvNextV2Model:()=>b.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>b.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Jt.DPTFeatureExtractor,DPTForDepthEstimation:()=>b.DPTForDepthEstimation,DPTImageProcessor:()=>Jt.DPTImageProcessor,DPTModel:()=>b.DPTModel,DPTPreTrainedModel:()=>b.DPTPreTrainedModel,DebertaForMaskedLM:()=>b.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>b.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>b.DebertaForSequenceClassification,DebertaForTokenClassification:()=>b.DebertaForTokenClassification,DebertaModel:()=>b.DebertaModel,DebertaPreTrainedModel:()=>b.DebertaPreTrainedModel,DebertaTokenizer:()=>nr.DebertaTokenizer,DebertaV2ForMaskedLM:()=>b.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>b.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>b.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>b.DebertaV2ForTokenClassification,DebertaV2Model:()=>b.DebertaV2Model,DebertaV2PreTrainedModel:()=>b.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>nr.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>Jt.DeiTFeatureExtractor,DeiTForImageClassification:()=>b.DeiTForImageClassification,DeiTModel:()=>b.DeiTModel,DeiTPreTrainedModel:()=>b.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>b.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>b.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Wr.DepthEstimationPipeline,DetrFeatureExtractor:()=>Jt.DetrFeatureExtractor,DetrForObjectDetection:()=>b.DetrForObjectDetection,DetrForSegmentation:()=>b.DetrForSegmentation,DetrModel:()=>b.DetrModel,DetrObjectDetectionOutput:()=>b.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>b.DetrPreTrainedModel,DetrSegmentationOutput:()=>b.DetrSegmentationOutput,Dinov2ForImageClassification:()=>b.Dinov2ForImageClassification,Dinov2Model:()=>b.Dinov2Model,Dinov2PreTrainedModel:()=>b.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>b.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>b.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>b.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>b.DistilBertForTokenClassification,DistilBertModel:()=>b.DistilBertModel,DistilBertPreTrainedModel:()=>b.DistilBertPreTrainedModel,DistilBertTokenizer:()=>nr.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Wr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Jt.DonutFeatureExtractor,DonutSwinModel:()=>b.DonutSwinModel,DonutSwinPreTrainedModel:()=>b.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>b.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Jt.EfficientNetImageProcessor,EfficientNetModel:()=>b.EfficientNetModel,EfficientNetPreTrainedModel:()=>b.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>b.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>b.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>b.ElectraForSequenceClassification,ElectraForTokenClassification:()=>b.ElectraForTokenClassification,ElectraModel:()=>b.ElectraModel,ElectraPreTrainedModel:()=>b.ElectraPreTrainedModel,ElectraTokenizer:()=>nr.ElectraTokenizer,EosTokenCriteria:()=>Su.EosTokenCriteria,EsmForMaskedLM:()=>b.EsmForMaskedLM,EsmForSequenceClassification:()=>b.EsmForSequenceClassification,EsmForTokenClassification:()=>b.EsmForTokenClassification,EsmModel:()=>b.EsmModel,EsmPreTrainedModel:()=>b.EsmPreTrainedModel,EsmTokenizer:()=>nr.EsmTokenizer,FFT:()=>En.FFT,FalconForCausalLM:()=>b.FalconForCausalLM,FalconModel:()=>b.FalconModel,FalconPreTrainedModel:()=>b.FalconPreTrainedModel,FalconTokenizer:()=>nr.FalconTokenizer,FastViTForImageClassification:()=>b.FastViTForImageClassification,FastViTModel:()=>b.FastViTModel,FastViTPreTrainedModel:()=>b.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Wr.FeatureExtractionPipeline,FeatureExtractor:()=>Jt.FeatureExtractor,FillMaskPipeline:()=>Wr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>b.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>b.Florence2PreTrainedModel,Florence2Processor:()=>Jt.Florence2Processor,GLPNFeatureExtractor:()=>Jt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>b.GLPNForDepthEstimation,GLPNModel:()=>b.GLPNModel,GLPNPreTrainedModel:()=>b.GLPNPreTrainedModel,GPT2LMHeadModel:()=>b.GPT2LMHeadModel,GPT2Model:()=>b.GPT2Model,GPT2PreTrainedModel:()=>b.GPT2PreTrainedModel,GPT2Tokenizer:()=>nr.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>b.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>b.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>b.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>b.GPTJForCausalLM,GPTJModel:()=>b.GPTJModel,GPTJPreTrainedModel:()=>b.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>b.GPTNeoForCausalLM,GPTNeoModel:()=>b.GPTNeoModel,GPTNeoPreTrainedModel:()=>b.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>b.GPTNeoXForCausalLM,GPTNeoXModel:()=>b.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>b.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>nr.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>b.Gemma2ForCausalLM,Gemma2Model:()=>b.Gemma2Model,Gemma2PreTrainedModel:()=>b.Gemma2PreTrainedModel,GemmaForCausalLM:()=>b.GemmaForCausalLM,GemmaModel:()=>b.GemmaModel,GemmaPreTrainedModel:()=>b.GemmaPreTrainedModel,GemmaTokenizer:()=>nr.GemmaTokenizer,Grok1Tokenizer:()=>nr.Grok1Tokenizer,HerbertTokenizer:()=>nr.HerbertTokenizer,HieraForImageClassification:()=>b.HieraForImageClassification,HieraModel:()=>b.HieraModel,HieraPreTrainedModel:()=>b.HieraPreTrainedModel,HubertForCTC:()=>b.HubertForCTC,HubertForSequenceClassification:()=>b.HubertForSequenceClassification,HubertModel:()=>b.HubertModel,HubertPreTrainedModel:()=>b.HubertPreTrainedModel,ImageClassificationPipeline:()=>Wr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Wr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Jt.ImageFeatureExtractor,ImageMattingOutput:()=>b.ImageMattingOutput,ImageSegmentationPipeline:()=>Wr.ImageSegmentationPipeline,ImageToImagePipeline:()=>Wr.ImageToImagePipeline,ImageToTextPipeline:()=>Wr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Su.InterruptableStoppingCriteria,JAISLMHeadModel:()=>b.JAISLMHeadModel,JAISModel:()=>b.JAISModel,JAISPreTrainedModel:()=>b.JAISPreTrainedModel,LlamaForCausalLM:()=>b.LlamaForCausalLM,LlamaModel:()=>b.LlamaModel,LlamaPreTrainedModel:()=>b.LlamaPreTrainedModel,LlamaTokenizer:()=>nr.LlamaTokenizer,LlavaForConditionalGeneration:()=>b.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>b.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>b.LongT5ForConditionalGeneration,LongT5Model:()=>b.LongT5Model,LongT5PreTrainedModel:()=>b.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>b.M2M100ForConditionalGeneration,M2M100Model:()=>b.M2M100Model,M2M100PreTrainedModel:()=>b.M2M100PreTrainedModel,M2M100Tokenizer:()=>nr.M2M100Tokenizer,MBart50Tokenizer:()=>nr.MBart50Tokenizer,MBartForCausalLM:()=>b.MBartForCausalLM,MBartForConditionalGeneration:()=>b.MBartForConditionalGeneration,MBartForSequenceClassification:()=>b.MBartForSequenceClassification,MBartModel:()=>b.MBartModel,MBartPreTrainedModel:()=>b.MBartPreTrainedModel,MBartTokenizer:()=>nr.MBartTokenizer,MPNetForMaskedLM:()=>b.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>b.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>b.MPNetForSequenceClassification,MPNetForTokenClassification:()=>b.MPNetForTokenClassification,MPNetModel:()=>b.MPNetModel,MPNetPreTrainedModel:()=>b.MPNetPreTrainedModel,MPNetTokenizer:()=>nr.MPNetTokenizer,MT5ForConditionalGeneration:()=>b.MT5ForConditionalGeneration,MT5Model:()=>b.MT5Model,MT5PreTrainedModel:()=>b.MT5PreTrainedModel,MarianMTModel:()=>b.MarianMTModel,MarianModel:()=>b.MarianModel,MarianPreTrainedModel:()=>b.MarianPreTrainedModel,MarianTokenizer:()=>nr.MarianTokenizer,MaskedLMOutput:()=>b.MaskedLMOutput,MaxLengthCriteria:()=>Su.MaxLengthCriteria,MistralForCausalLM:()=>b.MistralForCausalLM,MistralModel:()=>b.MistralModel,MistralPreTrainedModel:()=>b.MistralPreTrainedModel,MobileBertForMaskedLM:()=>b.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>b.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>b.MobileBertForSequenceClassification,MobileBertModel:()=>b.MobileBertModel,MobileBertPreTrainedModel:()=>b.MobileBertPreTrainedModel,MobileBertTokenizer:()=>nr.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Jt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>b.MobileNetV1ForImageClassification,MobileNetV1Model:()=>b.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>b.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Jt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>b.MobileNetV2ForImageClassification,MobileNetV2Model:()=>b.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>b.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Jt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>b.MobileNetV3ForImageClassification,MobileNetV3Model:()=>b.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>b.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Jt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>b.MobileNetV4ForImageClassification,MobileNetV4Model:()=>b.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>b.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Jt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>b.MobileViTForImageClassification,MobileViTImageProcessor:()=>Jt.MobileViTImageProcessor,MobileViTModel:()=>b.MobileViTModel,MobileViTPreTrainedModel:()=>b.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>b.MobileViTV2ForImageClassification,MobileViTV2Model:()=>b.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>b.MobileViTV2PreTrainedModel,ModelOutput:()=>b.ModelOutput,Moondream1ForConditionalGeneration:()=>b.Moondream1ForConditionalGeneration,MptForCausalLM:()=>b.MptForCausalLM,MptModel:()=>b.MptModel,MptPreTrainedModel:()=>b.MptPreTrainedModel,MusicgenForCausalLM:()=>b.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>b.MusicgenForConditionalGeneration,MusicgenModel:()=>b.MusicgenModel,MusicgenPreTrainedModel:()=>b.MusicgenPreTrainedModel,NllbTokenizer:()=>nr.NllbTokenizer,NomicBertModel:()=>b.NomicBertModel,NomicBertPreTrainedModel:()=>b.NomicBertPreTrainedModel,NougatImageProcessor:()=>Jt.NougatImageProcessor,NougatTokenizer:()=>nr.NougatTokenizer,OPTForCausalLM:()=>b.OPTForCausalLM,OPTModel:()=>b.OPTModel,OPTPreTrainedModel:()=>b.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Wr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>b.OpenELMForCausalLM,OpenELMModel:()=>b.OpenELMModel,OpenELMPreTrainedModel:()=>b.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Jt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>b.OwlViTForObjectDetection,OwlViTModel:()=>b.OwlViTModel,OwlViTPreTrainedModel:()=>b.OwlViTPreTrainedModel,OwlViTProcessor:()=>Jt.OwlViTProcessor,Owlv2ForObjectDetection:()=>b.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Jt.Owlv2ImageProcessor,Owlv2Model:()=>b.Owlv2Model,Owlv2PreTrainedModel:()=>b.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>b.Phi3ForCausalLM,Phi3Model:()=>b.Phi3Model,Phi3PreTrainedModel:()=>b.Phi3PreTrainedModel,PhiForCausalLM:()=>b.PhiForCausalLM,PhiModel:()=>b.PhiModel,PhiPreTrainedModel:()=>b.PhiPreTrainedModel,Pipeline:()=>Wr.Pipeline,PreTrainedModel:()=>b.PreTrainedModel,PreTrainedTokenizer:()=>nr.PreTrainedTokenizer,PretrainedConfig:()=>Fc.PretrainedConfig,PretrainedMixin:()=>b.PretrainedMixin,Processor:()=>Jt.Processor,PyAnnoteFeatureExtractor:()=>Jt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>b.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>b.PyAnnoteModel,PyAnnotePreTrainedModel:()=>b.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Jt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>b.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Wr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>b.Qwen2ForCausalLM,Qwen2Model:()=>b.Qwen2Model,Qwen2PreTrainedModel:()=>b.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>nr.Qwen2Tokenizer,RTDetrForObjectDetection:()=>b.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Jt.RTDetrImageProcessor,RTDetrModel:()=>b.RTDetrModel,RTDetrObjectDetectionOutput:()=>b.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>b.RTDetrPreTrainedModel,RawImage:()=>m_.RawImage,ResNetForImageClassification:()=>b.ResNetForImageClassification,ResNetModel:()=>b.ResNetModel,ResNetPreTrainedModel:()=>b.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>b.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>b.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>b.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>b.RoFormerForTokenClassification,RoFormerModel:()=>b.RoFormerModel,RoFormerPreTrainedModel:()=>b.RoFormerPreTrainedModel,RoFormerTokenizer:()=>nr.RoFormerTokenizer,RobertaForMaskedLM:()=>b.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>b.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>b.RobertaForSequenceClassification,RobertaForTokenClassification:()=>b.RobertaForTokenClassification,RobertaModel:()=>b.RobertaModel,RobertaPreTrainedModel:()=>b.RobertaPreTrainedModel,RobertaTokenizer:()=>nr.RobertaTokenizer,SamImageProcessor:()=>Jt.SamImageProcessor,SamImageSegmentationOutput:()=>b.SamImageSegmentationOutput,SamModel:()=>b.SamModel,SamPreTrainedModel:()=>b.SamPreTrainedModel,SamProcessor:()=>Jt.SamProcessor,SapiensFeatureExtractor:()=>Jt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>b.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>b.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>b.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>b.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Jt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Jt.SegformerFeatureExtractor,SegformerForImageClassification:()=>b.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>b.SegformerForSemanticSegmentation,SegformerModel:()=>b.SegformerModel,SegformerPreTrainedModel:()=>b.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>b.Seq2SeqLMOutput,SequenceClassifierOutput:()=>b.SequenceClassifierOutput,SiglipImageProcessor:()=>Jt.SiglipImageProcessor,SiglipModel:()=>b.SiglipModel,SiglipPreTrainedModel:()=>b.SiglipPreTrainedModel,SiglipTextModel:()=>b.SiglipTextModel,SiglipTokenizer:()=>nr.SiglipTokenizer,SiglipVisionModel:()=>b.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Jt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>b.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>b.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>b.SpeechT5HifiGan,SpeechT5Model:()=>b.SpeechT5Model,SpeechT5PreTrainedModel:()=>b.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Jt.SpeechT5Processor,SpeechT5Tokenizer:()=>nr.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>b.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>b.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>b.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>b.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>b.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>nr.SqueezeBertTokenizer,StableLmForCausalLM:()=>b.StableLmForCausalLM,StableLmModel:()=>b.StableLmModel,StableLmPreTrainedModel:()=>b.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>b.Starcoder2ForCausalLM,Starcoder2Model:()=>b.Starcoder2Model,Starcoder2PreTrainedModel:()=>b.Starcoder2PreTrainedModel,StoppingCriteria:()=>Su.StoppingCriteria,StoppingCriteriaList:()=>Su.StoppingCriteriaList,SummarizationPipeline:()=>Wr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>b.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Jt.Swin2SRImageProcessor,Swin2SRModel:()=>b.Swin2SRModel,Swin2SRPreTrainedModel:()=>b.Swin2SRPreTrainedModel,SwinForImageClassification:()=>b.SwinForImageClassification,SwinModel:()=>b.SwinModel,SwinPreTrainedModel:()=>b.SwinPreTrainedModel,T5ForConditionalGeneration:()=>b.T5ForConditionalGeneration,T5Model:()=>b.T5Model,T5PreTrainedModel:()=>b.T5PreTrainedModel,T5Tokenizer:()=>nr.T5Tokenizer,TableTransformerForObjectDetection:()=>b.TableTransformerForObjectDetection,TableTransformerModel:()=>b.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>b.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>b.TableTransformerPreTrainedModel,Tensor:()=>nn.Tensor,Text2TextGenerationPipeline:()=>Wr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Wr.TextClassificationPipeline,TextGenerationPipeline:()=>Wr.TextGenerationPipeline,TextStreamer:()=>Oc.TextStreamer,TextToAudioPipeline:()=>Wr.TextToAudioPipeline,TokenClassificationPipeline:()=>Wr.TokenClassificationPipeline,TokenClassifierOutput:()=>b.TokenClassifierOutput,TokenizerModel:()=>nr.TokenizerModel,TrOCRForCausalLM:()=>b.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>b.TrOCRPreTrainedModel,TranslationPipeline:()=>Wr.TranslationPipeline,UniSpeechForCTC:()=>b.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>b.UniSpeechForSequenceClassification,UniSpeechModel:()=>b.UniSpeechModel,UniSpeechPreTrainedModel:()=>b.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>b.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>b.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>b.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>b.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>b.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Jt.ViTFeatureExtractor,ViTForImageClassification:()=>b.ViTForImageClassification,ViTImageProcessor:()=>Jt.ViTImageProcessor,ViTModel:()=>b.ViTModel,ViTPreTrainedModel:()=>b.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>b.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>b.VitMatteForImageMatting,VitMatteImageProcessor:()=>Jt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>b.VitMattePreTrainedModel,VitsModel:()=>b.VitsModel,VitsModelOutput:()=>b.VitsModelOutput,VitsPreTrainedModel:()=>b.VitsPreTrainedModel,VitsTokenizer:()=>nr.VitsTokenizer,Wav2Vec2BertForCTC:()=>b.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>b.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>b.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>b.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>nr.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Jt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>b.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>b.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>b.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>b.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>b.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Jt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>b.WavLMForAudioFrameClassification,WavLMForCTC:()=>b.WavLMForCTC,WavLMForSequenceClassification:()=>b.WavLMForSequenceClassification,WavLMForXVector:()=>b.WavLMForXVector,WavLMModel:()=>b.WavLMModel,WavLMPreTrainedModel:()=>b.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Jt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>b.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>b.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Jt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>b.WhisperForConditionalGeneration,WhisperModel:()=>b.WhisperModel,WhisperPreTrainedModel:()=>b.WhisperPreTrainedModel,WhisperProcessor:()=>Jt.WhisperProcessor,WhisperTextStreamer:()=>Oc.WhisperTextStreamer,WhisperTokenizer:()=>nr.WhisperTokenizer,XLMForQuestionAnswering:()=>b.XLMForQuestionAnswering,XLMForSequenceClassification:()=>b.XLMForSequenceClassification,XLMForTokenClassification:()=>b.XLMForTokenClassification,XLMModel:()=>b.XLMModel,XLMPreTrainedModel:()=>b.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>b.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>b.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>b.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>b.XLMRobertaForTokenClassification,XLMRobertaModel:()=>b.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>b.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>nr.XLMRobertaTokenizer,XLMTokenizer:()=>nr.XLMTokenizer,XLMWithLMHeadModel:()=>b.XLMWithLMHeadModel,XVectorOutput:()=>b.XVectorOutput,YolosFeatureExtractor:()=>Jt.YolosFeatureExtractor,YolosForObjectDetection:()=>b.YolosForObjectDetection,YolosModel:()=>b.YolosModel,YolosObjectDetectionOutput:()=>b.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>b.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Wr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Wr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Wr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Wr.ZeroShotObjectDetectionPipeline,bankers_round:()=>En.bankers_round,cat:()=>nn.cat,cos_sim:()=>En.cos_sim,dot:()=>En.dot,dynamic_time_warping:()=>En.dynamic_time_warping,env:()=>f_.env,full:()=>nn.full,full_like:()=>nn.full_like,getKeyValueShapes:()=>Fc.getKeyValueShapes,hamming:()=>Ia.hamming,hanning:()=>Ia.hanning,interpolate:()=>nn.interpolate,interpolate_4d:()=>nn.interpolate_4d,interpolate_data:()=>En.interpolate_data,is_chinese_char:()=>nr.is_chinese_char,layer_norm:()=>nn.layer_norm,log_softmax:()=>En.log_softmax,magnitude:()=>En.magnitude,matmul:()=>nn.matmul,max:()=>En.max,mean:()=>nn.mean,mean_pooling:()=>nn.mean_pooling,medianFilter:()=>En.medianFilter,mel_filter_bank:()=>Ia.mel_filter_bank,min:()=>En.min,ones:()=>nn.ones,ones_like:()=>nn.ones_like,permute:()=>nn.permute,permute_data:()=>En.permute_data,pipeline:()=>Wr.pipeline,quantize_embeddings:()=>nn.quantize_embeddings,read_audio:()=>Ia.read_audio,rfft:()=>nn.rfft,round:()=>En.round,softmax:()=>En.softmax,spectrogram:()=>Ia.spectrogram,stack:()=>nn.stack,std_mean:()=>nn.std_mean,topk:()=>nn.topk,window_function:()=>Ia.window_function,zeros:()=>nn.zeros,zeros_like:()=>nn.zeros_like});var f_=Gr("./src/env.js"),Wr=Gr("./src/pipelines.js"),b=Gr("./src/models.js"),nr=Gr("./src/tokenizers.js"),Jt=Gr("./src/processors.js"),Fc=Gr("./src/configs.js"),Ia=Gr("./src/utils/audio.js"),m_=Gr("./src/utils/image.js"),nn=Gr("./src/utils/tensor.js"),En=Gr("./src/utils/maths.js"),Oc=Gr("./src/generation/streamers.js"),Su=Gr("./src/generation/stopping_criteria.js");p.ASTFeatureExtractor;p.ASTForAudioClassification;p.ASTModel;p.ASTPreTrainedModel;p.AlbertForMaskedLM;p.AlbertForQuestionAnswering;p.AlbertForSequenceClassification;p.AlbertModel;p.AlbertPreTrainedModel;p.AlbertTokenizer;p.AudioClassificationPipeline;p.AutoConfig;p.AutoModel;p.AutoModelForAudioClassification;p.AutoModelForAudioFrameClassification;p.AutoModelForCTC;p.AutoModelForCausalLM;p.AutoModelForDepthEstimation;p.AutoModelForDocumentQuestionAnswering;p.AutoModelForImageClassification;p.AutoModelForImageFeatureExtraction;p.AutoModelForImageMatting;p.AutoModelForImageSegmentation;p.AutoModelForImageToImage;p.AutoModelForMaskGeneration;p.AutoModelForMaskedLM;p.AutoModelForNormalEstimation;p.AutoModelForObjectDetection;p.AutoModelForQuestionAnswering;p.AutoModelForSemanticSegmentation;p.AutoModelForSeq2SeqLM;p.AutoModelForSequenceClassification;p.AutoModelForSpeechSeq2Seq;p.AutoModelForTextToSpectrogram;p.AutoModelForTextToWaveform;p.AutoModelForTokenClassification;p.AutoModelForVision2Seq;p.AutoModelForXVector;p.AutoModelForZeroShotObjectDetection;var __=p.AutoProcessor,g_=p.AutoTokenizer;p.AutomaticSpeechRecognitionPipeline;p.BartForConditionalGeneration;p.BartForSequenceClassification;p.BartModel;p.BartPretrainedModel;p.BartTokenizer;p.BaseModelOutput;p.BaseStreamer;p.BeitFeatureExtractor;p.BeitForImageClassification;p.BeitModel;p.BeitPreTrainedModel;p.BertForMaskedLM;p.BertForQuestionAnswering;p.BertForSequenceClassification;p.BertForTokenClassification;p.BertModel;p.BertPreTrainedModel;p.BertTokenizer;p.BitImageProcessor;p.BlenderbotForConditionalGeneration;p.BlenderbotModel;p.BlenderbotPreTrainedModel;p.BlenderbotSmallForConditionalGeneration;p.BlenderbotSmallModel;p.BlenderbotSmallPreTrainedModel;p.BlenderbotSmallTokenizer;p.BlenderbotTokenizer;p.BloomForCausalLM;p.BloomModel;p.BloomPreTrainedModel;p.BloomTokenizer;p.CLIPFeatureExtractor;p.CLIPImageProcessor;p.CLIPModel;p.CLIPPreTrainedModel;p.CLIPSegForImageSegmentation;p.CLIPSegModel;p.CLIPSegPreTrainedModel;var w_=p.CLIPTextModelWithProjection;p.CLIPTokenizer;var y_=p.CLIPVisionModelWithProjection;p.CamembertForMaskedLM;p.CamembertForQuestionAnswering;p.CamembertForSequenceClassification;p.CamembertForTokenClassification;p.CamembertModel;p.CamembertPreTrainedModel;p.CamembertTokenizer;p.CausalLMOutput;p.CausalLMOutputWithPast;p.ChineseCLIPFeatureExtractor;p.ChineseCLIPModel;p.ChineseCLIPPreTrainedModel;p.ClapAudioModelWithProjection;p.ClapFeatureExtractor;p.ClapModel;p.ClapPreTrainedModel;p.ClapTextModelWithProjection;p.CodeGenForCausalLM;p.CodeGenModel;p.CodeGenPreTrainedModel;p.CodeGenTokenizer;p.CodeLlamaTokenizer;p.CohereForCausalLM;p.CohereModel;p.CoherePreTrainedModel;p.CohereTokenizer;p.ConvBertForMaskedLM;p.ConvBertForQuestionAnswering;p.ConvBertForSequenceClassification;p.ConvBertForTokenClassification;p.ConvBertModel;p.ConvBertPreTrainedModel;p.ConvBertTokenizer;p.ConvNextFeatureExtractor;p.ConvNextForImageClassification;p.ConvNextImageProcessor;p.ConvNextModel;p.ConvNextPreTrainedModel;p.ConvNextV2ForImageClassification;p.ConvNextV2Model;p.ConvNextV2PreTrainedModel;p.DPTFeatureExtractor;p.DPTForDepthEstimation;p.DPTImageProcessor;p.DPTModel;p.DPTPreTrainedModel;p.DebertaForMaskedLM;p.DebertaForQuestionAnswering;p.DebertaForSequenceClassification;p.DebertaForTokenClassification;p.DebertaModel;p.DebertaPreTrainedModel;p.DebertaTokenizer;p.DebertaV2ForMaskedLM;p.DebertaV2ForQuestionAnswering;p.DebertaV2ForSequenceClassification;p.DebertaV2ForTokenClassification;p.DebertaV2Model;p.DebertaV2PreTrainedModel;p.DebertaV2Tokenizer;p.DeiTFeatureExtractor;p.DeiTForImageClassification;p.DeiTModel;p.DeiTPreTrainedModel;p.DepthAnythingForDepthEstimation;p.DepthAnythingPreTrainedModel;p.DepthEstimationPipeline;p.DetrFeatureExtractor;p.DetrForObjectDetection;p.DetrForSegmentation;p.DetrModel;p.DetrObjectDetectionOutput;p.DetrPreTrainedModel;p.DetrSegmentationOutput;p.Dinov2ForImageClassification;p.Dinov2Model;p.Dinov2PreTrainedModel;p.DistilBertForMaskedLM;p.DistilBertForQuestionAnswering;p.DistilBertForSequenceClassification;p.DistilBertForTokenClassification;p.DistilBertModel;p.DistilBertPreTrainedModel;p.DistilBertTokenizer;p.DocumentQuestionAnsweringPipeline;p.DonutFeatureExtractor;p.DonutSwinModel;p.DonutSwinPreTrainedModel;p.EfficientNetForImageClassification;p.EfficientNetImageProcessor;p.EfficientNetModel;p.EfficientNetPreTrainedModel;p.ElectraForMaskedLM;p.ElectraForQuestionAnswering;p.ElectraForSequenceClassification;p.ElectraForTokenClassification;p.ElectraModel;p.ElectraPreTrainedModel;p.ElectraTokenizer;p.EosTokenCriteria;p.EsmForMaskedLM;p.EsmForSequenceClassification;p.EsmForTokenClassification;p.EsmModel;p.EsmPreTrainedModel;p.EsmTokenizer;p.FFT;p.FalconForCausalLM;p.FalconModel;p.FalconPreTrainedModel;p.FalconTokenizer;p.FastViTForImageClassification;p.FastViTModel;p.FastViTPreTrainedModel;p.FeatureExtractionPipeline;p.FeatureExtractor;p.FillMaskPipeline;p.Florence2ForConditionalGeneration;p.Florence2PreTrainedModel;p.Florence2Processor;p.GLPNFeatureExtractor;p.GLPNForDepthEstimation;p.GLPNModel;p.GLPNPreTrainedModel;p.GPT2LMHeadModel;p.GPT2Model;p.GPT2PreTrainedModel;p.GPT2Tokenizer;p.GPTBigCodeForCausalLM;p.GPTBigCodeModel;p.GPTBigCodePreTrainedModel;p.GPTJForCausalLM;p.GPTJModel;p.GPTJPreTrainedModel;p.GPTNeoForCausalLM;p.GPTNeoModel;p.GPTNeoPreTrainedModel;p.GPTNeoXForCausalLM;p.GPTNeoXModel;p.GPTNeoXPreTrainedModel;p.GPTNeoXTokenizer;p.Gemma2ForCausalLM;p.Gemma2Model;p.Gemma2PreTrainedModel;p.GemmaForCausalLM;p.GemmaModel;p.GemmaPreTrainedModel;p.GemmaTokenizer;p.Grok1Tokenizer;p.HerbertTokenizer;p.HieraForImageClassification;p.HieraModel;p.HieraPreTrainedModel;p.HubertForCTC;p.HubertForSequenceClassification;p.HubertModel;p.HubertPreTrainedModel;p.ImageClassificationPipeline;p.ImageFeatureExtractionPipeline;p.ImageFeatureExtractor;p.ImageMattingOutput;p.ImageSegmentationPipeline;p.ImageToImagePipeline;p.ImageToTextPipeline;p.InterruptableStoppingCriteria;p.JAISLMHeadModel;p.JAISModel;p.JAISPreTrainedModel;p.LlamaForCausalLM;p.LlamaModel;p.LlamaPreTrainedModel;p.LlamaTokenizer;p.LlavaForConditionalGeneration;p.LlavaPreTrainedModel;p.LongT5ForConditionalGeneration;p.LongT5Model;p.LongT5PreTrainedModel;p.M2M100ForConditionalGeneration;p.M2M100Model;p.M2M100PreTrainedModel;p.M2M100Tokenizer;p.MBart50Tokenizer;p.MBartForCausalLM;p.MBartForConditionalGeneration;p.MBartForSequenceClassification;p.MBartModel;p.MBartPreTrainedModel;p.MBartTokenizer;p.MPNetForMaskedLM;p.MPNetForQuestionAnswering;p.MPNetForSequenceClassification;p.MPNetForTokenClassification;p.MPNetModel;p.MPNetPreTrainedModel;p.MPNetTokenizer;p.MT5ForConditionalGeneration;p.MT5Model;p.MT5PreTrainedModel;p.MarianMTModel;p.MarianModel;p.MarianPreTrainedModel;p.MarianTokenizer;p.MaskedLMOutput;p.MaxLengthCriteria;p.MistralForCausalLM;p.MistralModel;p.MistralPreTrainedModel;p.MobileBertForMaskedLM;p.MobileBertForQuestionAnswering;p.MobileBertForSequenceClassification;p.MobileBertModel;p.MobileBertPreTrainedModel;p.MobileBertTokenizer;p.MobileNetV1FeatureExtractor;p.MobileNetV1ForImageClassification;p.MobileNetV1Model;p.MobileNetV1PreTrainedModel;p.MobileNetV2FeatureExtractor;p.MobileNetV2ForImageClassification;p.MobileNetV2Model;p.MobileNetV2PreTrainedModel;p.MobileNetV3FeatureExtractor;p.MobileNetV3ForImageClassification;p.MobileNetV3Model;p.MobileNetV3PreTrainedModel;p.MobileNetV4FeatureExtractor;p.MobileNetV4ForImageClassification;p.MobileNetV4Model;p.MobileNetV4PreTrainedModel;p.MobileViTFeatureExtractor;p.MobileViTForImageClassification;p.MobileViTImageProcessor;p.MobileViTModel;p.MobileViTPreTrainedModel;p.MobileViTV2ForImageClassification;p.MobileViTV2Model;p.MobileViTV2PreTrainedModel;p.ModelOutput;p.Moondream1ForConditionalGeneration;p.MptForCausalLM;p.MptModel;p.MptPreTrainedModel;p.MusicgenForCausalLM;p.MusicgenForConditionalGeneration;p.MusicgenModel;p.MusicgenPreTrainedModel;p.NllbTokenizer;p.NomicBertModel;p.NomicBertPreTrainedModel;p.NougatImageProcessor;p.NougatTokenizer;p.OPTForCausalLM;p.OPTModel;p.OPTPreTrainedModel;p.ObjectDetectionPipeline;p.OpenELMForCausalLM;p.OpenELMModel;p.OpenELMPreTrainedModel;p.OwlViTFeatureExtractor;p.OwlViTForObjectDetection;p.OwlViTModel;p.OwlViTPreTrainedModel;p.OwlViTProcessor;p.Owlv2ForObjectDetection;p.Owlv2ImageProcessor;p.Owlv2Model;p.Owlv2PreTrainedModel;p.Phi3ForCausalLM;p.Phi3Model;p.Phi3PreTrainedModel;p.PhiForCausalLM;p.PhiModel;p.PhiPreTrainedModel;p.Pipeline;p.PreTrainedModel;p.PreTrainedTokenizer;p.PretrainedConfig;p.PretrainedMixin;p.Processor;p.PyAnnoteFeatureExtractor;p.PyAnnoteForAudioFrameClassification;p.PyAnnoteModel;p.PyAnnotePreTrainedModel;p.PyAnnoteProcessor;p.QuestionAnsweringModelOutput;p.QuestionAnsweringPipeline;p.Qwen2ForCausalLM;p.Qwen2Model;p.Qwen2PreTrainedModel;p.Qwen2Tokenizer;p.RTDetrForObjectDetection;p.RTDetrImageProcessor;p.RTDetrModel;p.RTDetrObjectDetectionOutput;p.RTDetrPreTrainedModel;var b_=p.RawImage;p.ResNetForImageClassification;p.ResNetModel;p.ResNetPreTrainedModel;p.RoFormerForMaskedLM;p.RoFormerForQuestionAnswering;p.RoFormerForSequenceClassification;p.RoFormerForTokenClassification;p.RoFormerModel;p.RoFormerPreTrainedModel;p.RoFormerTokenizer;p.RobertaForMaskedLM;p.RobertaForQuestionAnswering;p.RobertaForSequenceClassification;p.RobertaForTokenClassification;p.RobertaModel;p.RobertaPreTrainedModel;p.RobertaTokenizer;p.SamImageProcessor;p.SamImageSegmentationOutput;p.SamModel;p.SamPreTrainedModel;p.SamProcessor;p.SapiensFeatureExtractor;p.SapiensForDepthEstimation;p.SapiensForNormalEstimation;p.SapiensForSemanticSegmentation;p.SapiensPreTrainedModel;p.SeamlessM4TFeatureExtractor;p.SegformerFeatureExtractor;p.SegformerForImageClassification;p.SegformerForSemanticSegmentation;p.SegformerModel;p.SegformerPreTrainedModel;p.Seq2SeqLMOutput;p.SequenceClassifierOutput;p.SiglipImageProcessor;p.SiglipModel;p.SiglipPreTrainedModel;p.SiglipTextModel;p.SiglipTokenizer;p.SiglipVisionModel;p.SpeechT5FeatureExtractor;p.SpeechT5ForSpeechToText;p.SpeechT5ForTextToSpeech;p.SpeechT5HifiGan;p.SpeechT5Model;p.SpeechT5PreTrainedModel;p.SpeechT5Processor;p.SpeechT5Tokenizer;p.SqueezeBertForMaskedLM;p.SqueezeBertForQuestionAnswering;p.SqueezeBertForSequenceClassification;p.SqueezeBertModel;p.SqueezeBertPreTrainedModel;p.SqueezeBertTokenizer;p.StableLmForCausalLM;p.StableLmModel;p.StableLmPreTrainedModel;p.Starcoder2ForCausalLM;p.Starcoder2Model;p.Starcoder2PreTrainedModel;p.StoppingCriteria;p.StoppingCriteriaList;p.SummarizationPipeline;p.Swin2SRForImageSuperResolution;p.Swin2SRImageProcessor;p.Swin2SRModel;p.Swin2SRPreTrainedModel;p.SwinForImageClassification;p.SwinModel;p.SwinPreTrainedModel;p.T5ForConditionalGeneration;p.T5Model;p.T5PreTrainedModel;p.T5Tokenizer;p.TableTransformerForObjectDetection;p.TableTransformerModel;p.TableTransformerObjectDetectionOutput;p.TableTransformerPreTrainedModel;p.Tensor;p.Text2TextGenerationPipeline;p.TextClassificationPipeline;p.TextGenerationPipeline;p.TextStreamer;p.TextToAudioPipeline;p.TokenClassificationPipeline;p.TokenClassifierOutput;p.TokenizerModel;p.TrOCRForCausalLM;p.TrOCRPreTrainedModel;p.TranslationPipeline;p.UniSpeechForCTC;p.UniSpeechForSequenceClassification;p.UniSpeechModel;p.UniSpeechPreTrainedModel;p.UniSpeechSatForAudioFrameClassification;p.UniSpeechSatForCTC;p.UniSpeechSatForSequenceClassification;p.UniSpeechSatModel;p.UniSpeechSatPreTrainedModel;p.ViTFeatureExtractor;p.ViTForImageClassification;p.ViTImageProcessor;p.ViTModel;p.ViTPreTrainedModel;p.VisionEncoderDecoderModel;p.VitMatteForImageMatting;p.VitMatteImageProcessor;p.VitMattePreTrainedModel;p.VitsModel;p.VitsModelOutput;p.VitsPreTrainedModel;p.VitsTokenizer;p.Wav2Vec2BertForCTC;p.Wav2Vec2BertForSequenceClassification;p.Wav2Vec2BertModel;p.Wav2Vec2BertPreTrainedModel;p.Wav2Vec2CTCTokenizer;p.Wav2Vec2FeatureExtractor;p.Wav2Vec2ForAudioFrameClassification;p.Wav2Vec2ForCTC;p.Wav2Vec2ForSequenceClassification;p.Wav2Vec2Model;p.Wav2Vec2PreTrainedModel;p.Wav2Vec2ProcessorWithLM;p.WavLMForAudioFrameClassification;p.WavLMForCTC;p.WavLMForSequenceClassification;p.WavLMForXVector;p.WavLMModel;p.WavLMPreTrainedModel;p.WeSpeakerFeatureExtractor;p.WeSpeakerResNetModel;p.WeSpeakerResNetPreTrainedModel;p.WhisperFeatureExtractor;p.WhisperForConditionalGeneration;p.WhisperModel;p.WhisperPreTrainedModel;p.WhisperProcessor;p.WhisperTextStreamer;p.WhisperTokenizer;p.XLMForQuestionAnswering;p.XLMForSequenceClassification;p.XLMForTokenClassification;p.XLMModel;p.XLMPreTrainedModel;p.XLMRobertaForMaskedLM;p.XLMRobertaForQuestionAnswering;p.XLMRobertaForSequenceClassification;p.XLMRobertaForTokenClassification;p.XLMRobertaModel;p.XLMRobertaPreTrainedModel;p.XLMRobertaTokenizer;p.XLMTokenizer;p.XLMWithLMHeadModel;p.XVectorOutput;p.YolosFeatureExtractor;p.YolosForObjectDetection;p.YolosModel;p.YolosObjectDetectionOutput;p.YolosPreTrainedModel;p.ZeroShotAudioClassificationPipeline;p.ZeroShotClassificationPipeline;p.ZeroShotImageClassificationPipeline;p.ZeroShotObjectDetectionPipeline;p.bankers_round;p.cat;p.cos_sim;var M_=p.dot;p.dynamic_time_warping;p.env;p.full;p.full_like;p.getKeyValueShapes;p.hamming;p.hanning;p.interpolate;p.interpolate_4d;p.interpolate_data;p.is_chinese_char;p.layer_norm;p.log_softmax;p.magnitude;p.matmul;p.max;p.mean;p.mean_pooling;p.medianFilter;p.mel_filter_bank;p.min;p.ones;p.ones_like;p.permute;p.permute_data;p.pipeline;p.quantize_embeddings;p.read_audio;p.rfft;p.round;var v_=p.softmax;p.spectrogram;p.stack;p.std_mean;p.topk;p.window_function;p.zeros;p.zeros_like;const Ud=document.getElementById("status"),Tf=document.getElementById("container"),Eu=document.getElementById("video"),Lc=document.getElementById("labels"),Ld=document.getElementById("overlay");async function x_(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}const Rc=await x_()?"fp16":"fp32";Ud.textContent=`Loading model (${Rc==="fp32"?"600":"300"}MB)...`;const Rd="Marqo/marqo-fashionSigLIP";let Pf,Af,If,Ff;try{Pf=await g_.from_pretrained(Rd),Af=await w_.from_pretrained(Rd,{device:"webgpu",dtype:Rc}),If=await __.from_pretrained(Rd),Ff=await y_.from_pretrained(Rd,{device:"webgpu",dtype:Rc})}catch(_t){throw Ud.textContent=_t.message,alert(_t.message),_t}Lc.disabled=!1;Ud.textContent="Ready";const T_=Math.exp(4.6052),gi=224,Nc=document.createElement("canvas");Nc.width=Nc.height=gi;const Sf=Nc.getContext("2d",{willReadFrequently:!0});let zc=!1,Dc,Nd,Bc,jd;function Of(){zc||(zc=!0,async function(){if(Bc!==Lc.value)if(Nd=null,Bc=Lc.value,jd=Bc.split(/\s*,\s*/).filter(_t=>_t),jd.length>0){const _t=Pf(jd,{padding:"max_length",truncation:!0}),{text_embeds:Me}=await Af(_t);Nd=Me.normalize().tolist()}else Ld.innerHTML="";if(Nd){Sf.drawImage(Eu,0,0,gi,gi);const _t=Sf.getImageData(0,0,gi,gi).data,Me=new b_(_t,gi,gi,4),N=await If(Me),{image_embeds:I}=await Ff(N),ae=I.normalize().tolist()[0],he=Nd.map(be=>M_(be,ae)*T_),xe=v_(he).map((be,R)=>[be,R]).sort((be,R)=>R[0]-be[0]);Ld.innerHTML="";for(const[be,R]of xe)Ld.appendChild(document.createTextNode(`${jd[R]}: ${be.toFixed(2)}`)),Ld.appendChild(document.createElement("br"))}if(Dc!==void 0){const _t=1e3/(performance.now()-Dc);Ud.textContent=`FPS: ${_t.toFixed(2)}`}Dc=performance.now(),zc=!1}()),window.requestAnimationFrame(Of)}navigator.mediaDevices.getUserMedia({video:!0}).then(_t=>{Eu.srcObject=_t,Eu.play();const Me=_t.getVideoTracks()[0],{width:N,height:I}=Me.getSettings();Eu.width=N,Eu.height=I;const ae=N/I,[he,xe]=ae>720/405?[720,720/ae]:[405*ae,405];Tf.style.width=`${he}px`,Tf.style.height=`${xe}px`,window.requestAnimationFrame(Of)}).catch(_t=>{alert(_t)});