diff --git "a/assets/worker-D9nS5ej1.js" "b/assets/worker-D9nS5ej1.js" new file mode 100644--- /dev/null +++ "b/assets/worker-D9nS5ej1.js" @@ -0,0 +1,2770 @@ +var hh={},s_={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Ce,A,r)=>{Ce.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Ce,A,r)=>{r.r(A),r.d(A,{Environment:()=>Ye,Interpreter:()=>nt,Template:()=>ht,parse:()=>Z,tokenize:()=>T});var g=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),O=Object.freeze({set:g.Set,for:g.For,in:g.In,is:g.Is,if:g.If,else:g.Else,endif:g.EndIf,elif:g.ElseIf,endfor:g.EndFor,and:g.And,or:g.Or,not:g.Not,"not in":g.NotIn,macro:g.Macro,endmacro:g.EndMacro,true:g.BooleanLiteral,false:g.BooleanLiteral,none:g.NullLiteral,True:g.BooleanLiteral,False:g.BooleanLiteral,None:g.NullLiteral}),j=class{constructor(I,ie){this.value=I,this.type=ie}};function te(I){return/\w/.test(I)}function U(I){return/[0-9]/.test(I)}var y=[["{%",g.OpenStatement],["%}",g.CloseStatement],["{{",g.OpenExpression],["}}",g.CloseExpression],["(",g.OpenParen],[")",g.CloseParen],["{",g.OpenCurlyBracket],["}",g.CloseCurlyBracket],["[",g.OpenSquareBracket],["]",g.CloseSquareBracket],[",",g.Comma],[".",g.Dot],[":",g.Colon],["|",g.Pipe],["<=",g.ComparisonBinaryOperator],[">=",g.ComparisonBinaryOperator],["==",g.ComparisonBinaryOperator],["!=",g.ComparisonBinaryOperator],["<",g.ComparisonBinaryOperator],[">",g.ComparisonBinaryOperator],["+",g.AdditiveBinaryOperator],["-",g.AdditiveBinaryOperator],["*",g.MultiplicativeBinaryOperator],["/",g.MultiplicativeBinaryOperator],["%",g.MultiplicativeBinaryOperator],["=",g.Equals]],P=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function b(I,ie={}){return I.endsWith(` +`)&&(I=I.slice(0,-1)),I=I.replace(/{#.*?#}/gs,"{##}"),ie.lstrip_blocks&&(I=I.replace(/^[ \t]*({[#%])/gm,"$1")),ie.trim_blocks&&(I=I.replace(/([#%]})\n/g,"$1")),I.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function T(I,ie={}){const X=[],_e=b(I,ie);let $e=0;const He=et=>{let ot="";for(;et(_e[$e]);){if(_e[$e]==="\\"){if(++$e,$e>=_e.length)throw new SyntaxError("Unexpected end of input");const yt=_e[$e++],mt=P.get(yt);if(mt===void 0)throw new SyntaxError(`Unexpected escaped character: ${yt}`);ot+=mt;continue}if(ot+=_e[$e++],$e>=_e.length)throw new SyntaxError("Unexpected end of input")}return ot};e:for(;$e<_e.length;){const et=X.at(-1)?.type;if(et===void 0||et===g.CloseStatement||et===g.CloseExpression){let yt="";for(;$e<_e.length&&!(_e[$e]==="{"&&(_e[$e+1]==="%"||_e[$e+1]==="{"));)yt+=_e[$e++];if(yt.length>0){X.push(new j(yt,g.Text));continue}}He(yt=>/\s/.test(yt));const ot=_e[$e];if(ot==="-"||ot==="+"){const yt=X.at(-1)?.type;if(yt===g.Text||yt===void 0)throw new SyntaxError(`Unexpected character: ${ot}`);switch(yt){case g.Identifier:case g.NumericLiteral:case g.BooleanLiteral:case g.NullLiteral:case g.StringLiteral:case g.CloseParen:case g.CloseSquareBracket:break;default:{++$e;const mt=He(U);X.push(new j(`${ot}${mt}`,mt.length>0?g.NumericLiteral:g.UnaryOperator));continue}}}for(const[yt,mt]of y)if(_e.slice($e,$e+yt.length)===yt){X.push(new j(yt,mt)),$e+=yt.length;continue e}if(ot==="'"||ot==='"'){++$e;const yt=He(mt=>mt!==ot);X.push(new j(yt,g.StringLiteral)),++$e;continue}if(U(ot)){const yt=He(U);X.push(new j(yt,g.NumericLiteral));continue}if(te(ot)){const yt=He(te),mt=Object.hasOwn(O,yt)?O[yt]:g.Identifier;mt===g.In&&X.at(-1)?.type===g.Not?(X.pop(),X.push(new j("not in",g.NotIn))):X.push(new j(yt,mt));continue}throw new SyntaxError(`Unexpected character: ${ot}`)}return X}var v=class{type="Statement"},z=class extends v{constructor(I){super(),this.body=I}type="Program"},K=class extends v{constructor(I,ie,X){super(),this.test=I,this.body=ie,this.alternate=X}type="If"},re=class extends v{constructor(I,ie,X,_e){super(),this.loopvar=I,this.iterable=ie,this.body=X,this.defaultBlock=_e}type="For"},ae=class extends v{constructor(I,ie){super(),this.assignee=I,this.value=ie}type="Set"},R=class extends v{constructor(I,ie,X){super(),this.name=I,this.args=ie,this.body=X}type="Macro"},G=class extends v{type="Expression"},H=class extends G{constructor(I,ie,X){super(),this.object=I,this.property=ie,this.computed=X}type="MemberExpression"},D=class extends G{constructor(I,ie){super(),this.callee=I,this.args=ie}type="CallExpression"},$=class extends G{constructor(I){super(),this.value=I}type="Identifier"},w=class extends G{constructor(I){super(),this.value=I}type="Literal"},C=class extends w{type="NumericLiteral"},x=class extends w{type="StringLiteral"},J=class extends w{type="BooleanLiteral"},q=class extends w{type="NullLiteral"},le=class extends w{type="ArrayLiteral"},ce=class extends w{type="TupleLiteral"},fe=class extends w{type="ObjectLiteral"},Pe=class extends G{constructor(I,ie,X){super(),this.operator=I,this.left=ie,this.right=X}type="BinaryExpression"},be=class extends G{constructor(I,ie){super(),this.operand=I,this.filter=ie}type="FilterExpression"},De=class extends G{constructor(I,ie){super(),this.iterable=I,this.test=ie}type="SelectExpression"},Ge=class extends G{constructor(I,ie,X){super(),this.operand=I,this.negate=ie,this.test=X}type="TestExpression"},Ne=class extends G{constructor(I,ie){super(),this.operator=I,this.argument=ie}type="UnaryExpression"},lt=class extends G{constructor(I=void 0,ie=void 0,X=void 0){super(),this.start=I,this.stop=ie,this.step=X}type="SliceExpression"},ue=class extends G{constructor(I,ie){super(),this.key=I,this.value=ie}type="KeywordArgumentExpression"};function Z(I){const ie=new z([]);let X=0;function _e(it,dt){const St=I[X++];if(!St||St.type!==it)throw new Error(`Parser Error: ${dt}. ${St.type} !== ${it}.`);return St}function $e(){switch(I[X].type){case g.Text:return ot();case g.OpenStatement:return yt();case g.OpenExpression:return mt();default:throw new SyntaxError(`Unexpected token type: ${I[X].type}`)}}function He(...it){return X+it.length<=I.length&&it.some((dt,St)=>dt!==I[X+St].type)}function et(...it){return X+it.length<=I.length&&it.every((dt,St)=>dt===I[X+St].type)}function ot(){return new x(_e(g.Text,"Expected text token").value)}function yt(){_e(g.OpenStatement,"Expected opening statement token");let it;switch(I[X].type){case g.Set:++X,it=Qt(),_e(g.CloseStatement,"Expected closing statement token");break;case g.If:++X,it=ts(),_e(g.OpenStatement,"Expected {% token"),_e(g.EndIf,"Expected endif token"),_e(g.CloseStatement,"Expected %} token");break;case g.Macro:++X,it=xs(),_e(g.OpenStatement,"Expected {% token"),_e(g.EndMacro,"Expected endmacro token"),_e(g.CloseStatement,"Expected %} token");break;case g.For:++X,it=$s(),_e(g.OpenStatement,"Expected {% token"),_e(g.EndFor,"Expected endfor token"),_e(g.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${I[X].type}`)}return it}function mt(){_e(g.OpenExpression,"Expected opening expression token");const it=Ms();return _e(g.CloseExpression,"Expected closing expression token"),it}function Qt(){const it=Ms();if(et(g.Equals)){++X;const dt=Qt();return new ae(it,dt)}return it}function ts(){const it=Ms();_e(g.CloseStatement,"Expected closing statement token");const dt=[],St=[];for(;!(I[X]?.type===g.OpenStatement&&(I[X+1]?.type===g.ElseIf||I[X+1]?.type===g.Else||I[X+1]?.type===g.EndIf));)dt.push($e());if(I[X]?.type===g.OpenStatement&&I[X+1]?.type!==g.EndIf)if(++X,et(g.ElseIf))_e(g.ElseIf,"Expected elseif token"),St.push(ts());else for(_e(g.Else,"Expected else token"),_e(g.CloseStatement,"Expected closing statement token");!(I[X]?.type===g.OpenStatement&&I[X+1]?.type===g.EndIf);)St.push($e());return new K(it,dt,St)}function xs(){const it=rr();if(it.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const dt=kr();_e(g.CloseStatement,"Expected closing statement token");const St=[];for(;He(g.OpenStatement,g.EndMacro);)St.push($e());return new R(it,dt,St)}function hs(it=!1){const dt=it?rr:Ms,St=[dt()],cs=et(g.Comma);for(;cs&&(++X,St.push(dt()),!!et(g.Comma)););return cs?new ce(St):St[0]}function $s(){const it=hs(!0);if(!(it instanceof $||it instanceof ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${it.type} instead`);_e(g.In,"Expected `in` keyword following loop variable");const dt=Ms();_e(g.CloseStatement,"Expected closing statement token");const St=[];for(;He(g.OpenStatement,g.EndFor)&&He(g.OpenStatement,g.Else);)St.push($e());const cs=[];if(et(g.OpenStatement,g.Else))for(++X,++X,_e(g.CloseStatement,"Expected closing statement token");He(g.OpenStatement,g.EndFor);)cs.push($e());return new re(it,dt,St,cs)}function Ms(){return Ks()}function Ks(){const it=sr();if(et(g.If)){++X;const dt=sr();if(et(g.Else)){++X;const St=sr();return new K(dt,[it],[St])}else return new De(it,dt)}return it}function sr(){let it=Rr();for(;et(g.Or);){const dt=I[X];++X;const St=Rr();it=new Pe(dt,it,St)}return it}function Rr(){let it=Cr();for(;et(g.And);){const dt=I[X];++X;const St=Cr();it=new Pe(dt,it,St)}return it}function Cr(){let it;for(;et(g.Not);){const dt=I[X];++X;const St=Cr();it=new Ne(dt,St)}return it??an()}function an(){let it=Ot();for(;et(g.ComparisonBinaryOperator)||et(g.In)||et(g.NotIn);){const dt=I[X];++X;const St=Ot();it=new Pe(dt,it,St)}return it}function Ot(){let it=ur();for(;et(g.AdditiveBinaryOperator);){const dt=I[X];++X;const St=ur();it=new Pe(dt,it,St)}return it}function Nr(){const it=Js();return et(g.OpenParen)?br(it):it}function br(it){let dt=new D(it,kr());return et(g.OpenParen)&&(dt=br(dt)),dt}function kr(){_e(g.OpenParen,"Expected opening parenthesis for arguments list");const it=vr();return _e(g.CloseParen,"Expected closing parenthesis for arguments list"),it}function vr(){const it=[];for(;!et(g.CloseParen);){let dt=Ms();if(et(g.Equals)){if(++X,!(dt instanceof $))throw new SyntaxError("Expected identifier for keyword argument");const St=Ms();dt=new ue(dt,St)}it.push(dt),et(g.Comma)&&++X}return it}function Sr(){const it=[];let dt=!1;for(;!et(g.CloseSquareBracket);)et(g.Colon)?(it.push(void 0),++X,dt=!0):(it.push(Ms()),et(g.Colon)&&(++X,dt=!0));if(it.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(dt){if(it.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new lt(...it)}return it[0]}function Js(){let it=rr();for(;et(g.Dot)||et(g.OpenSquareBracket);){const dt=I[X];++X;let St;const cs=dt.type!==g.Dot;if(cs)St=Sr(),_e(g.CloseSquareBracket,"Expected closing square bracket");else if(St=rr(),St.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");it=new H(it,St,cs)}return it}function ur(){let it=Tr();for(;et(g.MultiplicativeBinaryOperator);){const dt=I[X];++X;const St=Tr();it=new Pe(dt,it,St)}return it}function Tr(){let it=jr();for(;et(g.Is);){++X;const dt=et(g.Not);dt&&++X;let St=rr();if(St instanceof J?St=new $(St.value.toString()):St instanceof q&&(St=new $("none")),!(St instanceof $))throw new SyntaxError("Expected identifier for the test");it=new Ge(it,dt,St)}return it}function jr(){let it=Nr();for(;et(g.Pipe);){++X;let dt=rr();if(!(dt instanceof $))throw new SyntaxError("Expected identifier for the filter");et(g.OpenParen)&&(dt=br(dt)),it=new be(it,dt)}return it}function rr(){const it=I[X];switch(it.type){case g.NumericLiteral:return++X,new C(Number(it.value));case g.StringLiteral:return++X,new x(it.value);case g.BooleanLiteral:return++X,new J(it.value.toLowerCase()==="true");case g.NullLiteral:return++X,new q(null);case g.Identifier:return++X,new $(it.value);case g.OpenParen:{++X;const dt=hs();if(I[X].type!==g.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${I[X].type} instead`);return++X,dt}case g.OpenSquareBracket:{++X;const dt=[];for(;!et(g.CloseSquareBracket);)dt.push(Ms()),et(g.Comma)&&++X;return++X,new le(dt)}case g.OpenCurlyBracket:{++X;const dt=new Map;for(;!et(g.CloseCurlyBracket);){const St=Ms();_e(g.Colon,"Expected colon between key and value in object literal");const cs=Ms();dt.set(St,cs),et(g.Comma)&&++X}return++X,new fe(dt)}default:throw new SyntaxError(`Unexpected token: ${it.type}`)}}for(;X=0?(ie=(ie??=0)<0?Math.max(I.length+ie,0):Math.min(ie,I.length),X=(X??=I.length)<0?Math.max(I.length+X,0):Math.min(X,I.length)):(ie=(ie??=I.length-1)<0?Math.max(I.length+ie,-1):Math.min(ie,I.length-1),X=(X??=-1)<-1?Math.max(I.length+X,-1):Math.min(X,I.length-1));const He=[];for(let et=ie;$e*et<$e*X;et+=_e)He.push(I[et]);return He}function Le(I){return I.replace(/\b\w/g,ie=>ie.toUpperCase())}var Ze=class{type="RuntimeValue";value;builtins=new Map;constructor(I=void 0){this.value=I}__bool__(){return new qe(!!this.value)}},Ke=class extends Ze{type="NumericValue"},ne=class extends Ze{type="StringValue";builtins=new Map([["upper",new Re(()=>new ne(this.value.toUpperCase()))],["lower",new Re(()=>new ne(this.value.toLowerCase()))],["strip",new Re(()=>new ne(this.value.trim()))],["title",new Re(()=>new ne(Le(this.value)))],["length",new Ke(this.value.length)],["rstrip",new Re(()=>new ne(this.value.trimEnd()))],["lstrip",new Re(()=>new ne(this.value.trimStart()))]])},qe=class extends Ze{type="BooleanValue"},Ae=class extends Ze{type="ObjectValue";__bool__(){return new qe(this.value.size>0)}builtins=new Map([["get",new Re(([I,ie])=>{if(!(I instanceof ne))throw new Error(`Object key must be a string: got ${I.type}`);return this.value.get(I.value)??ie??new We})],["items",new Re(()=>new Me(Array.from(this.value.entries()).map(([I,ie])=>new Me([new ne(I),ie]))))]])},oe=class extends Ae{type="KeywordArgumentsValue"},Me=class extends Ze{type="ArrayValue";builtins=new Map([["length",new Ke(this.value.length)]]);__bool__(){return new qe(this.value.length>0)}},je=class extends Me{type="TupleValue"},Re=class extends Ze{type="FunctionValue"},We=class extends Ze{type="NullValue"},ze=class extends Ze{type="UndefinedValue"},Ye=class{constructor(I){this.parent=I}variables=new Map([["namespace",new Re(I=>{if(I.length===0)return new Ae(new Map);if(I.length!==1||!(I[0]instanceof Ae))throw new Error("`namespace` expects either zero arguments or a single object argument");return I[0]})]]);tests=new Map([["boolean",I=>I.type==="BooleanValue"],["callable",I=>I instanceof Re],["odd",I=>{if(I.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${I.type}`);return I.value%2!==0}],["even",I=>{if(I.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${I.type}`);return I.value%2===0}],["false",I=>I.type==="BooleanValue"&&!I.value],["true",I=>I.type==="BooleanValue"&&I.value],["none",I=>I.type==="NullValue"],["string",I=>I.type==="StringValue"],["number",I=>I.type==="NumericValue"],["integer",I=>I.type==="NumericValue"&&Number.isInteger(I.value)],["iterable",I=>I.type==="ArrayValue"||I.type==="StringValue"],["mapping",I=>I.type==="ObjectValue"],["lower",I=>{const ie=I.value;return I.type==="StringValue"&&ie===ie.toLowerCase()}],["upper",I=>{const ie=I.value;return I.type==="StringValue"&&ie===ie.toUpperCase()}],["none",I=>I.type==="NullValue"],["defined",I=>I.type!=="UndefinedValue"],["undefined",I=>I.type==="UndefinedValue"],["equalto",(I,ie)=>I.value===ie.value],["eq",(I,ie)=>I.value===ie.value]]);set(I,ie){return this.declareVariable(I,wt(ie))}declareVariable(I,ie){if(this.variables.has(I))throw new SyntaxError(`Variable already declared: ${I}`);return this.variables.set(I,ie),ie}setVariable(I,ie){return this.variables.set(I,ie),ie}resolve(I){if(this.variables.has(I))return this;if(this.parent)return this.parent.resolve(I);throw new Error(`Unknown variable: ${I}`)}lookupVariable(I){try{return this.resolve(I).variables.get(I)??new ze}catch{return new ze}}},nt=class{global;constructor(I){this.global=I??new Ye}run(I){return this.evaluate(I,this.global)}evaluateBinaryExpression(I,ie){const X=this.evaluate(I.left,ie);switch(I.operator.value){case"and":return X.__bool__().value?this.evaluate(I.right,ie):X;case"or":return X.__bool__().value?X:this.evaluate(I.right,ie)}const _e=this.evaluate(I.right,ie);switch(I.operator.value){case"==":return new qe(X.value==_e.value);case"!=":return new qe(X.value!=_e.value)}if(X instanceof ze||_e instanceof ze)throw new Error("Cannot perform operation on undefined values");if(X instanceof We||_e instanceof We)throw new Error("Cannot perform operation on null values");if(X instanceof Ke&&_e instanceof Ke)switch(I.operator.value){case"+":return new Ke(X.value+_e.value);case"-":return new Ke(X.value-_e.value);case"*":return new Ke(X.value*_e.value);case"/":return new Ke(X.value/_e.value);case"%":return new Ke(X.value%_e.value);case"<":return new qe(X.value<_e.value);case">":return new qe(X.value>_e.value);case">=":return new qe(X.value>=_e.value);case"<=":return new qe(X.value<=_e.value)}else if(X instanceof Me&&_e instanceof Me)switch(I.operator.value){case"+":return new Me(X.value.concat(_e.value))}else if(_e instanceof Me){const $e=_e.value.find(He=>He.value===X.value)!==void 0;switch(I.operator.value){case"in":return new qe($e);case"not in":return new qe(!$e)}}if(X instanceof ne||_e instanceof ne)switch(I.operator.value){case"+":return new ne(X.value.toString()+_e.value.toString())}if(X instanceof ne&&_e instanceof ne)switch(I.operator.value){case"in":return new qe(_e.value.includes(X.value));case"not in":return new qe(!_e.value.includes(X.value))}if(X instanceof ne&&_e instanceof Ae)switch(I.operator.value){case"in":return new qe(_e.value.has(X.value));case"not in":return new qe(!_e.value.has(X.value))}throw new SyntaxError(`Unknown operator "${I.operator.value}" between ${X.type} and ${_e.type}`)}evaluateArguments(I,ie){const X=[],_e=new Map;for(const $e of I)if($e.type==="KeywordArgumentExpression"){const He=$e;_e.set(He.key.value,this.evaluate(He.value,ie))}else{if(_e.size>0)throw new Error("Positional arguments must come before keyword arguments");X.push(this.evaluate($e,ie))}return[X,_e]}evaluateFilterExpression(I,ie){const X=this.evaluate(I.operand,ie);if(I.filter.type==="Identifier"){const _e=I.filter;if(_e.value==="tojson")return new ne(ut(X));if(X instanceof Me)switch(_e.value){case"list":return X;case"first":return X.value[0];case"last":return X.value[X.value.length-1];case"length":return new Ke(X.value.length);case"reverse":return new Me(X.value.reverse());case"sort":return new Me(X.value.sort(($e,He)=>{if($e.type!==He.type)throw new Error(`Cannot compare different types: ${$e.type} and ${He.type}`);switch($e.type){case"NumericValue":return $e.value-He.value;case"StringValue":return $e.value.localeCompare(He.value);default:throw new Error(`Cannot compare type: ${$e.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${_e.value}`)}else if(X instanceof ne)switch(_e.value){case"length":return new Ke(X.value.length);case"upper":return new ne(X.value.toUpperCase());case"lower":return new ne(X.value.toLowerCase());case"title":return new ne(Le(X.value));case"capitalize":return new ne(X.value.charAt(0).toUpperCase()+X.value.slice(1));case"trim":return new ne(X.value.trim());case"indent":return new ne(X.value.split(` +`).map(($e,He)=>He===0||$e.length===0?$e:" "+$e).join(` +`));case"string":return X;default:throw new Error(`Unknown StringValue filter: ${_e.value}`)}else if(X instanceof Ke)switch(_e.value){case"abs":return new Ke(Math.abs(X.value));default:throw new Error(`Unknown NumericValue filter: ${_e.value}`)}else if(X instanceof Ae)switch(_e.value){case"items":return new Me(Array.from(X.value.entries()).map(([$e,He])=>new Me([new ne($e),He])));case"length":return new Ke(X.value.size);default:throw new Error(`Unknown ObjectValue filter: ${_e.value}`)}throw new Error(`Cannot apply filter "${_e.value}" to type: ${X.type}`)}else if(I.filter.type==="CallExpression"){const _e=I.filter;if(_e.callee.type!=="Identifier")throw new Error(`Unknown filter: ${_e.callee.type}`);const $e=_e.callee.value;if($e==="tojson"){const[,He]=this.evaluateArguments(_e.args,ie),et=He.get("indent")??new We;if(!(et instanceof Ke||et instanceof We))throw new Error("If set, indent must be a number");return new ne(ut(X,et.value))}if(X instanceof Me){switch($e){case"selectattr":case"rejectattr":{const He=$e==="selectattr";if(X.value.some(ts=>!(ts instanceof Ae)))throw new Error(`\`${$e}\` can only be applied to array of objects`);if(_e.args.some(ts=>ts.type!=="StringLiteral"))throw new Error(`arguments of \`${$e}\` must be strings`);const[et,ot,yt]=_e.args.map(ts=>this.evaluate(ts,ie));let mt;if(ot){const ts=ie.tests.get(ot.value);if(!ts)throw new Error(`Unknown test: ${ot.value}`);mt=ts}else mt=(...ts)=>ts[0].__bool__().value;const Qt=X.value.filter(ts=>{const xs=ts.value.get(et.value),hs=xs?mt(xs,yt):!1;return He?hs:!hs});return new Me(Qt)}case"map":{const[,He]=this.evaluateArguments(_e.args,ie);if(He.has("attribute")){const et=He.get("attribute");if(!(et instanceof ne))throw new Error("attribute must be a string");const ot=He.get("default"),yt=X.value.map(mt=>{if(!(mt instanceof Ae))throw new Error("items in map must be an object");return mt.value.get(et.value)??ot??new ze});return new Me(yt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${$e}`)}else if(X instanceof ne){switch($e){case"indent":{const[He,et]=this.evaluateArguments(_e.args,ie),ot=He.at(0)??et.get("width")??new Ke(4);if(!(ot instanceof Ke))throw new Error("width must be a number");const yt=He.at(1)??et.get("first")??new qe(!1),mt=He.at(2)??et.get("blank")??new qe(!1),Qt=X.value.split(` +`),ts=" ".repeat(ot.value),xs=Qt.map((hs,$s)=>!yt.value&&$s===0||!mt.value&&hs.length===0?hs:ts+hs);return new ne(xs.join(` +`))}}throw new Error(`Unknown StringValue filter: ${$e}`)}else throw new Error(`Cannot apply filter "${$e}" to type: ${X.type}`)}throw new Error(`Unknown filter: ${I.filter.type}`)}evaluateTestExpression(I,ie){const X=this.evaluate(I.operand,ie),_e=ie.tests.get(I.test.value);if(!_e)throw new Error(`Unknown test: ${I.test.value}`);const $e=_e(X);return new qe(I.negate?!$e:$e)}evaluateUnaryExpression(I,ie){const X=this.evaluate(I.argument,ie);switch(I.operator.value){case"not":return new qe(!X.value);default:throw new SyntaxError(`Unknown operator: ${I.operator.value}`)}}evalProgram(I,ie){return this.evaluateBlock(I.body,ie)}evaluateBlock(I,ie){let X="";for(const _e of I){const $e=this.evaluate(_e,ie);$e.type!=="NullValue"&&$e.type!=="UndefinedValue"&&(X+=$e.value)}return new ne(X)}evaluateIdentifier(I,ie){return ie.lookupVariable(I.value)}evaluateCallExpression(I,ie){const[X,_e]=this.evaluateArguments(I.args,ie);_e.size>0&&X.push(new oe(_e));const $e=this.evaluate(I.callee,ie);if($e.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${$e.type}`);return $e.value(X,ie)}evaluateSliceExpression(I,ie,X){if(!(I instanceof Me||I instanceof ne))throw new Error("Slice object must be an array or string");const _e=this.evaluate(ie.start,X),$e=this.evaluate(ie.stop,X),He=this.evaluate(ie.step,X);if(!(_e instanceof Ke||_e instanceof ze))throw new Error("Slice start must be numeric or undefined");if(!($e instanceof Ke||$e instanceof ze))throw new Error("Slice stop must be numeric or undefined");if(!(He instanceof Ke||He instanceof ze))throw new Error("Slice step must be numeric or undefined");return I instanceof Me?new Me(ve(I.value,_e.value,$e.value,He.value)):new ne(ve(Array.from(I.value),_e.value,$e.value,He.value).join(""))}evaluateMemberExpression(I,ie){const X=this.evaluate(I.object,ie);let _e;if(I.computed){if(I.property.type==="SliceExpression")return this.evaluateSliceExpression(X,I.property,ie);_e=this.evaluate(I.property,ie)}else _e=new ne(I.property.value);let $e;if(X instanceof Ae){if(!(_e instanceof ne))throw new Error(`Cannot access property with non-string: got ${_e.type}`);$e=X.value.get(_e.value)??X.builtins.get(_e.value)}else if(X instanceof Me||X instanceof ne)if(_e instanceof Ke)$e=X.value.at(_e.value),X instanceof ne&&($e=new ne(X.value.at(_e.value)));else if(_e instanceof ne)$e=X.builtins.get(_e.value);else throw new Error(`Cannot access property with non-string/non-number: got ${_e.type}`);else{if(!(_e instanceof ne))throw new Error(`Cannot access property with non-string: got ${_e.type}`);$e=X.builtins.get(_e.value)}return $e instanceof Ze?$e:new ze}evaluateSet(I,ie){const X=this.evaluate(I.value,ie);if(I.assignee.type==="Identifier"){const _e=I.assignee.value;ie.setVariable(_e,X)}else if(I.assignee.type==="MemberExpression"){const _e=I.assignee,$e=this.evaluate(_e.object,ie);if(!($e instanceof Ae))throw new Error("Cannot assign to member of non-object");if(_e.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");$e.value.set(_e.property.value,X)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(I.assignee)}`);return new We}evaluateIf(I,ie){const X=this.evaluate(I.test,ie);return this.evaluateBlock(X.__bool__().value?I.body:I.alternate,ie)}evaluateFor(I,ie){const X=new Ye(ie);let _e,$e;if(I.iterable.type==="SelectExpression"){const mt=I.iterable;$e=this.evaluate(mt.iterable,X),_e=mt.test}else $e=this.evaluate(I.iterable,X);if(!($e instanceof Me))throw new Error(`Expected iterable type in for loop: got ${$e.type}`);const He=[],et=[];for(let mt=0;mt<$e.value.length;++mt){const Qt=new Ye(X),ts=$e.value[mt];let xs;if(I.loopvar.type==="Identifier")xs=hs=>hs.setVariable(I.loopvar.value,ts);else if(I.loopvar.type==="TupleLiteral"){const hs=I.loopvar;if(ts.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ts.type}`);const $s=ts;if(hs.value.length!==$s.value.length)throw new Error(`Too ${hs.value.length>$s.value.length?"few":"many"} items to unpack`);xs=Ms=>{for(let Ks=0;Ks0?He[mt-1]:new ze],["nextitem",mt{const $e=new Ye(_e);X=X.slice();let He;X.at(-1)?.type==="KeywordArgumentsValue"&&(He=X.pop());for(let et=0;etthis.evaluate(X,ie)));case"TupleLiteral":return new je(I.value.map(X=>this.evaluate(X,ie)));case"ObjectLiteral":{const X=new Map;for(const[_e,$e]of I.value){const He=this.evaluate(_e,ie);if(!(He instanceof ne))throw new Error(`Object keys must be strings: got ${He.type}`);X.set(He.value,this.evaluate($e,ie))}return new Ae(X)}case"Identifier":return this.evaluateIdentifier(I,ie);case"CallExpression":return this.evaluateCallExpression(I,ie);case"MemberExpression":return this.evaluateMemberExpression(I,ie);case"UnaryExpression":return this.evaluateUnaryExpression(I,ie);case"BinaryExpression":return this.evaluateBinaryExpression(I,ie);case"FilterExpression":return this.evaluateFilterExpression(I,ie);case"TestExpression":return this.evaluateTestExpression(I,ie);default:throw new SyntaxError(`Unknown node type: ${I.type}`)}}};function wt(I){switch(typeof I){case"number":return new Ke(I);case"string":return new ne(I);case"boolean":return new qe(I);case"undefined":return new ze;case"object":return I===null?new We:Array.isArray(I)?new Me(I.map(wt)):new Ae(new Map(Object.entries(I).map(([ie,X])=>[ie,wt(X)])));case"function":return new Re((ie,X)=>{const _e=I(...ie.map($e=>$e.value))??null;return wt(_e)});default:throw new Error(`Cannot convert to runtime value: ${I}`)}}function ut(I,ie,X){const _e=X??0;switch(I.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(I.value);case"ArrayValue":case"ObjectValue":{const $e=ie?" ".repeat(ie):"",He=` +`+$e.repeat(_e),et=He+$e;if(I.type==="ArrayValue"){const ot=I.value.map(yt=>ut(yt,ie,_e+1));return ie?`[${et}${ot.join(`,${et}`)}${He}]`:`[${ot.join(", ")}]`}else{const ot=Array.from(I.value.entries()).map(([yt,mt])=>{const Qt=`"${yt}": ${ut(mt,ie,_e+1)}`;return ie?`${et}${Qt}`:Qt});return ie?`{${ot.join(",")}${He}}`:`{${ot.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${I.type}`)}}var ht=class{parsed;constructor(I){const ie=T(I,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Z(ie)}render(I){const ie=new Ye;ie.set("false",!1),ie.set("true",!0),ie.set("raise_exception",$e=>{throw new Error($e)}),ie.set("range",he);for(const[$e,He]of Object.entries(I))ie.set($e,He);return new nt(ie).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>j,resolveBackendAndExecutionProviders:()=>U});const g=new Map,O=[],j=(y,P,b)=>{if(P&&typeof P.init=="function"&&typeof P.createInferenceSessionHandler=="function"){const T=g.get(y);if(T===void 0)g.set(y,{backend:P,priority:b});else{if(T.priority>b)return;if(T.priority===b&&T.backend!==P)throw new Error(`cannot register backend "${y}" using priority ${b}`)}if(b>=0){const v=O.indexOf(y);v!==-1&&O.splice(v,1);for(let z=0;z{const P=g.get(y);if(!P)return"backend not found.";if(P.initialized)return P.backend;if(P.aborted)return P.error;{const b=!!P.initPromise;try{return b||(P.initPromise=P.backend.init(y)),await P.initPromise,P.initialized=!0,P.backend}catch(T){return b||(P.error=`${T}`,P.aborted=!0),P.error}finally{delete P.initPromise}}},U=async y=>{const P=y.executionProviders||[],b=P.map(ae=>typeof ae=="string"?ae:ae.name),T=b.length===0?O:b;let v;const z=[],K=new Set;for(const ae of T){const R=await te(ae);typeof R=="string"?z.push({name:ae,err:R}):(v||(v=R),v===R&&K.add(ae))}if(!v)throw new Error(`no available backend found. ERR: ${z.map(ae=>`[${ae.name}] ${ae.err}`).join(", ")}`);for(const{name:ae,err:R}of z)b.includes(ae)&&console.warn(`removing requested execution provider "${ae}" from session options because it is not available: ${R}`);const re=P.filter(ae=>K.has(typeof ae=="string"?ae:ae.name));return[v,new Proxy(y,{get:(ae,R)=>R==="executionProviders"?re:Reflect.get(ae,R)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Ce,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>g.registerBackend});var g=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{env:()=>j});var g=r("./node_modules/onnxruntime-common/dist/esm/version.js");let O="warning";const j={wasm:{},webgl:{},webgpu:{},versions:{common:g.version},set logLevel(te){if(te!==void 0){if(typeof te!="string"||["verbose","info","warning","error","fatal"].indexOf(te)===-1)throw new Error(`Unsupported logging level: ${te}`);O=te}},get logLevel(){return O}};Object.defineProperty(j,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Ce,A,r)=>{r.r(A),r.d(A,{env:()=>O});var g=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const O=g.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Ce,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>j.InferenceSession,TRACE:()=>U.TRACE,TRACE_FUNC_BEGIN:()=>U.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>U.TRACE_FUNC_END,Tensor:()=>te.Tensor,TrainingSession:()=>y.TrainingSession,env:()=>O.env,registerBackend:()=>g.registerBackend});var g=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),O=r("./node_modules/onnxruntime-common/dist/esm/env.js"),j=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),te=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var U=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var y=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>te});var g=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),O=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),j=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class te{constructor(y){this.handler=y}async run(y,P,b){(0,j.TRACE_FUNC_BEGIN)();const T={};let v={};if(typeof y!="object"||y===null||y instanceof O.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let z=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof O.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.");z=!1;for(const ae of P){if(typeof ae!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ae)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ae}.`);T[ae]=null}if(typeof b=="object"&&b!==null)v=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ae=!1;const R=Object.getOwnPropertyNames(P);for(const G of this.outputNames)if(R.indexOf(G)!==-1){const H=P[G];(H===null||H instanceof O.Tensor)&&(ae=!0,z=!1,T[G]=H)}if(ae){if(typeof b=="object"&&b!==null)v=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else v=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ae of this.inputNames)if(typeof y[ae]>"u")throw new Error(`input '${ae}' is missing in 'feeds'.`);if(z)for(const ae of this.outputNames)T[ae]=null;const K=await this.handler.run(y,T,v),re={};for(const ae in K)if(Object.hasOwnProperty.call(K,ae)){const R=K[ae];R instanceof O.Tensor?re[ae]=R:re[ae]=new O.Tensor(R.type,R.data,R.dims)}return(0,j.TRACE_FUNC_END)(),re}async release(){return this.handler.dispose()}static async create(y,P,b,T){(0,j.TRACE_FUNC_BEGIN)();let v,z={};if(typeof y=="string"){if(v=y,typeof P=="object"&&P!==null)z=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(y instanceof Uint8Array){if(v=y,typeof P=="object"&&P!==null)z=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(y instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&y instanceof SharedArrayBuffer){const R=y;let G=0,H=y.byteLength;if(typeof P=="object"&&P!==null)z=P;else if(typeof P=="number"){if(G=P,!Number.isSafeInteger(G))throw new RangeError("'byteOffset' must be an integer.");if(G<0||G>=R.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${R.byteLength}).`);if(H=y.byteLength-G,typeof b=="number"){if(H=b,!Number.isSafeInteger(H))throw new RangeError("'byteLength' must be an integer.");if(H<=0||G+H>R.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${R.byteLength-G}].`);if(typeof T=="object"&&T!==null)z=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(typeof b<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof P<"u")throw new TypeError("'options' must be an object.");v=new Uint8Array(R,G,H)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[K,re]=await(0,g.resolveBackendAndExecutionProviders)(z),ae=await K.createInferenceSessionHandler(v,re);return(0,j.TRACE_FUNC_END)(),new te(ae)}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":(Ce,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>O});var g=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const O=g.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Ce,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Ce,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>g,tensorToImageData:()=>O});const g=(j,te)=>{const U=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);U.width=j.dims[3],U.height=j.dims[2];const y=U.getContext("2d");if(y!=null){let P,b;te?.tensorLayout!==void 0&&te.tensorLayout==="NHWC"?(P=j.dims[2],b=j.dims[3]):(P=j.dims[3],b=j.dims[2]);const T=te?.format!==void 0?te.format:"RGB",v=te?.norm;let z,K;v===void 0||v.mean===void 0?z=[255,255,255,255]:typeof v.mean=="number"?z=[v.mean,v.mean,v.mean,v.mean]:(z=[v.mean[0],v.mean[1],v.mean[2],0],v.mean[3]!==void 0&&(z[3]=v.mean[3])),v===void 0||v.bias===void 0?K=[0,0,0,0]:typeof v.bias=="number"?K=[v.bias,v.bias,v.bias,v.bias]:(K=[v.bias[0],v.bias[1],v.bias[2],0],v.bias[3]!==void 0&&(K[3]=v.bias[3]));const re=b*P;let ae=0,R=re,G=re*2,H=-1;T==="RGBA"?(ae=0,R=re,G=re*2,H=re*3):T==="RGB"?(ae=0,R=re,G=re*2):T==="RBG"&&(ae=0,G=re,R=re*2);for(let D=0;D{const U=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let y;if(U!=null){let P,b,T;te?.tensorLayout!==void 0&&te.tensorLayout==="NHWC"?(P=j.dims[2],b=j.dims[1],T=j.dims[3]):(P=j.dims[3],b=j.dims[2],T=j.dims[1]);const v=te!==void 0&&te.format!==void 0?te.format:"RGB",z=te?.norm;let K,re;z===void 0||z.mean===void 0?K=[255,255,255,255]:typeof z.mean=="number"?K=[z.mean,z.mean,z.mean,z.mean]:(K=[z.mean[0],z.mean[1],z.mean[2],255],z.mean[3]!==void 0&&(K[3]=z.mean[3])),z===void 0||z.bias===void 0?re=[0,0,0,0]:typeof z.bias=="number"?re=[z.bias,z.bias,z.bias,z.bias]:(re=[z.bias[0],z.bias[1],z.bias[2],0],z.bias[3]!==void 0&&(re[3]=z.bias[3]));const ae=b*P;if(te!==void 0&&(te.format!==void 0&&T===4&&te.format!=="RGBA"||T===3&&te.format!=="RGB"&&te.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const R=4;let G=0,H=1,D=2,$=3,w=0,C=ae,x=ae*2,J=-1;v==="RGBA"?(w=0,C=ae,x=ae*2,J=ae*3):v==="RGB"?(w=0,C=ae,x=ae*2):v==="RBG"&&(w=0,x=ae,C=ae*2),y=U.createImageData(P,b);for(let q=0;q{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>O,tensorFromGpuBuffer:()=>U,tensorFromImage:()=>j,tensorFromMLTensor:()=>y,tensorFromPinnedBuffer:()=>P,tensorFromTexture:()=>te});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const O=(b,T)=>{if(b===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");const{height:v,width:z}=T,K=T.norm??{mean:255,bias:0};let re,ae;typeof K.mean=="number"?re=[K.mean,K.mean,K.mean,K.mean]:re=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?ae=[K.bias,K.bias,K.bias,K.bias]:ae=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];const R=T.format!==void 0?T.format:"RGBA",G=T.tensorFormat!==void 0&&T.tensorFormat!==void 0?T.tensorFormat:"RGB",H=v*z,D=G==="RGBA"?new Float32Array(H*4):new Float32Array(H*3);let $=4,w=0,C=1,x=2,J=3,q=0,le=H,ce=H*2,fe=-1;R==="RGB"&&($=3,w=0,C=1,x=2,J=-1),G==="RGBA"?fe=H*3:G==="RBG"?(q=0,ce=H,le=H*2):G==="BGR"&&(ce=0,le=H,q=H*2);for(let be=0;be{const v=typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement,z=typeof ImageData<"u"&&b instanceof ImageData,K=typeof ImageBitmap<"u"&&b instanceof ImageBitmap,re=typeof b=="string";let ae,R=T??{};const G=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},H=D=>typeof HTMLCanvasElement<"u"&&D instanceof HTMLCanvasElement||D instanceof OffscreenCanvas?D.getContext("2d"):null;if(v){const D=G();D.width=b.width,D.height=b.height;const $=H(D);if($!=null){let w=b.height,C=b.width;if(T!==void 0&&T.resizedHeight!==void 0&&T.resizedWidth!==void 0&&(w=T.resizedHeight,C=T.resizedWidth),T!==void 0){if(R=T,T.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");R.tensorFormat="RGBA",R.height=w,R.width=C}else R.tensorFormat="RGBA",R.height=w,R.width=C;$.drawImage(b,0,0),ae=$.getImageData(0,0,C,w).data}else throw new Error("Can not access image data")}else if(z){let D,$;if(T!==void 0&&T.resizedWidth!==void 0&&T.resizedHeight!==void 0?(D=T.resizedHeight,$=T.resizedWidth):(D=b.height,$=b.width),T!==void 0&&(R=T),R.format="RGBA",R.height=D,R.width=$,T!==void 0){const w=G();w.width=$,w.height=D;const C=H(w);if(C!=null)C.putImageData(b,0,0),ae=C.getImageData(0,0,$,D).data;else throw new Error("Can not access image data")}else ae=b.data}else if(K){if(T===void 0)throw new Error("Please provide image config with format for Imagebitmap");const D=G();D.width=b.width,D.height=b.height;const $=H(D);if($!=null){const w=b.height,C=b.width;return $.drawImage(b,0,0,C,w),ae=$.getImageData(0,0,C,w).data,R.height=w,R.width=C,O(ae,R)}else throw new Error("Can not access image data")}else{if(re)return new Promise((D,$)=>{const w=G(),C=H(w);if(!b||!C)return $();const x=new Image;x.crossOrigin="Anonymous",x.src=b,x.onload=()=>{w.width=x.width,w.height=x.height,C.drawImage(x,0,0,w.width,w.height);const J=C.getImageData(0,0,w.width,w.height);R.height=w.height,R.width=w.width,D(O(J.data,R))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ae!==void 0)return O(ae,R);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(b,T)=>{const{width:v,height:z,download:K,dispose:re}=T,ae=[1,z,v,4];return new g.Tensor({location:"texture",type:"float32",texture:b,dims:ae,download:K,dispose:re})},U=(b,T)=>{const{dataType:v,dims:z,download:K,dispose:re}=T;return new g.Tensor({location:"gpu-buffer",type:v??"float32",gpuBuffer:b,dims:z,download:K,dispose:re})},y=(b,T)=>{const{dataType:v,dims:z,download:K,dispose:re}=T;return new g.Tensor({location:"ml-tensor",type:v??"float32",mlTensor:b,dims:z,download:K,dispose:re})},P=(b,T,v)=>new g.Tensor({location:"cpu-pinned",type:b,data:T,dims:v??[T.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Ce,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Ce,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>O,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>g,checkTypedArray:()=>te});const g=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),O=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let j=!1;const te=()=>{if(!j){j=!0;const U=typeof BigInt64Array<"u"&&BigInt64Array.from,y=typeof BigUint64Array<"u"&&BigUint64Array.from,P=typeof Float16Array<"u"&&Float16Array.from;U&&(g.set("int64",BigInt64Array),O.set(BigInt64Array,"int64")),y&&(g.set("uint64",BigUint64Array),O.set(BigUint64Array,"uint64")),P?(g.set("float16",Float16Array),O.set(Float16Array,"float16")):g.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{Tensor:()=>U});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),O=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),j=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),te=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class U{constructor(P,b,T){(0,j.checkTypedArray)();let v,z;if(typeof P=="object"&&"location"in P)switch(this.dataLocation=P.location,v=P.type,z=P.dims,P.location){case"cpu-pinned":{const re=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(!re)throw new TypeError(`unsupported type "${v}" to create tensor from pinned buffer`);if(!(P.data instanceof re))throw new TypeError(`buffer should be of type ${re.name}`);this.cpuData=P.data;break}case"texture":{if(v!=="float32")throw new TypeError(`unsupported type "${v}" to create tensor from texture`);this.gpuTextureData=P.texture,this.downloader=P.download,this.disposer=P.dispose;break}case"gpu-buffer":{if(v!=="float32"&&v!=="float16"&&v!=="int32"&&v!=="int64"&&v!=="uint32"&&v!=="uint8"&&v!=="bool"&&v!=="uint4"&&v!=="int4")throw new TypeError(`unsupported type "${v}" to create tensor from gpu buffer`);this.gpuBufferData=P.gpuBuffer,this.downloader=P.download,this.disposer=P.dispose;break}case"ml-tensor":{if(v!=="float32"&&v!=="float16"&&v!=="int32"&&v!=="int64"&&v!=="uint32"&&v!=="uint64"&&v!=="int8"&&v!=="uint8"&&v!=="bool")throw new TypeError(`unsupported type "${v}" to create tensor from MLTensor`);this.mlTensorData=P.mlTensor,this.downloader=P.download,this.disposer=P.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let re,ae;if(typeof P=="string")if(v=P,ae=T,P==="string"){if(!Array.isArray(b))throw new TypeError("A string tensor's data must be a string array.");re=b}else{const R=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(P);if(R===void 0)throw new TypeError(`Unsupported tensor type: ${P}.`);if(Array.isArray(b)){if(P==="float16"&&R===Uint16Array||P==="uint4"||P==="int4")throw new TypeError(`Creating a ${P} tensor from number array is not supported. Please use ${R.name} as data.`);P==="uint64"||P==="int64"?re=R.from(b,BigInt):re=R.from(b)}else if(b instanceof R)re=b;else if(b instanceof Uint8ClampedArray)if(P==="uint8")re=Uint8Array.from(b);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${v} tensor's data must be type of ${R}`)}else if(ae=b,Array.isArray(P)){if(P.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const R=typeof P[0];if(R==="string")v="string",re=P;else if(R==="boolean")v="bool",re=Uint8Array.from(P);else throw new TypeError(`Invalid element type of data array: ${R}.`)}else if(P instanceof Uint8ClampedArray)v="uint8",re=Uint8Array.from(P);else{const R=j.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(P.constructor);if(R===void 0)throw new TypeError(`Unsupported type for tensor data: ${P.constructor}.`);v=R,re=P}if(ae===void 0)ae=[re.length];else if(!Array.isArray(ae))throw new TypeError("A tensor's dims must be a number array");z=ae,this.cpuData=re,this.dataLocation="cpu"}const K=(0,te.calculateSize)(z);if(this.cpuData&&K!==this.cpuData.length&&!((v==="uint4"||v==="int4")&&Math.ceil(K/2)===this.cpuData.length))throw new Error(`Tensor's size(${K}) does not match data length(${this.cpuData.length}).`);this.type=v,this.dims=z,this.size=K}static async fromImage(P,b){return(0,O.tensorFromImage)(P,b)}static fromTexture(P,b){return(0,O.tensorFromTexture)(P,b)}static fromGpuBuffer(P,b){return(0,O.tensorFromGpuBuffer)(P,b)}static fromMLTensor(P,b){return(0,O.tensorFromMLTensor)(P,b)}static fromPinnedBuffer(P,b,T){return(0,O.tensorFromPinnedBuffer)(P,b,T)}toDataURL(P){return(0,g.tensorToDataURL)(this,P)}toImageData(P){return(0,g.tensorToImageData)(this,P)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(P){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const b=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=b,P&&this.disposer&&(this.disposer(),this.disposer=void 0),b}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(P){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,te.tensorReshape)(this,P)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>O,tensorReshape:()=>j});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const O=te=>{let U=1;for(let y=0;y{switch(te.location){case"cpu":return new g.Tensor(te.type,te.data,U);case"cpu-pinned":return new g.Tensor({location:"cpu-pinned",data:te.data,type:te.type,dims:U});case"texture":return new g.Tensor({location:"texture",texture:te.texture,type:te.type,dims:U});case"gpu-buffer":return new g.Tensor({location:"gpu-buffer",gpuBuffer:te.gpuBuffer,type:te.type,dims:U});case"ml-tensor":return new g.Tensor({location:"ml-tensor",mlTensor:te.mlTensor,type:te.type,dims:U});default:throw new Error(`tensorReshape: tensor location ${te.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Ce,A,r)=>{r.r(A),r.d(A,{Tensor:()=>O});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const O=g.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Ce,A,r)=>{r.r(A),r.d(A,{TRACE:()=>O,TRACE_FUNC_BEGIN:()=>te,TRACE_FUNC_END:()=>U});var g=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const O=(y,P)=>{(typeof g.env.trace>"u"?!g.env.wasm.trace:!g.env.trace)||console.timeStamp(`${y}::ORT::${P}`)},j=(y,P)=>{const b=new Error().stack?.split(/\r\n|\r|\n/g)||[];let T=!1;for(let v=0;v{(typeof g.env.trace>"u"?!g.env.wasm.trace:!g.env.trace)||j("BEGIN",y)},U=y=>{(typeof g.env.trace>"u"?!g.env.wasm.trace:!g.env.trace)||j("END",y)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Ce,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>te});var g=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),O=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const j="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class te{constructor(y,P,b){this.handler=y,this.hasOptimizerModel=P,this.hasEvalModel=b}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(y,P){const b=y.evalModel||"",T=y.optimizerModel||"",v=P||{},[z,K]=await(0,g.resolveBackendAndExecutionProviders)(v);if(z.createTrainingSessionHandler){const re=await z.createTrainingSessionHandler(y.checkpointState,y.trainModel,b,T,K);return new te(re,!!y.optimizerModel,!!y.evalModel)}else throw new Error(j)}typeNarrowingForRunStep(y,P,b,T,v){const z={};let K={};if(typeof b!="object"||b===null||b instanceof O.Tensor||Array.isArray(b))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let re=!0;if(typeof T=="object"){if(T===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(T instanceof O.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(T)){if(T.length===0)throw new TypeError("'fetches' cannot be an empty array.");re=!1;for(const ae of T){if(typeof ae!="string")throw new TypeError("'fetches' must be a string array or an object.");if(P.indexOf(ae)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ae}.`);z[ae]=null}if(typeof v=="object"&&v!==null)K=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else{let ae=!1;const R=Object.getOwnPropertyNames(T);for(const G of P)if(R.indexOf(G)!==-1){const H=T[G];(H===null||H instanceof O.Tensor)&&(ae=!0,re=!1,z[G]=H)}if(ae){if(typeof v=="object"&&v!==null)K=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else K=T}}else if(typeof T<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ae of y)if(typeof b[ae]>"u")throw new Error(`input '${ae}' is missing in 'feeds'.`);if(re)for(const ae of P)z[ae]=null;return[z,K]}convertHandlerReturnTypeToMapOfTensors(y){const P={};for(const b in y)if(Object.hasOwnProperty.call(y,b)){const T=y[b];T instanceof O.Tensor?P[b]=T:P[b]=new O.Tensor(T.type,T.data,T.dims)}return P}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(y,P,b){const[T,v]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,y,P,b),z=await this.handler.runTrainStep(y,T,v);return this.convertHandlerReturnTypeToMapOfTensors(z)}async runOptimizerStep(y){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(y||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(y,P,b){if(this.hasEvalModel){const[T,v]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,y,P,b),z=await this.handler.runEvalStep(y,T,v);return this.convertHandlerReturnTypeToMapOfTensors(z)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(y=!0){return this.handler.getParametersSize(y)}async loadParametersBuffer(y,P=!0){const b=await this.getParametersSize(P);if(y.length!==4*b)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(y,P)}async getContiguousParameters(y=!0){return this.handler.getContiguousParameters(y)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Ce,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>O});var g=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const O=g.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Ce,A,r)=>{r.r(A),r.d(A,{version:()=>g});const g="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs":(Ce,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>ut,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>We,TRACE_FUNC_END:()=>ze,Tensor:()=>oe,default:()=>c_,env:()=>x,registerBackend:()=>K});/*! + * ONNX Runtime Web v1.21.0-dev.20241205-d27fecd3d3 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var g=Object.defineProperty,O=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyNames,te=Object.prototype.hasOwnProperty,U=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),y=(e,t)=>()=>(e&&(t=e(e=0)),t),P=(e,t)=>{for(var s in t)g(e,s,{get:t[s],enumerable:!0})},b=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of j(t))!te.call(e,o)&&o!==s&&g(e,o,{get:()=>t[o],enumerable:!(n=O(t,o))||n.enumerable});return e},T=e=>b(g({},"__esModule",{value:!0}),e),v,z,K,re,ae,R=y(()=>{v=new Map,z=[],K=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=v.get(e);if(n===void 0)v.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=z.indexOf(e);o!==-1&&z.splice(o,1);for(let i=0;i{let t=v.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ae=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?z:s,o,i=[],a=new Set;for(let p of n){let h=await re(p);typeof h=="string"?i.push({name:p,err:h}):(o||(o=h),o===h&&a.add(p))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of i)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let c=t.filter(p=>a.has(typeof p=="string"?p:p.name));return[o,new Proxy(e,{get:(p,h)=>h==="executionProviders"?c:Reflect.get(p,h)})]}}),G=y(()=>{R()}),H,D=y(()=>{H="1.21.0-dev.20241205-6ed77cc374"}),$,w,C=y(()=>{D(),$="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:H},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);$=e}},get logLevel(){return $}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),x,J=y(()=>{C(),x=w}),q,le,ce=y(()=>{q=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:"RGB",c=t?.norm,p,h;c===void 0||c.mean===void 0?p=[255,255,255,255]:typeof c.mean=="number"?p=[c.mean,c.mean,c.mean,c.mean]:(p=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(p[3]=c.mean[3])),c===void 0||c.bias===void 0?h=[0,0,0,0]:typeof c.bias=="number"?h=[c.bias,c.bias,c.bias,c.bias]:(h=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(h[3]=c.bias[3]));let k=i*o,u=0,S=k,B=k*2,N=-1;a==="RGBA"?(u=0,S=k,B=k*2,N=k*3):a==="RGB"?(u=0,S=k,B=k*2):a==="RBG"&&(u=0,B=k,S=k*2);for(let L=0;L{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t?.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let u=i*o;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 S=4,B=0,N=1,L=2,se=3,ee=0,V=u,de=u*2,me=-1;c==="RGBA"?(ee=0,V=u,de=u*2,me=u*3):c==="RGB"?(ee=0,V=u,de=u*2):c==="RBG"&&(ee=0,de=u,V=u*2),n=s.createImageData(o,i);for(let ye=0;ye{Ae(),fe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean=="number"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),u=4,S=0,B=1,N=2,L=3,se=0,ee=h,V=h*2,de=-1;c==="RGB"&&(u=3,S=0,B=1,N=2,L=-1),p==="RGBA"?de=h*3:p==="RBG"?(se=0,V=h,ee=h*2):p==="BGR"&&(V=0,ee=h,se=h*2);for(let me=0;me{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",a,c=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(s){let k=p();k.width=e.width,k.height=e.height;let u=h(k);if(u!=null){let S=e.height,B=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(S=t.resizedHeight,B=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=S,c.width=B}else c.tensorFormat="RGBA",c.height=S,c.width=B;u.drawImage(e,0,0),a=u.getImageData(0,0,B,S).data}else throw new Error("Can not access image data")}else if(n){let k,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,u=t.resizedWidth):(k=e.height,u=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=k,c.width=u,t!==void 0){let S=p();S.width=u,S.height=k;let B=h(S);if(B!=null)B.putImageData(e,0,0),a=B.getImageData(0,0,u,k).data;else throw new Error("Can not access image data")}else a=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let u=h(k);if(u!=null){let S=e.height,B=e.width;return u.drawImage(e,0,0,B,S),a=u.getImageData(0,0,B,S).data,c.height=S,c.width=B,fe(a,c)}else throw new Error("Can not access image data")}else{if(i)return new Promise((k,u)=>{let S=p(),B=h(S);if(!e||!B)return u();let N=new Image;N.crossOrigin="Anonymous",N.src=e,N.onload=()=>{S.width=N.width,S.height=N.height,B.drawImage(N,0,0,S.width,S.height);let L=B.getImageData(0,0,S.width,S.height);c.height=S.height,c.width=S.width,k(fe(L.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return fe(a,c);throw new Error("Input data provided is not supported - aborted tensor creation")},be=(e,t)=>{let{width:s,height:n,download:o,dispose:i}=t,a=[1,n,s,4];return new qe({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},De=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:i}=t;return new qe({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},Ge=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:i}=t;return new qe({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:o,dispose:i})},Ne=(e,t,s)=>new qe({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),ue,Z,he,ve,Le=y(()=>{ue=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Z=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),he=!1,ve=()=>{if(!he){he=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(ue.set("int64",BigInt64Array),Z.set(BigInt64Array,"int64")),t&&(ue.set("uint64",BigUint64Array),Z.set(BigUint64Array,"uint64")),s?(ue.set("float16",Float16Array),Z.set(Float16Array,"float16")):ue.set("float16",Uint16Array)}}}),Ze,Ke,ne=y(()=>{Ae(),Ze=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new qe(e.type,e.data,t);case"cpu-pinned":return new qe({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new qe({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new qe({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new qe({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),qe,Ae=y(()=>{ce(),lt(),Le(),ne(),qe=class{constructor(e,t,s){ve();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let a=ue.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}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,c;if(typeof e=="string")if(n=e,c=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let p=ue.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?a=p.from(t,BigInt):a=p.from(t)}else if(t instanceof p)a=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${p}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",a=e;else if(p==="boolean")n="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(e);else{let p=Z.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,a=e}if(c===void 0)c=[a.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");o=c,this.cpuData=a,this.dataLocation="cpu"}let i=Ze(o);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=o,this.size=i}static async fromImage(e,t){return Pe(e,t)}static fromTexture(e,t){return be(e,t)}static fromGpuBuffer(e,t){return De(e,t)}static fromMLTensor(e,t){return Ge(e,t)}static fromPinnedBuffer(e,t,s){return Ne(e,t,s)}toDataURL(e){return q(this,e)}toImageData(e){return le(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ke(this,e)}}}),oe,Me=y(()=>{Ae(),oe=qe}),je,Re,We,ze,Ye=y(()=>{C(),je=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},Re=(e,t)=>{let s=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let o=0;o{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Re("BEGIN",e)},ze=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Re("END",e)}}),nt,wt=y(()=>{R(),Me(),Ye(),nt=class r_{constructor(t){this.handler=t}async run(t,s,n){We();let o={},i={};if(typeof t!="object"||t===null||t instanceof oe||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 s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof oe)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.");a=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(s);for(let u of this.outputNames)if(k.indexOf(u)!==-1){let S=s[u];(S===null||S instanceof oe)&&(h=!0,a=!1,o[u]=S)}if(h){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(a)for(let h of this.outputNames)o[h]=null;let c=await this.handler.run(t,o,i),p={};for(let h in c)if(Object.hasOwnProperty.call(c,h)){let k=c[h];k instanceof oe?p[h]=k:p[h]=new oe(k.type,k.data,k.dims)}return ze(),p}async release(){return this.handler.dispose()}static async create(t,s,n,o){We();let i,a={};if(typeof t=="string"){if(i=t,typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,u=0,S=t.byteLength;if(typeof s=="object"&&s!==null)a=s;else if(typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(S=t.byteLength-u,typeof n=="number"){if(S=n,!Number.isSafeInteger(S))throw new RangeError("'byteLength' must be an integer.");if(S<=0||u+S>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-u}].`);if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(k,u,S)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,p]=await ae(a),h=await c.createInferenceSessionHandler(i,p);return ze(),new r_(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ut,ht=y(()=>{wt(),ut=nt}),I=y(()=>{}),ie=y(()=>{}),X=y(()=>{}),_e=y(()=>{}),$e={};P($e,{InferenceSession:()=>ut,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>We,TRACE_FUNC_END:()=>ze,Tensor:()=>oe,env:()=>x,registerBackend:()=>K});var He=y(()=>{G(),J(),ht(),Me(),I(),ie(),Ye(),X(),_e()}),et=y(()=>{}),ot={};P(ot,{default:()=>Qt});var yt,mt,Qt,ts=y(()=>{Mh(),St(),vr(),yt="ort-wasm-proxy-worker",mt=globalThis.self?.name===yt,mt&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":it(s.wasm).then(()=>{Op(s).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:o}=s;Fp(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=s,o=ap(n);postMessage({type:t,out:o});break}case"create":{let{model:n,options:o}=s;Dp(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":Lp(s),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:c}=s;Bp(n,o,i,a,new Array(a.length).fill(null),c).then(p=>{p.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:p},Np([...i,...p]))},p=>{postMessage({type:t,err:p})});break}case"end-profiling":Rp(s),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),Qt=mt?null:e=>new Worker(e??sr,{type:"module",name:yt})}),xs={};P(xs,{default:()=>Ms});var hs,$s,Ms,Ks=y(()=>{$s=(hs=import.meta.url,async function(e={}){function t(){return jt.buffer!=Jt.buffer&&Ys(),Jt}function s(){return jt.buffer!=Jt.buffer&&Ys(),qt}function n(){return jt.buffer!=Jt.buffer&&Ys(),Qs}function o(){return jt.buffer!=Jt.buffer&&Ys(),at}function i(){return jt.buffer!=Jt.buffer&&Ys(),Pt}function a(){return jt.buffer!=Jt.buffer&&Ys(),ps}function c(){return jt.buffer!=Jt.buffer&&Ys(),vs}function p(){return jt.buffer!=Jt.buffer&&Ys(),Gs}var h,k,u=Object.assign({},e),S=new Promise((l,m)=>{h=l,k=m}),B=typeof window=="object",N=typeof importScripts=="function",L=N&&self.name=="em-pthread";u.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(u.Fb||(u.Fb=new Map)).set(l,m)},u.unmountExternalData=()=>{delete u.Fb};var se=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let ee=()=>{let l=(E,F,W)=>(...we)=>{let Ve=nn,Je=F?.();we=E(...we);let Tt=F?.();return Je!==Tt&&(E=Tt,W(Je),F=W=null),nn!=Ve?new Promise((Et,Nt)=>{oh={resolve:Et,reject:Nt}}):we},m=E=>async(...F)=>{try{if(u.Gb)throw Error("Session already started");let W=u.Gb={hc:F[0],errors:[]},we=await E(...F);if(u.Gb!==W)throw Error("Session mismatch");u.Hb?.flush();let Ve=W.errors;if(0Tt),0u._OrtCreateSession,E=>u._OrtCreateSession=E),u._OrtRun=m(l(u._OrtRun,()=>u._OrtRun,E=>u._OrtRun=E)),u._OrtRunWithBinding=m(l(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,E=>u._OrtRunWithBinding=E)),u._OrtBindInput=l(u._OrtBindInput,()=>u._OrtBindInput,E=>u._OrtBindInput=E),ee=void 0};u.jsepInit=(l,m)=>{if(ee?.(),l==="webgpu"){[u.Hb,u.Vb,u.Zb,u.Ob,u.Yb,u.kb,u.$b,u.cc,u.Wb,u.Xb,u.ac]=m;let E=u.Hb;u.jsepRegisterBuffer=(F,W,we,Ve)=>E.registerBuffer(F,W,we,Ve),u.jsepGetBuffer=F=>E.getBuffer(F),u.jsepCreateDownloader=(F,W,we)=>E.createDownloader(F,W,we),u.jsepOnCreateSession=F=>{E.onCreateSession(F)},u.jsepOnReleaseSession=F=>{E.onReleaseSession(F)},u.jsepOnRunStart=F=>E.onRunStart(F),u.dc=(F,W)=>{E.upload(F,W)}}else if(l==="webnn"){[u.Hb,u.bc,u.Pb,u.jsepEnsureTensor,u.ec,u.jsepDownloadTensor]=m,u.jsepReleaseTensorId=u.Pb;let E=u.Hb;u.jsepOnRunStart=F=>E.onRunStart(F),u.jsepRegisterMLContext=(F,W)=>{E.registerMLContext(F,W)},u.jsepOnReleaseSession=F=>{E.onReleaseSession(F)},u.jsepCreateMLTensorDownloader=(F,W)=>E.createMLTensorDownloader(F,W),u.jsepRegisterMLTensor=(F,W,we)=>E.registerMLTensor(F,W,we),u.jsepCreateMLContext=F=>E.createMLContext(F),u.jsepRegisterMLConstant=(F,W,we,Ve,Je)=>E.registerMLConstant(F,W,we,Ve,Je,u.Fb)}};var V,de,me=Object.assign({},u),ye="./this.program",Be=(l,m)=>{throw m},Ee="";(B||N)&&(N?Ee=self.location.href:typeof document<"u"&&document.currentScript&&(Ee=document.currentScript.src),hs&&(Ee=hs),Ee=Ee.startsWith("blob:")?"":Ee.substr(0,Ee.replace(/[?#].*/,"").lastIndexOf("/")+1),N&&(de=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),V=(l,m,E)=>{var F=new XMLHttpRequest;F.open("GET",l,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?m(F.response):E()},F.onerror=E,F.send(null)});var tt,pt=console.log.bind(console),Ct=console.error.bind(console),Dt=pt,$t=Ct;if(Object.assign(u,me),me=null,L){let l=function(m){try{var E=m.data,F=E.cmd;if(F==="load"){let W=[];self.onmessage=we=>W.push(we),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let we of W)l(we);self.onmessage=l};for(let we of E.handlers)u[we]&&!u[we].proxy||(u[we]=(...Ve)=>{postMessage({Nb:"callHandler",pc:we,args:Ve})},we=="print"&&(Dt=u[we]),we=="printErr"&&($t=u[we]));jt=E.wasmMemory,Ys(),bt(E.wasmModule)}else if(F==="run"){uh(E.pthread_ptr,0,0,1,0,0),rh(E.pthread_ptr),__(),Wh(),Kt||(jm(),Kt=!0);try{f_(E.start_routine,E.arg)}catch(W){if(W!="unwind")throw W}}else F==="cancel"?Pa()&&vp(-1):E.target!=="setimmediate"&&(F==="checkMailbox"?Kt&&pp():F&&($t(`worker: received unknown command ${F}`),$t(E)))}catch(W){throw Um(),W}};var bt,Kt=!1;$t=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Pa()})},u.instantiateWasm=(m,E)=>new Promise(F=>{bt=W=>{W=new WebAssembly.Instance(W,Rh()),E(W),F()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}u.wasmBinary&&(tt=u.wasmBinary);var jt,Lt,ss,Jt,qt,Qs,at,Pt,ps,vs,Ts,yn,Gs,Cs=!1;function Ys(){var l=jt.buffer;u.HEAP8=Jt=new Int8Array(l),u.HEAP16=Qs=new Int16Array(l),u.HEAPU8=qt=new Uint8Array(l),u.HEAPU16=at=new Uint16Array(l),u.HEAP32=Pt=new Int32Array(l),u.HEAPU32=ps=new Uint32Array(l),u.HEAPF32=vs=new Float32Array(l),u.HEAPF64=Gs=new Float64Array(l),u.HEAP64=Ts=new BigInt64Array(l),u.HEAPU64=yn=new BigUint64Array(l)}if(!L){if(!((jt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof se))throw $t("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");Ys()}var dp=[],Vd=[],p_=[],Wd=0,Gd=null;function Fh(){if(--Wd==0&&Gd){var l=Gd;Gd=null,l()}}function Vn(l){throw $t(l="Aborted("+l+")"),Cs=!0,ss=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),k(l),l}var Gp,Dh=l=>l.startsWith("data:application/octet-stream;base64,"),Lh=l=>l.startsWith("file://");function zh(l){if(l==Gp&&tt)return new Uint8Array(tt);if(de)return de(l);throw"both async and sync fetching of the wasm failed"}function Bh(l,m,E){return function(F){if(!tt&&(B||N)){if(typeof fetch=="function"&&!Lh(F))return fetch(F,{credentials:"same-origin"}).then(W=>{if(!W.ok)throw`failed to load wasm binary file at '${F}'`;return W.arrayBuffer()}).catch(()=>zh(F));if(V)return new Promise((W,we)=>{V(F,Ve=>W(new Uint8Array(Ve)),we)})}return Promise.resolve().then(()=>zh(F))}(l).then(F=>WebAssembly.instantiate(F,m)).then(E,F=>{$t(`failed to asynchronously prepare wasm: ${F}`),Vn(F)})}function Rh(){return{a:{O:m_,Aa:h_,b:w_,aa:qh,B:Yh,qa:Jh,Y:em,_:tm,ra:sm,oa:rm,ha:nm,na:om,L:im,Z:am,W:lm,pa:um,X:dm,va:y_,F:M_,Q:b_,P:T_,E:P_,u:E_,q:C_,G:k_,A:D_,R:L_,ua:z_,ka:B_,U:R_,ba:N_,H:j_,ja:rh,ta:U_,t:V_,Ba:W_,x:H_,n:q_,l:Q_,c:th,o:Y_,j:ef,w:tf,p:sf,f:rf,s:nf,m:of,e:af,k:lf,i:uf,h:df,d:cf,ea:pf,fa:hf,ga:mf,ca:xm,da:Pm,T:_f,g:ff,D:gf,I:wf,M:yf,y:Mf,sa:bf,V:vf,v:Cm,z:Tf,N:xf,S:Pf,za:Ef,ya:Cf,la:$m,ma:Am,$:Qp,C:Im,K:Om,ia:Fm,J:Dm,a:jt,xa:Xp,wa:Bm,r:$f}}}var Kp={874308:(l,m,E,F,W)=>{if(u===void 0||!u.Fb)return 1;if((l=Ds(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=u.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),F=Number(F>>>0),m+E>l.byteLength)return 3;try{let we=l.subarray(m,m+E);switch(W){case 0:s().set(we,F>>>0);break;case 1:u.dc(F,we);break;default:return 4}return 0}catch{return 4}},875023:(l,m,E)=>{u.ec(l,s().subarray(m>>>0,m+E>>>0))},875086:()=>u.bc(),875127:l=>{u.Pb(l)},875163:()=>{u.Wb()},875194:()=>{u.Xb()},875223:()=>{u.ac()},875248:l=>u.Vb(l),875281:l=>u.Zb(l),875313:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E),!0)},875376:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E))},875433:()=>typeof wasmOffsetConverter<"u",875490:l=>{u.kb("Abs",l,void 0)},875541:l=>{u.kb("Neg",l,void 0)},875592:l=>{u.kb("Floor",l,void 0)},875645:l=>{u.kb("Ceil",l,void 0)},875697:l=>{u.kb("Reciprocal",l,void 0)},875755:l=>{u.kb("Sqrt",l,void 0)},875807:l=>{u.kb("Exp",l,void 0)},875858:l=>{u.kb("Erf",l,void 0)},875909:l=>{u.kb("Sigmoid",l,void 0)},875964:(l,m,E)=>{u.kb("HardSigmoid",l,{alpha:m,beta:E})},876043:l=>{u.kb("Log",l,void 0)},876094:l=>{u.kb("Sin",l,void 0)},876145:l=>{u.kb("Cos",l,void 0)},876196:l=>{u.kb("Tan",l,void 0)},876247:l=>{u.kb("Asin",l,void 0)},876299:l=>{u.kb("Acos",l,void 0)},876351:l=>{u.kb("Atan",l,void 0)},876403:l=>{u.kb("Sinh",l,void 0)},876455:l=>{u.kb("Cosh",l,void 0)},876507:l=>{u.kb("Asinh",l,void 0)},876560:l=>{u.kb("Acosh",l,void 0)},876613:l=>{u.kb("Atanh",l,void 0)},876666:l=>{u.kb("Tanh",l,void 0)},876718:l=>{u.kb("Not",l,void 0)},876769:(l,m,E)=>{u.kb("Clip",l,{min:m,max:E})},876838:l=>{u.kb("Clip",l,void 0)},876890:(l,m)=>{u.kb("Elu",l,{alpha:m})},876948:l=>{u.kb("Gelu",l,void 0)},877e3:l=>{u.kb("Relu",l,void 0)},877052:(l,m)=>{u.kb("LeakyRelu",l,{alpha:m})},877116:(l,m)=>{u.kb("ThresholdedRelu",l,{alpha:m})},877186:(l,m)=>{u.kb("Cast",l,{to:m})},877244:l=>{u.kb("Add",l,void 0)},877295:l=>{u.kb("Sub",l,void 0)},877346:l=>{u.kb("Mul",l,void 0)},877397:l=>{u.kb("Div",l,void 0)},877448:l=>{u.kb("Pow",l,void 0)},877499:l=>{u.kb("Equal",l,void 0)},877552:l=>{u.kb("Greater",l,void 0)},877607:l=>{u.kb("GreaterOrEqual",l,void 0)},877669:l=>{u.kb("Less",l,void 0)},877721:l=>{u.kb("LessOrEqual",l,void 0)},877780:(l,m,E,F,W)=>{u.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},877955:(l,m,E,F,W)=>{u.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},878129:(l,m,E,F,W)=>{u.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},878303:(l,m,E,F,W)=>{u.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},878478:(l,m,E,F,W)=>{u.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},878652:(l,m,E,F,W)=>{u.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},878825:(l,m,E,F,W)=>{u.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},878998:(l,m,E,F,W)=>{u.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},879175:(l,m,E,F,W)=>{u.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},879355:(l,m,E,F,W)=>{u.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},879535:l=>{u.kb("Where",l,void 0)},879588:(l,m,E)=>{u.kb("Transpose",l,{perm:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},879712:(l,m,E,F)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:Ds(E),format:F?"NHWC":"NCHW"})},879845:(l,m,E,F)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:Ds(E),format:F?"NHWC":"NCHW"})},879978:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue,is)=>{u.kb("ConvTranspose",l,{format:Tt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:F,kernelShape:[W],pads:[we,Ve],strides:[Je],wIsConst:()=>!!t()[Et>>>0],outputPadding:Nt?Array.from(i().subarray(Number(Nt)>>>0,Number(ls)>>>0)):[],outputShape:fs?Array.from(i().subarray(Number(fs)>>>0,Number(Ue)>>>0)):[],activation:Ds(is)})},880411:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue)=>{u.kb("ConvTranspose",l,{format:Je?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:F,kernelShape:Array.from(i().subarray(Number(W)>>>0,2+(Number(W)>>>0)>>>0)),pads:Array.from(i().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ve)>>>0,2+(Number(Ve)>>>0)>>>0)),wIsConst:()=>!!t()[Tt>>>0],outputPadding:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],outputShape:ls?Array.from(i().subarray(Number(ls)>>>0,Number(fs)>>>0)):[],activation:Ds(Ue)})},881072:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue,is)=>{u.kb("ConvTranspose",l,{format:Tt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:F,kernelShape:[W],pads:[we,Ve],strides:[Je],wIsConst:()=>!!t()[Et>>>0],outputPadding:Nt?Array.from(i().subarray(Number(Nt)>>>0,Number(ls)>>>0)):[],outputShape:fs?Array.from(i().subarray(Number(fs)>>>0,Number(Ue)>>>0)):[],activation:Ds(is)})},881505:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue)=>{u.kb("ConvTranspose",l,{format:Je?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:F,kernelShape:Array.from(i().subarray(Number(W)>>>0,2+(Number(W)>>>0)>>>0)),pads:Array.from(i().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ve)>>>0,2+(Number(Ve)>>>0)>>>0)),wIsConst:()=>!!t()[Tt>>>0],outputPadding:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],outputShape:ls?Array.from(i().subarray(Number(ls)>>>0,Number(fs)>>>0)):[],activation:Ds(Ue)})},882166:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882257:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue)=>{u.kb("AveragePool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:W,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ve)>>>0)):[],kernel_shape:Je?Array.from(i().subarray(Number(Je)>>>0,Number(Tt)>>>0)):[],pads:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],strides:ls?Array.from(i().subarray(Number(ls)>>>0,Number(fs)>>>0)):[]})},882736:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882827:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue)=>{u.kb("AveragePool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:W,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ve)>>>0)):[],kernel_shape:Je?Array.from(i().subarray(Number(Je)>>>0,Number(Tt)>>>0)):[],pads:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],strides:ls?Array.from(i().subarray(Number(ls)>>>0,Number(fs)>>>0)):[]})},883306:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883393:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue)=>{u.kb("MaxPool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:W,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ve)>>>0)):[],kernel_shape:Je?Array.from(i().subarray(Number(Je)>>>0,Number(Tt)>>>0)):[],pads:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],strides:ls?Array.from(i().subarray(Number(ls)>>>0,Number(fs)>>>0)):[]})},883868:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883955:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue)=>{u.kb("MaxPool",l,{format:Ue?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:W,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ve)>>>0)):[],kernel_shape:Je?Array.from(i().subarray(Number(Je)>>>0,Number(Tt)>>>0)):[],pads:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],strides:ls?Array.from(i().subarray(Number(ls)>>>0,Number(fs)>>>0)):[]})},884430:(l,m,E,F,W)=>{u.kb("Gemm",l,{alpha:m,beta:E,transA:F,transB:W})},884534:l=>{u.kb("MatMul",l,void 0)},884588:(l,m,E,F)=>{u.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:F})},884696:(l,m,E,F)=>{u.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:F})},884804:(l,m)=>{u.kb("Softmax",l,{axis:m})},884867:(l,m)=>{u.kb("Concat",l,{axis:m})},884927:(l,m,E,F,W)=>{u.kb("Split",l,{axis:m,numOutputs:E,splitSizes:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},885083:l=>{u.kb("Expand",l,void 0)},885137:(l,m)=>{u.kb("Gather",l,{axis:Number(m)})},885208:(l,m)=>{u.kb("GatherElements",l,{axis:Number(m)})},885287:(l,m)=>{u.kb("GatherND",l,{batch_dims:Number(m)})},885366:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt)=>{u.kb("Resize",l,{antialias:m,axes:E?Array.from(i().subarray(Number(E)>>>0,Number(F)>>>0)):[],coordinateTransformMode:Ds(W),cubicCoeffA:we,excludeOutside:Ve,extrapolationValue:Je,keepAspectRatioPolicy:Ds(Tt),mode:Ds(Et),nearestMode:Ds(Nt)})},885728:(l,m,E,F,W,we,Ve)=>{u.kb("Slice",l,{starts:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[],axes:we?Array.from(i().subarray(Number(we)>>>0,Number(Ve)>>>0)):[]})},885992:l=>{u.kb("Tile",l,void 0)},886044:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886158:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886272:l=>{u.kb("Range",l,void 0)},886325:(l,m)=>{u.kb("Einsum",l,{equation:Ds(m)})},886406:(l,m,E,F,W)=>{u.kb("Pad",l,{mode:m,value:E,pads:F?Array.from(i().subarray(Number(F)>>>0,Number(W)>>>0)):[]})},886549:(l,m,E,F,W,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!W,trainingMode:!!F,format:we?"NHWC":"NCHW"})},886718:(l,m,E,F,W,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!W,trainingMode:!!F,format:we?"NHWC":"NCHW"})},886887:(l,m,E)=>{u.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},886984:(l,m,E)=>{u.kb("DequantizeLinear",l,{axis:m,blockSize:E})},887074:(l,m,E,F,W)=>{u.kb("GridSample",l,{align_corners:m,mode:Ds(E),padding_mode:Ds(F),format:W?"NHWC":"NCHW"})},887244:(l,m,E,F,W)=>{u.kb("GridSample",l,{align_corners:m,mode:Ds(E),padding_mode:Ds(F),format:W?"NHWC":"NCHW"})},887414:(l,m)=>{u.kb("ScatterND",l,{reduction:Ds(m)})},887499:(l,m,E,F,W,we,Ve,Je,Tt)=>{u.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:F,scale:W,doRotary:we,qkvHiddenSizes:Ve?Array.from(i().subarray(Number(Je)>>>0,Number(Je)+Ve>>>0)):[],pastPresentShareBuffer:!!Tt})},887771:l=>{u.kb("BiasAdd",l,void 0)},887826:l=>{u.kb("BiasSplitGelu",l,void 0)},887887:l=>{u.kb("FastGelu",l,void 0)},887943:(l,m,E,F,W,we,Ve,Je,Tt,Et,Nt,ls,fs,Ue,is,Ls)=>{u.kb("Conv",l,{format:ls?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(i().subarray(Number(E)>>>0,Number(F)>>>0)):[],group:W,kernel_shape:we?Array.from(i().subarray(Number(we)>>>0,Number(Ve)>>>0)):[],pads:Je?Array.from(i().subarray(Number(Je)>>>0,Number(Tt)>>>0)):[],strides:Et?Array.from(i().subarray(Number(Et)>>>0,Number(Nt)>>>0)):[],w_is_const:()=>!!t()[Number(fs)>>>0],activation:Ds(Ue),activation_params:is?Array.from(c().subarray(Number(is)>>>0,Number(Ls)>>>0)):[]})},888527:l=>{u.kb("Gelu",l,void 0)},888579:(l,m,E,F,W,we,Ve,Je,Tt)=>{u.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:F,softcap:W,doRotary:we,rotaryInterleaved:Ve,smoothSoftmax:Je,localWindowSize:Tt})},888796:(l,m,E,F)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!F})},888907:(l,m,E,F)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!F})},889018:(l,m,E,F,W,we)=>{u.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:F,bits:W,blockSize:we})},889145:(l,m,E,F,W,we)=>{u.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:F,scale:W,doRotary:we})},889304:(l,m)=>{u.kb("QuickGelu",l,{alpha:m})},889368:(l,m,E,F,W)=>{u.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:F,scale:W})},889507:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889609:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889711:(l,m,E,F)=>{u.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:F})},889832:l=>{u.$b(l)},889866:(l,m)=>u.cc(Number(l),Number(m),u.Gb.hc,u.Gb.errors)};function h_(l,m,E){return ym(async()=>{await u.Yb(Number(l),Number(m),Number(E))})}function m_(){return typeof wasmOffsetConverter<"u"}function Hp(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var qp=l=>{l.terminate(),l.onmessage=()=>{}},Nh=l=>{Wn.length==0&&(Kh(),Gh(Wn[0]));var m=Wn.pop();if(!m)return 6;Eo.push(m),sn[l.Bb]=m,m.Bb=l.Bb;var E={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(E,l.nc),0},Po=0,Ss=(l,m,...E)=>{for(var F=2*E.length,W=ph(),we=ch(8*F),Ve=we>>>3,Je=0;Je>>0]=Tt)}return l=Vm(l,0,F,we,m),Tp(W),l};function Xp(l){if(L)return Ss(0,1,l);if(ss=l,!(0{if(ss=l,L)throw jh(l),"unwind";Xp(l)},Wn=[],Eo=[],Uh=[],sn={},Vh=l=>{var m=l.Bb;delete sn[m],Wn.push(l),Eo.splice(Eo.indexOf(l),1),l.Bb=0,dh(m)};function Wh(){Uh.forEach(l=>l())}var Gh=l=>new Promise(m=>{l.onmessage=W=>{var we=(W=W.data).cmd;if(W.targetThread&&W.targetThread!=Pa()){var Ve=sn[W.targetThread];Ve?Ve.postMessage(W,W.transferList):$t(`Internal error! Worker sent a message "${we}" to target pthread ${W.targetThread}, but that thread no longer exists!`)}else we==="checkMailbox"?pp():we==="spawnThread"?Nh(W):we==="cleanupThread"?Vh(sn[W.thread]):we==="killThread"?(W=W.thread,we=sn[W],delete sn[W],qp(we),dh(W),Eo.splice(Eo.indexOf(we),1),we.Bb=0):we==="cancelThread"?sn[W.thread].postMessage({cmd:"cancel"}):we==="loaded"?(l.loaded=!0,m(l)):we==="alert"?alert(`Thread ${W.threadId}: ${W.text}`):W.target==="setimmediate"?l.postMessage(W):we==="callHandler"?u[W.handler](...W.args):we&&$t(`worker sent an unknown command ${we}`)},l.onerror=W=>{throw $t(`worker sent an error! ${W.filename}:${W.lineno}: ${W.message}`),W};var E,F=[];for(E of[])u.hasOwnProperty(E)&&F.push(E);l.postMessage({cmd:"load",handlers:F,wasmMemory:jt,wasmModule:Lt})});function Kh(){var l=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Wn.push(l)}var cp=l=>{for(;0{var l=Pa(),m=a()[l+52>>>2>>>0];l=a()[l+56>>>2>>>0],Gm(m,m-l),Tp(m)},f_=(l,m)=>{Po=0,l=Km(l,m),0>>=0);throw m>>>=0,E>>>=0,a()[F.Kb+16>>>2>>>0]=0,a()[F.Kb+4>>>2>>>0]=m,a()[F.Kb+8>>>2>>>0]=E,l}function Hh(l,m,E,F){return L?Ss(2,1,l,m,E,F):qh(l,m,E,F)}function qh(l,m,E,F){if(l>>>=0,m>>>=0,E>>>=0,F>>>=0,se===void 0)return $t("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var W=[];return L&&W.length===0?Hh(l,m,E,F):(l={ic:E,Bb:l,Rb:F,nc:W},L?(l.Nb="spawnThread",postMessage(l,W),0):Nh(l))}var Xh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Qh=(l,m,E)=>{var F=(m>>>=0)+E;for(E=m;l[E]&&!(E>=F);)++E;if(16(W=(240&W)==224?(15&W)<<12|we<<6|Ve:(7&W)<<18|we<<12|Ve<<6|63&l[m++])?F+=String.fromCharCode(W):(W-=65536,F+=String.fromCharCode(55296|W>>10,56320|1023&W))}}else F+=String.fromCharCode(W)}return F},Ds=(l,m)=>(l>>>=0)?Qh(s(),l,m):"";function Yh(l,m,E){return L?Ss(3,1,l,m,E):0}function Jh(l,m){if(L)return Ss(4,1,l,m)}var Yp=l=>{for(var m=0,E=0;E=F?m++:2047>=F?m+=2:55296<=F&&57343>=F?(m+=4,++E):m+=3}return m},Zh=(l,m,E,F)=>{if(!(0>>=0;F=E+F-1;for(var we=0;we=Ve&&(Ve=65536+((1023&Ve)<<10)|1023&l.charCodeAt(++we)),127>=Ve){if(E>=F)break;m[E++>>>0]=Ve}else{if(2047>=Ve){if(E+1>=F)break;m[E++>>>0]=192|Ve>>6}else{if(65535>=Ve){if(E+2>=F)break;m[E++>>>0]=224|Ve>>12}else{if(E+3>=F)break;m[E++>>>0]=240|Ve>>18,m[E++>>>0]=128|Ve>>12&63}m[E++>>>0]=128|Ve>>6&63}m[E++>>>0]=128|63&Ve}}return m[E>>>0]=0,E-W},Ta=(l,m,E)=>Zh(l,s(),m,E);function em(l,m){if(L)return Ss(5,1,l,m)}function tm(l,m,E){if(L)return Ss(6,1,l,m,E)}function sm(l,m,E){return L?Ss(7,1,l,m,E):0}function rm(l,m){if(L)return Ss(8,1,l,m)}function nm(l,m,E){if(L)return Ss(9,1,l,m,E)}function om(l,m,E,F){if(L)return Ss(10,1,l,m,E,F)}function im(l,m,E,F){if(L)return Ss(11,1,l,m,E,F)}function am(l,m,E,F){if(L)return Ss(12,1,l,m,E,F)}function lm(l){if(L)return Ss(13,1,l)}function um(l,m){if(L)return Ss(14,1,l,m)}function dm(l,m,E){if(L)return Ss(15,1,l,m,E)}var cm,Gn,y_=()=>{Vn("")},rn=l=>{for(var m="";s()[l>>>0];)m+=cm[s()[l++>>>0]];return m},Jp={},Zp={};function Mn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(F,W,we={}){var Ve=W.name;if(!F)throw new Gn(`type "${Ve}" must have a positive integer typeid pointer`);if(Zp.hasOwnProperty(F)){if(we.Tb)return;throw new Gn(`Cannot register type '${Ve}' twice`)}Zp[F]=W,Jp.hasOwnProperty(F)&&(W=Jp[F],delete Jp[F],W.forEach(Je=>Je()))}(l,m,E)}var pm=(l,m,E)=>{switch(m){case 1:return E?F=>t()[F>>>0]:F=>s()[F>>>0];case 2:return E?F=>n()[F>>>1>>>0]:F=>o()[F>>>1>>>0];case 4:return E?F=>i()[F>>>2>>>0]:F=>a()[F>>>2>>>0];case 8:return E?F=>Ts[F>>>3]:F=>yn[F>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function M_(l,m,E){E>>>=0,Mn(l>>>=0,{name:m=rn(m>>>0),fromWireType:F=>F,toWireType:function(F,W){if(typeof W!="bigint"&&typeof W!="number")throw W=W===null?"null":(F=typeof W)=="object"||F==="array"||F==="function"?W.toString():""+W,new TypeError(`Cannot convert "${W}" to ${this.name}`);return typeof W=="number"&&(W=BigInt(W)),W},argPackAdvance:Kn,readValueFromPointer:pm(m,E,m.indexOf("u")==-1),Eb:null})}var Kn=8;function b_(l,m,E,F){Mn(l>>>=0,{name:m=rn(m>>>0),fromWireType:function(W){return!!W},toWireType:function(W,we){return we?E:F},argPackAdvance:Kn,readValueFromPointer:function(W){return this.fromWireType(s()[W>>>0])},Eb:null})}var eh=[],bn=[];function th(l){9<(l>>>=0)&&--bn[l+1]==0&&(bn[l]=void 0,eh.push(l))}var Mr=l=>{if(!l)throw new Gn("Cannot use deleted val. handle = "+l);return bn[l]},Er=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=eh.pop()||bn.length;return bn[m]=l,bn[m+1]=1,m}};function sh(l){return this.fromWireType(a()[l>>>2>>>0])}var v_={name:"emscripten::val",fromWireType:l=>{var m=Mr(l);return th(l),m},toWireType:(l,m)=>Er(m),argPackAdvance:Kn,readValueFromPointer:sh,Eb:null};function T_(l){return Mn(l>>>0,v_)}var x_=(l,m)=>{switch(m){case 4:return function(E){return this.fromWireType(c()[E>>>2>>>0])};case 8:return function(E){return this.fromWireType(p()[E>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function P_(l,m,E){E>>>=0,Mn(l>>>=0,{name:m=rn(m>>>0),fromWireType:F=>F,toWireType:(F,W)=>W,argPackAdvance:Kn,readValueFromPointer:x_(m,E),Eb:null})}function E_(l,m,E,F,W){if(l>>>=0,E>>>=0,m=rn(m>>>0),W===-1&&(W=4294967295),W=Je=>Je,F===0){var we=32-8*E;W=Je=>Je<>>we}var Ve=m.includes("unsigned")?function(Je,Tt){return Tt>>>0}:function(Je,Tt){return Tt};Mn(l,{name:m,fromWireType:W,toWireType:Ve,argPackAdvance:Kn,readValueFromPointer:pm(m,E,F!==0),Eb:null})}function C_(l,m,E){function F(we){var Ve=a()[we>>>2>>>0];return we=a()[we+4>>>2>>>0],new W(t().buffer,we,Ve)}var W=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Mn(l>>>=0,{name:E=rn(E>>>0),fromWireType:F,argPackAdvance:Kn,readValueFromPointer:F},{Tb:!0})}function k_(l,m){l>>>=0;var E=(m=rn(m>>>0))==="std::string";Mn(l,{name:m,fromWireType:function(F){var W=a()[F>>>2>>>0],we=F+4;if(E)for(var Ve=we,Je=0;Je<=W;++Je){var Tt=we+Je;if(Je==W||s()[Tt>>>0]==0){if(Ve=Ds(Ve,Tt-Ve),Et===void 0)var Et=Ve;else Et+="\0",Et+=Ve;Ve=Tt+1}}else{for(Et=Array(W),Je=0;Je>>0]);Et=Et.join("")}return on(F),Et},toWireType:function(F,W){W instanceof ArrayBuffer&&(W=new Uint8Array(W));var we=typeof W=="string";if(!(we||W instanceof Uint8Array||W instanceof Uint8ClampedArray||W instanceof Int8Array))throw new Gn("Cannot pass non-string to std::string");var Ve=E&&we?Yp(W):W.length,Je=bp(4+Ve+1),Tt=Je+4;if(a()[Je>>>2>>>0]=Ve,E&&we)Ta(W,Tt,Ve+1);else if(we)for(we=0;we>>0]=Et}else for(we=0;we>>0]=W[we];return F!==null&&F.push(on,Je),Je},argPackAdvance:Kn,readValueFromPointer:sh,Eb(F){on(F)}})}var hm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,S_=(l,m)=>{for(var E=l>>1,F=E+m/2;!(E>=F)&&o()[E>>>0];)++E;if(32<(E<<=1)-l&&hm)return hm.decode(s().slice(l,E));for(E="",F=0;!(F>=m/2);++F){var W=n()[l+2*F>>>1>>>0];if(W==0)break;E+=String.fromCharCode(W)}return E},$_=(l,m,E)=>{if(E??=2147483647,2>E)return 0;var F=m;E=(E-=2)<2*l.length?E/2:l.length;for(var W=0;W>>1>>>0]=we,m+=2}return n()[m>>>1>>>0]=0,m-F},A_=l=>2*l.length,I_=(l,m)=>{for(var E=0,F="";!(E>=m/4);){var W=i()[l+4*E>>>2>>>0];if(W==0)break;++E,65536<=W?(W-=65536,F+=String.fromCharCode(55296|W>>10,56320|1023&W)):F+=String.fromCharCode(W)}return F},O_=(l,m,E)=>{if(m>>>=0,E??=2147483647,4>E)return 0;var F=m;E=F+E-4;for(var W=0;W=we&&(we=65536+((1023&we)<<10)|1023&l.charCodeAt(++W)),i()[m>>>2>>>0]=we,(m+=4)+4>E)break}return i()[m>>>2>>>0]=0,m-F},F_=l=>{for(var m=0,E=0;E=F&&++E,m+=4}return m};function D_(l,m,E){if(l>>>=0,m>>>=0,E=rn(E>>>=0),m===2)var F=S_,W=$_,we=A_,Ve=Je=>o()[Je>>>1>>>0];else m===4&&(F=I_,W=O_,we=F_,Ve=Je=>a()[Je>>>2>>>0]);Mn(l,{name:E,fromWireType:Je=>{for(var Tt,Et=a()[Je>>>2>>>0],Nt=Je+4,ls=0;ls<=Et;++ls){var fs=Je+4+ls*m;ls!=Et&&Ve(fs)!=0||(Nt=F(Nt,fs-Nt),Tt===void 0?Tt=Nt:(Tt+="\0",Tt+=Nt),Nt=fs+m)}return on(Je),Tt},toWireType:(Je,Tt)=>{if(typeof Tt!="string")throw new Gn(`Cannot pass non-string to C++ string type ${E}`);var Et=we(Tt),Nt=bp(4+Et+m);return a()[Nt>>>2>>>0]=Et/m,W(Tt,Nt+4,Et+m),Je!==null&&Je.push(on,Nt),Nt},argPackAdvance:Kn,readValueFromPointer:sh,Eb(Je){on(Je)}})}function L_(l,m){Mn(l>>>=0,{Ub:!0,name:m=rn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var z_=()=>1;function B_(l){uh(l>>>0,!N,1,!B,131072,!1),Wh()}var mm=l=>{if(!Cs)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(i(),l>>>2,l).value.then(pp),l+=128,Atomics.store(i(),l>>>2,1))}var pp=()=>{var l=Pa();l&&(rh(l),mm(Wm))};function R_(l,m){(l>>>=0)==m>>>0?setTimeout(pp):L?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=sn[l])&&l.postMessage({cmd:"checkMailbox"})}var nh=[];function N_(l,m,E,F,W){for(m>>>=0,F/=2,nh.length=F,E=W>>>0>>>3,W=0;W>>0];return(m?Kp[m]:Af[l])(...nh)}function j_(l){l>>>=0,L?postMessage({cmd:"cleanupThread",thread:l}):Vh(sn[l])}function U_(l){}var hp=(l,m)=>{var E=Zp[l];if(E===void 0)throw l=Nm(l),E=rn(l),on(l),new Gn(`${m} has unknown type ${E}`);return E},_m=(l,m,E)=>{var F=[];return l=l.toWireType(F,E),F.length&&(a()[m>>>2>>>0]=Er(F)),l};function V_(l,m,E){return m>>>=0,E>>>=0,l=Mr(l>>>0),m=hp(m,"emval::as"),_m(m,E,l)}function W_(l,m){return m>>>=0,l=Mr(l>>>0),(m=hp(m,"emval::as")).toWireType(null,l)}var mp=l=>{try{l()}catch(m){Vn(m)}},Hn=0,nn=null,fm=0,_p=[],gm={},wm={},G_=0,oh=null,K_=[];function ym(l){return function(m){if(!Cs){if(Hn===0){var E=!1,F=!1;m((W=0)=>{if(!Cs&&(fm=W,E=!0,F)){Hn=2,mp(()=>Xm(nn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),W=!1;try{var we=function(){var Tt=i()[nn+8>>>2>>>0];return Tt=Rt[wm[Tt]],--Po,Tt()}()}catch(Tt){we=Tt,W=!0}var Ve=!1;if(!nn){var Je=oh;Je&&(oh=null,(W?Je.reject:Je.resolve)(we),Ve=!0)}if(W&&!Ve)throw we}}),F=!0,E||(Hn=1,nn=function(){var W=bp(65548),we=W+12;a()[W>>>2>>>0]=we,a()[W+4>>>2>>>0]=we+65536,we=_p[0];var Ve=gm[we];return Ve===void 0&&(Ve=G_++,gm[we]=Ve,wm[Ve]=we),we=Ve,i()[W+8>>>2>>>0]=we,W}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),mp(()=>Hm(nn)))}else Hn===2?(Hn=0,mp(Qm),on(nn),nn=null,K_.forEach(mm)):Vn(`invalid state: ${Hn}`);return fm}}(m=>{l().then(m)})}function H_(l){return l>>>=0,ym(()=>(l=Mr(l)).then(Er))}var fp=[];function q_(l,m,E,F){return E>>>=0,F>>>=0,(l=fp[l>>>0])(null,m=Mr(m>>>0),E,F)}var X_={},gp=l=>{var m=X_[l];return m===void 0?rn(l):m};function Q_(l,m,E,F,W){return E>>>=0,F>>>=0,W>>>=0,(l=fp[l>>>0])(m=Mr(m>>>0),m[E=gp(E)],F,W)}var Mm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Y_(l){return(l>>>=0)==0?Er(Mm()):(l=gp(l),Er(Mm()[l]))}var J_=l=>{var m=fp.length;return fp.push(l),m},Z_=(l,m)=>{for(var E=Array(l),F=0;F>>2>>>0],"parameter "+F);return E},bm=(l,m)=>Object.defineProperty(m,"name",{value:l});function ef(l,m,E){var F=(m=Z_(l,m>>>0)).shift();l--;var W=`return function (obj, func, destructorsRef, args) { +`,we=0,Ve=[];E===0&&Ve.push("obj");for(var Je=["retType"],Tt=[F],Et=0;EtNt.name).join(", ")}) => ${F.name}>`,J_(bm(E,l))}function tf(l){return l=gp(l>>>0),Er(u[l])}function sf(l,m){return m>>>=0,l=Mr(l>>>0),m=Mr(m),Er(l[m])}function rf(l){9<(l>>>=0)&&(bn[l+1]+=1)}function nf(){return Er([])}function of(l){l=Mr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function lf(){return Er({})}function uf(l){for(var m=Mr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}th(l)}function df(l,m,E){m>>>=0,E>>>=0,l=Mr(l>>>0),m=Mr(m),E=Mr(E),l[m]=E}function cf(l,m){return m>>>=0,l=(l=hp(l>>>0,"_emval_take_value")).readValueFromPointer(m),Er(l)}function pf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getUTCSeconds(),i()[m+4>>>2>>>0]=l.getUTCMinutes(),i()[m+8>>>2>>>0]=l.getUTCHours(),i()[m+12>>>2>>>0]=l.getUTCDate(),i()[m+16>>>2>>>0]=l.getUTCMonth(),i()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,i()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[m+28>>>2>>>0]=l}var xa=l=>l%4==0&&(l%100!=0||l%400==0),vm=[0,31,60,91,121,152,182,213,244,274,305,335],Tm=[0,31,59,90,120,151,181,212,243,273,304,334];function hf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getSeconds(),i()[m+4>>>2>>>0]=l.getMinutes(),i()[m+8>>>2>>>0]=l.getHours(),i()[m+12>>>2>>>0]=l.getDate(),i()[m+16>>>2>>>0]=l.getMonth(),i()[m+20>>>2>>>0]=l.getFullYear()-1900,i()[m+24>>>2>>>0]=l.getDay();var E=(xa(l.getFullYear())?vm:Tm)[l.getMonth()]+l.getDate()-1|0;i()[m+28>>>2>>>0]=E,i()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var F=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=F&&l.getTimezoneOffset()==Math.min(F,E)),i()[m+32>>>2>>>0]=l}function mf(l){l>>>=0;var m=new Date(i()[l+20>>>2>>>0]+1900,i()[l+16>>>2>>>0],i()[l+12>>>2>>>0],i()[l+8>>>2>>>0],i()[l+4>>>2>>>0],i()[l>>>2>>>0],0),E=i()[l+32>>>2>>>0],F=m.getTimezoneOffset(),W=new Date(m.getFullYear(),6,1).getTimezoneOffset(),we=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ve=Math.min(we,W);return 0>E?i()[l+32>>>2>>>0]=+(W!=we&&Ve==F):0>>2>>>0]=m.getDay(),E=(xa(m.getFullYear())?vm:Tm)[m.getMonth()]+m.getDate()-1|0,i()[l+28>>>2>>>0]=E,i()[l>>>2>>>0]=m.getSeconds(),i()[l+4>>>2>>>0]=m.getMinutes(),i()[l+8>>>2>>>0]=m.getHours(),i()[l+12>>>2>>>0]=m.getDate(),i()[l+16>>>2>>>0]=m.getMonth(),i()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function xm(l,m,E,F,W,we,Ve){return L?Ss(16,1,l,m,E,F,W,we,Ve):-52}function Pm(l,m,E,F,W,we){if(L)return Ss(17,1,l,m,E,F,W,we)}function _f(l,m,E,F){l>>>=0,m>>>=0,E>>>=0,F>>>=0;var W=new Date().getFullYear(),we=new Date(W,0,1),Ve=new Date(W,6,1);W=we.getTimezoneOffset();var Je=Ve.getTimezoneOffset(),Tt=Math.max(W,Je);a()[l>>>2>>>0]=60*Tt,i()[m>>>2>>>0]=+(W!=Je),we=(l=Et=>Et.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(we),Ve=l(Ve),Je{ih.length=0;for(var E;E=s()[l++>>>0];){var F=E!=105;m+=(F&=E!=112)&&m%8?4:0,ih.push(E==112?a()[m>>>2>>>0]:E==106?Ts[m>>>3]:E==105?i()[m>>>2>>>0]:p()[m>>>3>>>0]),m+=F?8:4}return ih};function ff(l,m,E){return l>>>=0,m=Em(m>>>0,E>>>0),Kp[l](...m)}function gf(l,m,E){return l>>>=0,m=Em(m>>>0,E>>>0),Kp[l](...m)}var wf=()=>{},yf=()=>Date.now();function Mf(l,m){return $t(Ds(l>>>0,m>>>0))}var Cm,bf=()=>{throw Po+=1,"unwind"};function vf(){return 4294901760}Cm=()=>performance.timeOrigin+performance.now();var Tf=()=>navigator.hardwareConcurrency;function xf(){return Vn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Pf(l){l>>>=0;var m=s().length;if(l<=m||4294901760=E;E*=2){var F=m*(1+.2/E);F=Math.min(F,l+100663296);var W=Math;F=Math.max(l,F);e:{W=(W.min.call(W,4294901760,F+(65536-F%65536)%65536)-jt.buffer.byteLength+65535)/65536;try{jt.grow(W),Ys();var we=1;break e}catch{}we=void 0}if(we)return!0}return!1}var wp=()=>(Vn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Kd={},km=l=>{l.forEach(m=>{wp()})};function Ef(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),km(l),Kd.Qb=wp(),Kd.fc=l,Kd.Qb}function Cf(l,m,E){if(l>>>=0,m>>>=0,Kd.Qb==l)var F=Kd.fc;else(F=Error().stack.toString().split(` +`))[0]=="Error"&&F.shift(),km(F);for(var W=3;F[W]&&wp()!=l;)++W;for(l=0;l>>2>>>0]=wp();return l}var ah,lh={},Sm=()=>{if(!ah){var l,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:ye};for(l in lh)lh[l]===void 0?delete m[l]:m[l]=lh[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);ah=E}return ah};function $m(l,m){if(L)return Ss(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Sm().forEach((F,W)=>{var we=m+E;for(W=a()[l+4*W>>>2>>>0]=we,we=0;we>>0]=F.charCodeAt(we);t()[W>>>0]=0,E+=F.length+1}),0}function Am(l,m){if(L)return Ss(19,1,l,m);l>>>=0,m>>>=0;var E=Sm();a()[l>>>2>>>0]=E.length;var F=0;return E.forEach(W=>F+=W.length+1),a()[m>>>2>>>0]=F,0}function Im(l){return L?Ss(20,1,l):52}function Om(l,m,E,F){return L?Ss(21,1,l,m,E,F):52}function Fm(l,m,E,F){return L?Ss(22,1,l,m,E,F):70}var kf=[null,[],[]];function Dm(l,m,E,F){if(L)return Ss(23,1,l,m,E,F);m>>>=0,E>>>=0,F>>>=0;for(var W=0,we=0;we>>2>>>0],Je=a()[m+4>>>2>>>0];m+=8;for(var Tt=0;Tt>>0],Nt=kf[l];Et===0||Et===10?((l===1?Dt:$t)(Qh(Nt,0)),Nt.length=0):Nt.push(Et)}W+=Je}return a()[F>>>2>>>0]=W,0}var Lm=[31,29,31,30,31,30,31,31,30,31,30,31],zm=[31,28,31,30,31,30,31,31,30,31,30,31],Sf=(l,m)=>{t().set(l,m>>>0)};function Bm(l,m,E,F){function W(Ue,is,Ls){for(Ue=typeof Ue=="number"?Ue.toString():Ue||"";Ue.lengthJm?-1:0Co-Ue.getDate())){Ue.setDate(Ue.getDate()+is);break}is-=Co-Ue.getDate()+1,Ue.setDate(1),11>Ls?Ue.setMonth(Ls+1):(Ue.setMonth(0),Ue.setFullYear(Ue.getFullYear()+1))}return Ls=new Date(Ue.getFullYear()+1,0,4),is=Je(new Date(Ue.getFullYear(),0,4)),Ls=Je(Ls),0>=Ve(is,Ue)?0>=Ve(Ls,Ue)?Ue.getFullYear()+1:Ue.getFullYear():Ue.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,F>>>=0;var Et=a()[F+40>>>2>>>0];for(var Nt in F={lc:i()[F>>>2>>>0],kc:i()[F+4>>>2>>>0],Ib:i()[F+8>>>2>>>0],Mb:i()[F+12>>>2>>>0],Jb:i()[F+16>>>2>>>0],Db:i()[F+20>>>2>>>0],vb:i()[F+24>>>2>>>0],Cb:i()[F+28>>>2>>>0],sc:i()[F+32>>>2>>>0],jc:i()[F+36>>>2>>>0],mc:Et?Ds(Et):""},E=Ds(E),Et={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})E=E.replace(new RegExp(Nt,"g"),Et[Nt]);var ls="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),fs="January February March April May June July August September October November December".split(" ");for(Nt in Et={"%a":Ue=>ls[Ue.vb].substring(0,3),"%A":Ue=>ls[Ue.vb],"%b":Ue=>fs[Ue.Jb].substring(0,3),"%B":Ue=>fs[Ue.Jb],"%C":Ue=>we((Ue.Db+1900)/100|0,2),"%d":Ue=>we(Ue.Mb,2),"%e":Ue=>W(Ue.Mb,2," "),"%g":Ue=>Tt(Ue).toString().substring(2),"%G":Tt,"%H":Ue=>we(Ue.Ib,2),"%I":Ue=>((Ue=Ue.Ib)==0?Ue=12:12{for(var is=0,Ls=0;Ls<=Ue.Jb-1;is+=(xa(Ue.Db+1900)?Lm:zm)[Ls++]);return we(Ue.Mb+is,3)},"%m":Ue=>we(Ue.Jb+1,2),"%M":Ue=>we(Ue.kc,2),"%n":()=>` +`,"%p":Ue=>0<=Ue.Ib&&12>Ue.Ib?"AM":"PM","%S":Ue=>we(Ue.lc,2),"%t":()=>" ","%u":Ue=>Ue.vb||7,"%U":Ue=>we(Math.floor((Ue.Cb+7-Ue.vb)/7),2),"%V":Ue=>{var is=Math.floor((Ue.Cb+7-(Ue.vb+6)%7)/7);if(2>=(Ue.vb+371-Ue.Cb-2)%7&&is++,is)is==53&&((Ls=(Ue.vb+371-Ue.Cb)%7)==4||Ls==3&&xa(Ue.Db)||(is=1));else{is=52;var Ls=(Ue.vb+7-Ue.Cb-1)%7;(Ls==4||Ls==5&&xa(Ue.Db%400-1))&&is++}return we(is,2)},"%w":Ue=>Ue.vb,"%W":Ue=>we(Math.floor((Ue.Cb+7-(Ue.vb+6)%7)/7),2),"%y":Ue=>(Ue.Db+1900).toString().substring(2),"%Y":Ue=>Ue.Db+1900,"%z":Ue=>{var is=0<=(Ue=Ue.jc);return Ue=Math.abs(Ue)/60,(is?"+":"-")+("0000"+(Ue/60*100+Ue%60)).slice(-4)},"%Z":Ue=>Ue.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),Et)E.includes(Nt)&&(E=E.replace(new RegExp(Nt,"g"),Et[Nt](F)));return Nt=function(Ue){var is=Array(Yp(Ue)+1);return Zh(Ue,is,0,is.length),is}(E=E.replace(/\0\0/g,"%")),Nt.length>m?0:(Sf(Nt,l),Nt.length-1)}function $f(l,m,E,F){return Bm(l>>>0,m>>>0,E>>>0,F>>>0)}L||function(){for(var l=u.numThreads-1;l--;)Kh();dp.unshift(()=>{Wd++,function(m){L?m():Promise.all(Wn.map(Gh)).then(m)}(()=>Fh())})}();for(var Rm=Array(256),yp=0;256>yp;++yp)Rm[yp]=String.fromCharCode(yp);cm=Rm,Gn=u.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},u.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},bn.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>bn.length/2-5-eh.length;var Af=[Xp,jh,Hh,Yh,Jh,em,tm,sm,rm,nm,om,im,am,lm,um,dm,xm,Pm,$m,Am,Im,Om,Fm,Dm],Rt=function(){function l(E,F){return Rt=E.exports,Rt=function(){var W=Rt,we={};for(let[Ve,Je]of Object.entries(W))we[Ve]=typeof Je=="function"?(...Tt)=>{_p.push(Ve);try{return Je(...Tt)}finally{Cs||(_p.pop(),nn&&Hn===1&&_p.length===0&&(Hn=0,Po+=1,mp(qm),typeof Fibers<"u"&&Fibers.tc()))}}:Je;return we}(),Rt=function(){var W=Rt,we=Je=>Tt=>Je(Tt)>>>0,Ve=Je=>()=>Je()>>>0;return(W=Object.assign({},W)).Da=we(W.Da),W.gb=Ve(W.gb),W.ib=we(W.ib),W.emscripten_main_runtime_thread_id=Ve(W.emscripten_main_runtime_thread_id),W.tb=we(W.tb),W.ub=Ve(W.ub),W}(),Uh.push(Rt.jb),Vd.unshift(Rt.Ca),Lt=F,Fh(),Rt}var m=Rh();if(Wd++,u.instantiateWasm)try{return u.instantiateWasm(m,l)}catch(E){$t(`Module.instantiateWasm callback failed with error: ${E}`),k(E)}return Gp||=u.locateFile?Dh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ee):Ee+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href,function(E,F){var W=Gp;return tt||typeof WebAssembly.instantiateStreaming!="function"||Dh(W)||Lh(W)||typeof fetch!="function"?Bh(W,E,F):fetch(W,{credentials:"same-origin"}).then(we=>WebAssembly.instantiateStreaming(we,E).then(F,function(Ve){return $t(`wasm streaming compile failed: ${Ve}`),$t("falling back to ArrayBuffer instantiation"),Bh(W,E,F)}))}(m,function(E){l(E.instance,E.module)}).catch(k),{}}(),Nm=l=>(Nm=Rt.Da)(l),jm=()=>(jm=Rt.Ea)();u._OrtInit=(l,m)=>(u._OrtInit=Rt.Fa)(l,m),u._OrtGetLastError=(l,m)=>(u._OrtGetLastError=Rt.Ga)(l,m),u._OrtCreateSessionOptions=(l,m,E,F,W,we,Ve,Je,Tt,Et)=>(u._OrtCreateSessionOptions=Rt.Ha)(l,m,E,F,W,we,Ve,Je,Tt,Et),u._OrtAppendExecutionProvider=(l,m)=>(u._OrtAppendExecutionProvider=Rt.Ia)(l,m),u._OrtAddFreeDimensionOverride=(l,m,E)=>(u._OrtAddFreeDimensionOverride=Rt.Ja)(l,m,E),u._OrtAddSessionConfigEntry=(l,m,E)=>(u._OrtAddSessionConfigEntry=Rt.Ka)(l,m,E),u._OrtReleaseSessionOptions=l=>(u._OrtReleaseSessionOptions=Rt.La)(l),u._OrtCreateSession=(l,m,E)=>(u._OrtCreateSession=Rt.Ma)(l,m,E),u._OrtReleaseSession=l=>(u._OrtReleaseSession=Rt.Na)(l),u._OrtGetInputOutputCount=(l,m,E)=>(u._OrtGetInputOutputCount=Rt.Oa)(l,m,E),u._OrtGetInputName=(l,m)=>(u._OrtGetInputName=Rt.Pa)(l,m),u._OrtGetOutputName=(l,m)=>(u._OrtGetOutputName=Rt.Qa)(l,m),u._OrtFree=l=>(u._OrtFree=Rt.Ra)(l),u._OrtCreateTensor=(l,m,E,F,W,we)=>(u._OrtCreateTensor=Rt.Sa)(l,m,E,F,W,we),u._OrtGetTensorData=(l,m,E,F,W)=>(u._OrtGetTensorData=Rt.Ta)(l,m,E,F,W),u._OrtReleaseTensor=l=>(u._OrtReleaseTensor=Rt.Ua)(l),u._OrtCreateRunOptions=(l,m,E,F)=>(u._OrtCreateRunOptions=Rt.Va)(l,m,E,F),u._OrtAddRunConfigEntry=(l,m,E)=>(u._OrtAddRunConfigEntry=Rt.Wa)(l,m,E),u._OrtReleaseRunOptions=l=>(u._OrtReleaseRunOptions=Rt.Xa)(l),u._OrtCreateBinding=l=>(u._OrtCreateBinding=Rt.Ya)(l),u._OrtBindInput=(l,m,E)=>(u._OrtBindInput=Rt.Za)(l,m,E),u._OrtBindOutput=(l,m,E,F)=>(u._OrtBindOutput=Rt._a)(l,m,E,F),u._OrtClearBoundOutputs=l=>(u._OrtClearBoundOutputs=Rt.$a)(l),u._OrtReleaseBinding=l=>(u._OrtReleaseBinding=Rt.ab)(l),u._OrtRunWithBinding=(l,m,E,F,W)=>(u._OrtRunWithBinding=Rt.bb)(l,m,E,F,W),u._OrtRun=(l,m,E,F,W,we,Ve,Je)=>(u._OrtRun=Rt.cb)(l,m,E,F,W,we,Ve,Je),u._OrtEndProfiling=l=>(u._OrtEndProfiling=Rt.db)(l),u._JsepOutput=(l,m,E)=>(u._JsepOutput=Rt.eb)(l,m,E),u._JsepGetNodeName=l=>(u._JsepGetNodeName=Rt.fb)(l);var Mp,Pa=()=>(Pa=Rt.gb)(),on=u._free=l=>(on=u._free=Rt.hb)(l),bp=u._malloc=l=>(bp=u._malloc=Rt.ib)(l),uh=(l,m,E,F,W,we)=>(uh=Rt.lb)(l,m,E,F,W,we),Um=()=>(Um=Rt.mb)(),Vm=(l,m,E,F,W)=>(Vm=Rt.nb)(l,m,E,F,W),dh=l=>(dh=Rt.ob)(l),vp=l=>(vp=Rt.pb)(l),Wm=()=>(Wm=Rt.qb)(),Gm=(l,m)=>(Gm=Rt.rb)(l,m),Tp=l=>(Tp=Rt.sb)(l),ch=l=>(ch=Rt.tb)(l),ph=()=>(ph=Rt.ub)(),Km=u.dynCall_ii=(l,m)=>(Km=u.dynCall_ii=Rt.wb)(l,m),Hm=l=>(Hm=Rt.xb)(l),qm=()=>(qm=Rt.yb)(),Xm=l=>(Xm=Rt.zb)(l),Qm=()=>(Qm=Rt.Ab)();function Ym(){0ph(),u.stackRestore=l=>Tp(l),u.stackAlloc=l=>ch(l),u.setValue=function(l,m,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":t()[l>>>0]=m;break;case"i16":n()[l>>>1>>>0]=m;break;case"i32":i()[l>>>2>>>0]=m;break;case"i64":Ts[l>>>3]=BigInt(m);break;case"float":c()[l>>>2>>>0]=m;break;case"double":p()[l>>>3>>>0]=m;break;case"*":a()[l>>>2>>>0]=m;break;default:Vn(`invalid type for setValue: ${E}`)}},u.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return t()[l>>>0];case"i16":return n()[l>>>1>>>0];case"i32":return i()[l>>>2>>>0];case"i64":return Ts[l>>>3];case"float":return c()[l>>>2>>>0];case"double":return p()[l>>>3>>>0];case"*":return a()[l>>>2>>>0];default:Vn(`invalid type for getValue: ${m}`)}},u.UTF8ToString=Ds,u.stringToUTF8=Ta,u.lengthBytesUTF8=Yp,Gd=function l(){Mp||Ym(),Mp||(Gd=l)},Ym(),u.PTR_SIZE=4,S}),Ms=$s,globalThis.self?.name==="em-pthread"&&$s()}),sr,Rr,Cr,an,Ot,Nr,br,kr,vr=y(()=>{et(),sr=import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Rr=typeof location>"u"?void 0:location.origin,Cr=(e,t)=>{try{let s=t??sr;return(s?new URL(e,s):new URL(e)).origin===Rr}catch{return!1}},an=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Ot=(ts(),T(ot)).default,Nr=async()=>{if(!sr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Cr(sr))return[void 0,Ot()];let e=await an(sr);return[e,Ot(e)]},br=(Ks(),T(xs)).default,kr=async(e,t,s)=>[void 0,br]}),Sr,Js,ur,Tr,jr,rr,it,dt,St=y(()=>{vr(),Js=!1,ur=!1,Tr=!1,jr=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},rr=()=>{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}},it=async e=>{if(Js)return Promise.resolve();if(ur)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Tr)throw new Error("previous call to 'initializeWebAssembly()' failed.");ur=!0;let t=e.initTimeout,s=e.numThreads;if(!rr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=jr();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let o=e.wasmPaths,i=typeof o=="string"?o:void 0,a=o?.mjs,c=a?.href??a,p=o?.wasm,h=p?.href??p,k=e.wasmBinary,[u,S]=await kr(c,i,s>1),B=!1,N=[];if(t>0&&N.push(new Promise(L=>{setTimeout(()=>{B=!0,L()},t)})),N.push(new Promise((L,se)=>{let ee={numThreads:s};k?ee.wasmBinary=k:(h||i)&&(ee.locateFile=(V,de)=>h??(i??de)+V),S(ee).then(V=>{ur=!1,Js=!0,Sr=V,L(),u&&URL.revokeObjectURL(u)},V=>{ur=!1,Tr=!0,se(V)})})),await Promise.race(N),B)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},dt=()=>{if(Js&&Sr)return Sr;throw new Error("WebAssembly is not initialized yet.")}}),cs,Ur,rs,Vr=y(()=>{St(),cs=(e,t)=>{let s=dt(),n=s.lengthBytesUTF8(e)+1,o=s._malloc(n);return s.stringToUTF8(e,o,n),t.push(o),o},Ur=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i=="object")Ur(i,a+".",s,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}`)})},rs=e=>{let t=dt(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?"i32":"i64")),a=t.getValue(o+n,"*"),c=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(s)}}}),$r,qn=y(()=>{St(),Vr(),$r=e=>{let t=dt(),s=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=cs(e.tag,n)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),s===0&&rs("Can't create run options."),e?.extra!==void 0&&Ur(e.extra,"",new WeakSet,(a,c)=>{let p=cs(a,n),h=cs(c,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&rs(`Can't set a run config entry: ${a} - ${c}.`)}),[s,n]}catch(i){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(a=>t._free(a)),i}}}),Tn,Wr,xn,Ar,Pn,Xn=y(()=>{St(),Vr(),Tn=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}`)}},Wr=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},xn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},Ar=(e,t,s)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let a=n?.deviceType;if(a){let c=cs("deviceType",s),p=cs(a,s);dt()._OrtAddSessionConfigEntry(e,c,p)!==0&&rs(`Can't set a session config entry: 'deviceType' - ${a}.`)}}break;case"webgpu":if(o="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 c=cs("preferredLayout",s),p=cs(a.preferredLayout,s);dt()._OrtAddSessionConfigEntry(e,c,p)!==0&&rs(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=cs(o,s);dt()._OrtAppendExecutionProvider(e,i)!==0&&rs(`Can't append execution provider: ${o}.`)}},Pn=e=>{let t=dt(),s=0,n=[],o=e||{};xn(o);try{let i=Tn(o.graphOptimizationLevel??"all"),a=Wr(o.executionMode??"sequential"),c=typeof o.logId=="string"?cs(o.logId,n):0,p=o.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=o.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof o.optimizedModelFilePath=="string"?cs(o.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,c,p,h,k),s===0&&rs("Can't create session options."),o.executionProviders&&Ar(s,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=cs("enableGraphCapture",n),S=cs(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,u,S)!==0&&rs(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,S]of Object.entries(o.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof S!="number"||!Number.isInteger(S)||S<0)throw new Error(`free dimension override value must be a non-negative integer: ${S}`);let B=cs(u,n);t._OrtAddFreeDimensionOverride(s,B,S)!==0&&rs(`Can't set a free dimension override: ${u} - ${S}.`)}return o.extra!==void 0&&Ur(o.extra,"",new WeakSet,(u,S)=>{let B=cs(u,n),N=cs(S,n);t._OrtAddSessionConfigEntry(s,B,N)!==0&&rs(`Can't set a session config entry: ${u} - ${S}.`)}),[s,n]}catch(i){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&rs("Can't release session options."),n.forEach(a=>t._free(a)),i}}}),Ir,fr,Zs,ln,Gr,un,Kr,dn,Ft=y(()=>{Ir=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},fr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Zs=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,i)=>o*i,1);return s>0?Math.ceil(n*s):void 0},ln=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}`)}},Gr=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}`)}},un=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Kr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",dn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),cn,En=y(()=>{et(),cn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(c){if(c instanceof RangeError){let p=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw c}let a=0;for(;;){let{done:c,value:p}=await o.read();if(c)break;let h=p.byteLength;new Uint8Array(i,a,h).set(p),a+=h}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Cn,kn,Or,Sn,pn,$n,ns,er=y(()=>{Ft(),Cn=["V","I","W","E","F"],kn=(e,t)=>{console.log(`[${Cn[e]},${new Date().toISOString()}]${t}`)},pn=(e,t)=>{Or=e,Sn=t},$n=(e,t)=>{let s=Gr(e),n=Gr(Or);s>=n&&kn(s,typeof t=="function"?t():t)},ns=(...e)=>{Sn&&$n(...e)}}),hn,An=y(()=>{Ft(),hn=(e,t)=>new(ln(t))(e)}),Hr=y(()=>{}),In,Te,M,Q,pe,ge,Ie,Xe,_t,ft=y(()=>{er(),Hr(),In=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]]),Te=[],M=e=>Math.ceil(Number(e)/16)*16,Q=e=>{for(let t=0;tpe++,Ie=async(e,t,s,n)=>{let o=M(s),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let c=i.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(c,0,s)),p}else return new Uint8Array(c.slice(0,s))}finally{i.destroy()}},Xe=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of In)Te.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,o=t.byteLength,i=M(o),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(Number(a.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${o}`);let c=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=c.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,o)),c.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(c,0,a.gpuData.buffer,0,i),this.backend.device.queue.submit([h.finish()]),c.destroy(),ns("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=M(s.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return ns("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else n=ge();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),ns("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),ns("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=Q(e),n,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||i){let c=(o?this.freeBuffers:this.freeUniformBuffers).get(s);c?c.length>0?n=c.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let a={id:ge(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:Number(e)}),ns("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return ns("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await Ie(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=In.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(ns("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},_t=(...e)=>new Xe(...e)}),vt,Qe,It=y(()=>{vt=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}},Qe=e=>new vt(e)}),Xt,gs,Se,Ps,js,Rs,dr,zt=y(()=>{Xt=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},gs=class{static calcShape(e,t,s=!1){let n=e.length,o=t.length;if(n===0)return t;if(o===0)return e;let i=Math.max(e.length,t.length),a=new Array(i);if(s){if(n<2||o<2)return;let c=Xt.calcMatMulShape([e[n-2],e[n-1]],[t[o-2],t[o-1]]);if(c===void 0)return;[a[i-2],a[i-1]]=c}for(let c=s?3:1;c<=i;c++){let p=n-c<0?1:e[n-c],h=o-c<0?1:t[o-c];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)a[i-c]=Math.max(p,h);else{if(k>1)return;a[i-c]=0}}return a}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[n-o])return!1;return!0}},Se=class xp{static size(t){return xp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%s===0){o[i]=t[i]/s;break}if(s%t[i]!==0)throw new Error("cannot convert shape");o[i]=1,s/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return xp.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return xp.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let o=1;for(let i=s;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((o,i)=>o+s[i]+s[i+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,o)=>n===s[o])}},Ps=class Hd{static adjustPoolAttributes(t,s,n,o,i,a){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=n.length?n.push(s[c+2]):n[c]=s[c+2];for(let c=0;c=n[c]||a[c+n.length]>=n[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,o,i,a,c){if(c){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Ft(),zt(),zs=64,gr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Zt=(e,t=1)=>{let s=gr(e,t);return typeof s=="string"?s:s[0]},us=(e,t=1)=>{let s=gr(e,t);return typeof s=="string"?s:s[1]},xt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:Se.computeStrides(s)})}),t},os=e=>e%4===0?4:e%2===0?2:1,wr=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,As=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Vs=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Mt=(e,t,s,n)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,Es=(e,t,s,n,o)=>{let i=typeof s=="number",a=i?s:s.length,c=[...new Array(a).keys()],p=a<2?"u32":a<=4?`vec${a}`:`array`,h=gr(t,o),k=typeof h=="string"?h:h[1],u=typeof h=="string"?h:h[0],S={indices:p,value:k,storage:u,tensor:t},B=at=>typeof at=="string"?at:`${at}u`,N={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},L=i?"uniforms.":"",se=`${L}${e}_shape`,ee=`${L}${e}_strides`,V="";for(let at=0;at ${S.indices} { + var indices: ${S.indices}; + var current = offset; + ${V} + return indices; + }`,me=at=>(N.offsetToIndices=!0,a<2?at:`o2i_${e}(${at})`),ye=[];if(a>=2)for(let at=a-1;at>=0;at--)ye.push(`${Mt(ee,at,a)} * (indices[${at}])`);let Be=a<2?"":` + fn i2o_${e}(indices: ${S.indices}) -> u32 { + return ${ye.join("+")}; + }`,Ee=at=>(N.indicesToOffset=!0,a<2?at:`i2o_${e}(${at})`),tt=(...at)=>a===0?"0u":`${S.indices}(${at.map(B).join(",")})`,pt=(at,Pt)=>a<2?`${at}`:`${Mt(at,Pt,a)}`,Ct=(at,Pt,ps)=>a<2?`${at}=${ps};`:`${Mt(at,Pt,a)}=${ps};`,Dt={},$t=(at,Pt)=>{N.broadcastedIndicesToOffset=!0;let ps=`${Pt.name}broadcastedIndicesTo${e}Offset`;if(ps in Dt)return`${ps}(${at})`;let vs=[];for(let Ts=a-1;Ts>=0;Ts--){let yn=Pt.indicesGet("outputIndices",Ts+Pt.rank-a);vs.push(`${pt(ee,Ts)} * (${yn} % ${pt(se,Ts)})`)}return Dt[ps]=`fn ${ps}(outputIndices: ${Pt.type.indices}) -> u32 { + return ${vs.length>0?vs.join("+"):"0u"}; + }`,`${ps}(${at})`},bt=(at,Pt)=>(()=>{if(S.storage===S.value)return`${e}[${at}]=${Pt};`;if(S.storage==="vec2"&&S.value==="i32")return`${e}[${at}]=vec2(u32(${Pt}), select(0u, 0xFFFFFFFFu, ${Pt} < 0));`;if(S.storage==="vec2"&&S.value==="u32")return`${e}[${at}]=vec2(u32(${Pt}), 0u);`;if(S.storage==="u32"&&S.value==="vec4")return`${e}[${at}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Pt}));`;throw new Error(`not supported combination of storage type ${S.storage} and value type ${S.value} yet`)})(),Kt=at=>(()=>{if(S.storage===S.value)return`${e}[${at}]`;if(S.storage==="vec2"&&S.value==="i32")return`i32(${e}[${at}].x)`;if(S.storage==="vec2"&&S.value==="u32")return`u32(${e}[${at}].x)`;if(S.storage==="u32"&&S.value==="vec4")return`vec4(bool(${e}[${at}] & 0xFFu), bool(${e}[${at}] & 0xFF00u), bool(${e}[${at}] & 0xFF0000u), bool(${e}[${at}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${S.storage} and value type ${S.value} yet`)})(),jt=a<2?"":` + fn get_${e}ByIndices(indices: ${S.indices}) -> ${k} { + return ${Kt(`i2o_${e}(indices)`)}; + }`,Lt=a<2?"":(()=>{let at=c.map(ps=>`d${ps}: u32`).join(", "),Pt=c.map(ps=>`d${ps}`).join(", ");return` + fn get_${e}(${at}) -> ${k} { + return get_${e}ByIndices(${tt(Pt)}); + }`})(),ss=(...at)=>{if(at.length!==a)throw new Error(`indices length must be ${a}`);let Pt=at.map(B).join(",");return a===0?Kt("0u"):a===1?Kt(Pt[0]):(N.get=!0,N.getByIndices=!0,N.indicesToOffset=!0,`get_${e}(${Pt})`)},Jt=at=>a<2?Kt(at):(N.getByIndices=!0,N.indicesToOffset=!0,`get_${e}ByIndices(${at})`),qt=a<2?"":` + fn set_${e}ByIndices(indices: ${S.indices}, value: ${k}) { + ${bt(`i2o_${e}(indices)`,"value")} + }`,Qs=a<2?"":(()=>{let at=c.map(ps=>`d${ps}: u32`).join(", "),Pt=c.map(ps=>`d${ps}`).join(", ");return` + fn set_${e}(${at}, value: ${k}) { + set_${e}ByIndices(${tt(Pt)}, value); + }`})();return{impl:()=>{let at=[],Pt=!1;return N.offsetToIndices&&(at.push(de),Pt=!0),N.indicesToOffset&&(at.push(Be),Pt=!0),N.broadcastedIndicesToOffset&&(Object.values(Dt).forEach(ps=>at.push(ps)),Pt=!0),N.set&&(at.push(Qs),Pt=!0),N.setByIndices&&(at.push(qt),Pt=!0),N.get&&(at.push(Lt),Pt=!0),N.getByIndices&&(at.push(jt),Pt=!0),!i&&Pt&&at.unshift(`const ${se} = ${S.indices}(${s.join(",")});`,`const ${ee} = ${S.indices}(${Se.computeStrides(s).join(",")});`),at.join(` +`)},type:S,offsetToIndices:me,indicesToOffset:Ee,broadcastedIndicesToOffset:$t,indices:tt,indicesGet:pt,indicesSet:Ct,set:(...at)=>{if(at.length!==a+1)throw new Error(`indices length must be ${a}`);let Pt=at[a];if(typeof Pt!="string")throw new Error("value must be string");let ps=at.slice(0,a).map(B).join(",");return a===0?bt("0u",Pt):a===1?bt(ps[0],Pt):(N.set=!0,N.setByIndices=!0,N.indicesToOffset=!0,`set_${e}(${ps}, ${Pt})`)},setByOffset:bt,setByIndices:(at,Pt)=>a<2?bt(at,Pt):(N.setByIndices=!0,N.indicesToOffset=!0,`set_${e}ByIndices(${at}, ${Pt});`),get:ss,getByOffset:Kt,getByIndices:Jt,usage:n,name:e,strides:ee,shape:se,rank:a}},Oe=(e,t,s,n=1)=>Es(e,t,s,"input",n),gt=(e,t,s,n=1)=>Es(e,t,s,"output",n),tr=(e,t,s)=>Es(e,t,s,"atomicOutput",1),qr=(e,t,s,n=1)=>Es(e,t,s,"internal",n),Qn=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=zs){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,a=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) + fn main(${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 s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let o=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},ka=(e,t)=>new Qn(e,t)}),Sa,ko,So,$a,Aa,$o,nr,Ia,Ao,Fr=y(()=>{Ft(),zt(),It(),Gt(),Sa=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},ko=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,So=(e,t)=>Se.sortBasedOnPerm(e,ko(e.length,t)),$a=(e,t,s,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`;for(let i=0;i{let s=[],n=[];for(let o=0;o{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,o=ko(n,t),i=So(e.dims,o),a=e.dims,c=i,p=n<2||$o(o,e.dims),h;if(p)return h=N=>{let L=Oe("input",s,a,4),se=gt("output",s,c,4);return` + ${N.registerUniform("output_size","u32").declareVariables(L,se)} + ${N.mainStart()} + ${N.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let N=Se.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(N/64/4)},programUniforms:[{type:12,data:Math.ceil(N/4)}]}},getShaderSource:h};let{newShape:k,newPerm:u}=Aa(e.dims,o),S=Se.areEqual(u,[2,3,1]),B=Se.areEqual(u,[3,1,2]);if(k.length===2||S||B){a=S?[k[0],k[1]*k[2]]:B?[k[0]*k[1],k[2]]:k,c=[a[1],a[0]];let N=16;return h=L=>{let se=Oe("a",s,a.length),ee=gt("output",s,c.length);return` + ${L.registerUniform("output_size","u32").declareVariables(se,ee)} + var tile : array, ${N}>; + ${L.mainStart([N,N,1])} + let stride = (uniforms.output_shape[1] - 1) / ${N} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${N}u + local_id.x; + let input_row = workgroup_id_x * ${N}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${se.getByIndices(`${se.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${N}u + local_id.x; + let output_row = workgroup_id_y * ${N}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${ee.setByIndices(`${ee.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let L=Se.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c[1]/N),y:Math.ceil(c[0]/N)},programUniforms:[{type:12,data:L},...xt(a,c)]}},getShaderSource:h}}return h=N=>{let L=Oe("a",s,a.length),se=gt("output",s,c.length);return` + ${N.registerUniform("output_size","u32").declareVariables(L,se)} + + ${$a(o,n,L,se)} + + ${N.mainStart()} + ${N.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${se.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${se.setByOffset("global_idx",L.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let N=Se.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:[{type:12,data:N},...xt(a,c)]}},getShaderSource:h}},Ia=(e,t)=>{Sa(e.inputs),e.compute(nr(e.inputs[0],t.perm))},Ao=e=>Qe({perm:e.perm})}),Yn,Oa,Fa,Da,La,za,Ba,Ra,Io,Na,or,Xr,ja,Yd,Ua,Jd,Va,Oo,Wa,Ga,Ka,Zd=y(()=>{Ft(),zt(),Gt(),eo(),Fr(),Yn={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"},Oa={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"},Fa={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Da={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},La=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let i=0;ie[i]);return[s,o]},Ba=(e,t)=>{let s=e.length+t.length,n=[],o=0;for(let i=0;i{for(let s=0;s{let s=[];if(!Ra(e,t)){for(let n=0;ns.push(n))}return s},Na=(e,t,s,n,o,i,a)=>{let c=s[0].dims,p=Se.size(i),h=Se.size(a),k=Oe("_A",s[0].dataType,c),u=gt("output",o,i),S=64;p===1&&(S=256);let B=` + var aBestValues : array; + `,N=L=>` + ${L.registerUniform("reduceSize","u32").declareVariables(k,u)} + ${B} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${L.mainStart(S)} + + let outputIndex = global_idx / ${S}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Fa[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${S}) { + let candidate = f32(${k.getByOffset("offset + k")}); + bestValue = ${Yn[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${S}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 = ${Oa[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${u.setByOffset("outputIndex",`${n==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${Da[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${S}`,inputDependencies:["type"]},getShaderSource:N,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},or=(e,t,s,n)=>{let o=e.inputs.length===1?s:Fo(e.inputs,s),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((B,N)=>N));let a=Se.normalizeAxes(i,e.inputs[0].dims.length),c=a,p=e.inputs[0],h=Io(c,e.inputs[0].dims.length);h.length>0&&(p=e.compute(nr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],c=La(c.length,p.dims.length));let[k,u]=za(p.dims,c),S=k;o.keepDims&&(S=Ba(k,a)),e.compute(Na(t,o.cacheKey,[p],n,e.inputs[0].dataType,S,u),{inputs:[p]})},Xr=(e,t)=>{or(e,"ReduceMeanShared",t,"mean")},ja=(e,t)=>{or(e,"ReduceL1Shared",t,"l1")},Yd=(e,t)=>{or(e,"ReduceL2Shared",t,"l2")},Ua=(e,t)=>{or(e,"ReduceLogSumExpShared",t,"logSumExp")},Jd=(e,t)=>{or(e,"ReduceMaxShared",t,"max")},Va=(e,t)=>{or(e,"ReduceMinShared",t,"min")},Oo=(e,t)=>{or(e,"ReduceProdShared",t,"prod")},Wa=(e,t)=>{or(e,"ReduceSumShared",t,"sum")},Ga=(e,t)=>{or(e,"ReduceSumSquareShared",t,"sumSquare")},Ka=(e,t)=>{or(e,"ReduceLogSumShared",t,"logSum")}}),cr,Jn,Zn,Fo,pr,Do,Ha,qa,Lo,Xa,Qa,zo,Ya,Ja,Bo,hr,Za,Ro,el,tl,No,sl,rl,jo,nl,ol,eo=y(()=>{Ft(),zt(),It(),Gt(),Zd(),cr=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.")},Jn=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Zn=(e,t,s,n,o,i,a=!1,c=!1)=>{let p=[],h=s[0].dims,k=h.length,u=Se.normalizeAxes(o,k),S=!c&&u.length===0;h.forEach((L,se)=>{S||u.indexOf(se)>=0?a&&p.push(1):p.push(L)});let B=p.length,N=Se.size(p);return{name:e,shaderCache:t,getShaderSource:L=>{let se=[],ee=Oe("_A",s[0].dataType,k),V=gt("output",i,B),de=n(ee,V,u),me=de[2];for(let ye=0,Be=0;ye=0?(a&&Be++,me=`for(var j${ye}: u32 = 0; j${ye} < ${h[ye]}; j${ye}++) { + ${de[2].includes("last_index")?`let last_index = j${ye};`:""} + ${ee.indicesSet("input_indices",ye,`j${ye}`)} + ${me} + }`):(se.push(`${ee.indicesSet("input_indices",ye,V.indicesGet("output_indices",Be))};`),Be++);return` + + ${L.registerUniform("output_size","u32").declareVariables(ee,V)} + + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${ee.type.indices}; + let output_indices = ${V.offsetToIndices("global_idx")}; + + ${se.join(` +`)} + ${de[0]} // init ops for reduce max/min + ${de[1]} + ${me} + ${de[3]} + ${de.length===4?V.setByOffset("global_idx","value"):de.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:[{type:12,data:N},...xt(h,p)]})}},Fo=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),Qe({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},pr=(e,t,s,n)=>{let o=e.inputs,i=o.length===1?s:Fo(o,s);e.compute(Zn(t,{hint:i.cacheKey,inputDependencies:["rank"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?Jn:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},Do=(e,t)=>{cr(e.inputs),pr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Ha=(e,t)=>{cr(e.inputs),pr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},qa=(e,t)=>{cr(e.inputs),pr(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Lo=(e,t)=>{cr(e.inputs),pr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},Xa=(e,t)=>{cr(e.inputs),pr(e,"ReduceMax",t,(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(s.indicesSet("input_indices",a,0));return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Qa=(e,t)=>{cr(e.inputs),pr(e,"ReduceMean",t,(s,n,o)=>{let i=1;for(let a=0;a=0||o.length===0)&&(i*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${i});`]})},zo=(e,t)=>{cr(e.inputs),pr(e,"ReduceMin",t,(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Ya=(e,t)=>{cr(e.inputs),pr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Ja=(e,t)=>{cr(e.inputs),pr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Bo=(e,t)=>{cr(e.inputs),pr(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},hr=(e,t,s)=>{if(t.length===0)return s;let n=1,o=1;for(let i=0;i1024},Za=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qa(e,t):Xr(e,t)},Ro=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ha(e,t):ja(e,t)},el=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qa(e,t):Yd(e,t)},tl=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):Ua(e,t)},No=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xa(e,t):Jd(e,t)},sl=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zo(e,t):Va(e,t)},rl=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ya(e,t):Oo(e,t)},jo=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):Wa(e,t)},nl=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):Ga(e,t)},ol=(e,t)=>{hr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Do(e,t):Ka(e,t)}}),Uo,il,Vo,Wo,ec=y(()=>{Ft(),It(),eo(),Uo=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.")},il=(e,t)=>{Uo(e.inputs);let s=(n,o,i)=>{let a=[];for(let c=0;c=0||i.length===0)&&a.push(`input_indices[${c}] = 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); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(Zn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Vo=(e,t)=>{Uo(e.inputs);let s=(n,o,i)=>{let a=[];for(let c=0;c=0||i.length===0)&&a.push(`input_indices[${c}] = 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); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(Zn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Wo=e=>Qe(e)}),Go,to,al,Ko,ll,On,Ho,ul,qo=y(()=>{Ft(),zt(),Hr(),Gt(),Go=(e,t)=>{let s=e[0],n=e[1],o=e[2],i=e[3],a=e[4],c=e[5];if(a&&c)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],k=s.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=o.dims[0]/3,S=u,B=S;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let de of t.qkvHiddenSizes)if(de%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=t.qkvHiddenSizes[0],S=t.qkvHiddenSizes[1],B=t.qkvHiddenSizes[2]}let N=h;if(u!==S)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==u+S+B)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let L=0;if(a){if(S!==B)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]!==p)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]!==S/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(L=a.dims[3])}let se=N+L,ee=-1,V=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(c){if(c.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(c.dims[0]!==p||c.dims[1]!==t.numHeads||c.dims[2]!==h||c.dims[3]!==se)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:L,kvSequenceLength:N,totalSequenceLength:se,maxSequenceLength:ee,inputHiddenSize:k,hiddenSize:u,vHiddenSize:B,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:V,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},to=(e,t,s)=>t&&e?` + let total_sequence_length_input = u32(${t.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,al=(e,t,s,n,o,i,a,c)=>{let p=os(a?1:i),h=64,k=i/p;k{let V=gt("x",e.dataType,e.dims,p),de=[V],me=a?Oe("seq_lens",a.dataType,a.dims):void 0;me&&de.push(me);let ye=c?Oe("total_sequence_length_input",c.dataType,c.dims):void 0;ye&&de.push(ye);let Be=us(e.dataType),Ee=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${ee.registerUniforms(Ee).declareVariables(...de)} + ${ee.mainStart([h,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${to(me,ye,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${a?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${N}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${N}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(p){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${h}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${N}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${N}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${h}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${V.type.value}(${Be}(1.0) / ${Be}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${N}(x[offset + i]); + x[offset + i] = ${V.type.value}(exp(f32input - max_value) / sum); + } + } + ${a?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${V.type.value}(${Be}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${B};${p}`,inputDependencies:L},getShaderSource:se,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/h),y:o,z:t*s},programUniforms:S})}},Ko=(e,t,s,n,o,i,a,c,p)=>{let h=a+i.kvSequenceLength,k=[i.batchSize,i.numHeads,i.sequenceLength,h],u=e>1&&n,S=i.kvNumHeads?i.kvNumHeads:i.numHeads,B=u?[i.batchSize,S,h,i.headSize]:void 0,N=i.nReps?i.nReps:1,L=i.scale===0?1/Math.sqrt(i.headSize):i.scale,se=os(i.headSize),ee=i.headSize/se,V=12,de={x:Math.ceil(h/V),y:Math.ceil(i.sequenceLength/V),z:i.batchSize*i.numHeads},me=[{type:12,data:i.sequenceLength},{type:12,data:ee},{type:12,data:h},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:L},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:N}],ye=u&&n&&Se.size(n.dims)>0,Be=["type","type"];ye&&Be.push("type"),o&&Be.push("type"),c&&Be.push("type"),p&&Be.push("type");let Ee=[{dims:k,dataType:t.dataType,gpuDataType:0}];u&&Ee.push({dims:B,dataType:t.dataType,gpuDataType:0});let tt=pt=>{let Ct=Oe("q",t.dataType,t.dims,se),Dt=Oe("key",s.dataType,s.dims,se),$t=[Ct,Dt];if(ye){let qt=Oe("past_key",n.dataType,n.dims,se);$t.push(qt)}o&&$t.push(Oe("attention_bias",o.dataType,o.dims));let bt=c?Oe("seq_lens",c.dataType,c.dims):void 0;bt&&$t.push(bt);let Kt=p?Oe("total_sequence_length_input",p.dataType,p.dims):void 0;Kt&&$t.push(Kt);let jt=gt("output",t.dataType,k),Lt=[jt];u&&Lt.push(gt("present_key",t.dataType,B,se));let ss=us(1,se),Jt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${V}u; + + var tileQ: array<${Ct.type.storage}, ${V*V}>; + var tileK: array<${Ct.type.storage}, ${V*V}>; + ${pt.registerUniforms(Jt).declareVariables(...$t,...Lt)} + ${pt.mainStart([V,V,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${N===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${N===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${to(bt,Kt,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${ye&&u?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${u?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${ss}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${ye&&u?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${u?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${ss}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(se){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: ${se}`)}})()}; + output[outputIdx] = ${jt.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${se};${o!==void 0};${n!==void 0};${e}`,inputDependencies:Be},getRunData:()=>({outputs:Ee,dispatchGroup:de,programUniforms:me}),getShaderSource:tt}},ll=(e,t,s,n,o,i,a=void 0,c=void 0)=>{let p=i+o.kvSequenceLength,h=o.nReps?o.nReps:1,k=o.vHiddenSize*h,u=e>1&&n,S=o.kvNumHeads?o.kvNumHeads:o.numHeads,B=u?[o.batchSize,S,p,o.headSize]:void 0,N=[o.batchSize,o.sequenceLength,k],L=12,se={x:Math.ceil(o.vHeadSize/L),y:Math.ceil(o.sequenceLength/L),z:o.batchSize*o.numHeads},ee=[{type:12,data:o.sequenceLength},{type:12,data:p},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:k},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:h}],V=u&&n&&Se.size(n.dims)>0,de=["type","type"];V&&de.push("type"),a&&de.push("type"),c&&de.push("type");let me=[{dims:N,dataType:t.dataType,gpuDataType:0}];u&&me.push({dims:B,dataType:t.dataType,gpuDataType:0});let ye=Be=>{let Ee=Oe("probs",t.dataType,t.dims),tt=Oe("v",s.dataType,s.dims),pt=[Ee,tt];V&&pt.push(Oe("past_value",n.dataType,n.dims));let Ct=a?Oe("seq_lens",a.dataType,a.dims):void 0;a&&pt.push(Ct);let Dt=c?Oe("total_sequence_length_input",c.dataType,c.dims):void 0;c&&pt.push(Dt);let $t=[gt("output",t.dataType,N)];u&&$t.push(gt("present_value",t.dataType,B));let bt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${L}u; + var tileQ: array<${Ee.type.value}, ${L*L}>; + var tileV: array<${Ee.type.value}, ${L*L}>; + ${Be.registerUniforms(bt).declareVariables(...pt,...$t)} + ${Be.mainStart([L,L,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${to(Ct,Dt,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${V&&u?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${u?"let presentValueOffset = absKvHeadIdx * 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; + ${V&&u?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${u?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:de},getRunData:()=>({outputs:me,dispatchGroup:se,programUniforms:ee}),getShaderSource:ye}},On=(e,t,s,n,o,i,a,c,p,h,k=void 0,u=void 0)=>{let S=Math.min(e.outputCount,1+(a?1:0)+(c?1:0)),B=S>1?h.pastSequenceLength:0,N=B+h.kvSequenceLength,L=p&&Se.size(p.dims)>0?p:void 0,se=[t,s];S>1&&a&&Se.size(a.dims)>0&&se.push(a),L&&se.push(L),k&&se.push(k),u&&se.push(u);let ee=e.compute(Ko(S,t,s,a,L,h,B,k,u),{inputs:se,outputs:S>1?[-1,1]:[-1]})[0];e.compute(al(ee,h.batchSize,h.numHeads,B,h.sequenceLength,N,k,u),{inputs:k&&u?[ee,k,u]:[ee],outputs:[]});let V=[ee,n];S>1&&c&&Se.size(c.dims)>0&&V.push(c),k&&V.push(k),u&&V.push(u),e.compute(ll(S,ee,n,c,h,B,k,u),{inputs:V,outputs:S>1?[0,2]:[0]})},Ho=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,c={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:o},{type:12,data: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}],k=u=>{let S=gt("output_q",p[0].dataType,s),B=gt("output_k",p[0].dataType,s),N=gt("output_v",p[0].dataType,s),L=Oe("input",p[0].dataType,p[0].dims),se=Oe("weight",p[1].dataType,p[1].dims),ee=Oe("bias",p[2].dataType,p[2].dims),V=L.type.storage,de=[{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<${V}, ${a*a}>; + var tileWeightQ: array<${V}, ${a*a}>; + var tileWeightK: array<${V}, ${a*a}>; + var tileWeightV: array<${V}, ${a*a}>; + ${u.registerUniforms(de).declareVariables(L,se,ee,S,B,N)} + ${u.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 = ${V}(0); + var valueK = ${V}(0); + var valueV = ${V}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},ul=(e,t)=>{let s=Go(e.inputs,t),[n,o,i]=Ho(e,s);return On(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),Xo,dl,cl,Qo,tc=y(()=>{He(),Ft(),zt(),It(),Gt(),Xo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((c,p)=>{if(c!==n[p])throw new Error(`${i}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},dl=(e,t)=>{let{epsilon:s,spatial:n,format:o}=t,i=e[0].dims,a=n?os(i[i.length-1]):1,c=o==="NHWC"&&i.length>1?a:1,p=Se.size(i)/a,h=n,k=h?i.length:i,u=Oe("x",e[0].dataType,e[0].dims,a),S=Oe("scale",e[1].dataType,e[1].dims,c),B=Oe("bias",e[2].dataType,e[2].dims,c),N=Oe("inputMean",e[3].dataType,e[3].dims,c),L=Oe("inputVar",e[4].dataType,e[4].dims,c),se=gt("y",e[0].dataType,k,a),ee=()=>{let de="";if(n)de=`let cOffset = ${i.length===1?"0u":o==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(o==="NCHW")de=` + ${se.indicesSet("outputIndices","0","0")} + let cOffset = ${se.indicesToOffset("outputIndices")};`;else{de=`var cIndices = ${S.type.indices}(0); + cIndices[0] = outputIndices[${i.length-1}];`;for(let me=1;me` + const epsilon = ${s}; + ${de.registerUniform("outputSize","u32").declareVariables(u,S,B,N,L,se)} + ${de.mainStart()} + ${de.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${se.offsetToIndices(`global_idx * ${a}`)}; + ${ee()} + let scale = ${S.getByOffset("cOffset")}; + let bias = ${B.getByOffset("cOffset")}; + let inputMean = ${N.getByOffset("cOffset")}; + let inputVar = ${L.getByOffset("cOffset")}; + let x = ${u.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${se.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...xt(i)]:[{type:12,data:p}]})}},cl=e=>Qe(e),Qo=(e,t)=>{let{inputs:s,outputCount:n}=e,o=cl({...t,outputCount:n});if(x.webgpu.validateInputContent&&Xo(s,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(dl(s,o))}}),pl,Yo,hl,sc=y(()=>{zt(),Gt(),pl=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")},Yo=e=>{let t=e[0].dims,s=e[0].dims[2],n=Se.size(t)/4,o=e[0].dataType,i=Oe("input",o,t,4),a=Oe("bias",o,[s],4),c=Oe("residual",o,t,4),p=gt("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` + const channels = ${s}u / 4; + ${h.declareVariables(i,a,c,p)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${i.getByOffset("global_idx")} + + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")}; + ${p.setByOffset("global_idx","value")} + }`}},hl=e=>{pl(e.inputs),e.compute(Yo(e.inputs))}}),Jo,as,ml,Zo,_l,fl,ei,gl,wl,ti,yl,Ml,bl,vl,si,Tl,Fn,ri,so,xl,ni,Pl,El,oi,Cl,kl,ii,Sl,$l,ai,Al,Il,li,Ol,Fl,ui,Dl,ro,di,Ll,zl,Bl,ci,Rl,Nl,pi=y(()=>{Ft(),zt(),It(),Gt(),Jo=(e,t,s,n,o,i,a)=>{let c=Math.ceil(t/4),p="";typeof o=="string"?p=`${o}(a)`:p=o("a");let h=Oe("inputData",s,[c],4),k=gt("outputData",n,[c],4),u=[{name:"vec_size",type:"u32"}];return a&&u.push(...a),` + ${e.registerUniforms(u).declareVariables(h,k)} + + ${i??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${h.getByOffset("global_idx")}; + ${k.setByOffset("global_idx",p)} + }`},as=(e,t,s,n,o,i=e.dataType,a,c)=>{let p=[{type:12,data:Math.ceil(Se.size(e.dims)/4)}];return a&&p.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:h=>Jo(h,Se.size(e.dims),e.dataType,i,s,n,c),getRunData:h=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(Se.size(h[0].dims)/64/4)},programUniforms:p})}},ml=e=>{e.compute(as(e.inputs[0],"Abs","abs"))},Zo=e=>{e.compute(as(e.inputs[0],"Acos","acos"))},_l=e=>{e.compute(as(e.inputs[0],"Acosh","acosh"))},fl=e=>{e.compute(as(e.inputs[0],"Asin","asin"))},ei=e=>{e.compute(as(e.inputs[0],"Asinh","asinh"))},gl=e=>{e.compute(as(e.inputs[0],"Atan","atan"))},wl=e=>{e.compute(as(e.inputs[0],"Atanh","atanh"))},ti=e=>Qe(e),yl=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(as(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},Ml=e=>{let t,s,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Qe({min:t,max:s})},bl=(e,t)=>{let s=t||Ml(e.inputs),n=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},vl=e=>{e.compute(as(e.inputs[0],"Ceil","ceil"))},si=e=>{e.compute(as(e.inputs[0],"Cos","cos"))},Tl=e=>{e.compute(as(e.inputs[0],"Cosh","cosh"))},Fn=e=>Qe(e),ri=(e,t)=>{let s=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${s}(${t.alpha}); + + fn elu_f32(a: ${s}) -> ${s} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},so=(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)); +}`,xl=e=>{let t=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,so(t)))},ni=e=>{e.compute(as(e.inputs[0],"Exp","exp"))},Pl=e=>{e.compute(as(e.inputs[0],"Floor","floor"))},El=e=>{let t=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,so(t)))},oi=(e,t)=>{let s=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},Cl=e=>{e.compute(as(e.inputs[0],"Not",t=>`!${t}`))},kl=e=>{e.compute(as(e.inputs[0],"Neg",t=>`-${t}`))},ii=e=>{e.compute(as(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Sl=e=>{let t=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},$l=e=>{e.compute(as(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ai=e=>Qe(e),Al=(e,t)=>{let s=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},Il=e=>{e.compute(as(e.inputs[0],"Sin","sin"))},li=e=>{e.compute(as(e.inputs[0],"Sinh","sinh"))},Ol=e=>{e.compute(as(e.inputs[0],"Sqrt","sqrt"))},Fl=e=>{e.compute(as(e.inputs[0],"Tan","tan"))},ui=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Dl=e=>{e.compute(as(e.inputs[0],"Tanh",ui))},ro=(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 ${ui("v")}; +} +`,di=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ll=e=>{let t=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"FastGelu",di,ro(t),void 0,e.inputs[0].dataType))},zl=(e,t)=>{let s=us(e.inputs[0].dataType);return e.compute(as(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},Bl=e=>{e.compute(as(e.inputs[0],"Log","log"))},ci=(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; +} +`,Rl=e=>`quick_gelu_impl(${e})`,Nl=(e,t)=>{let s=us(e.inputs[0].dataType);e.compute(as(e.inputs[0],"QuickGelu",Rl,ci(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),jl,hi,Ul,rc=y(()=>{zt(),Gt(),pi(),jl=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")},hi=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=Oe("input",e[0].dataType,e[0].dims,4),n=Oe("bias",e[0].dataType,[e[0].dims[2]],4),o=gt("output",e[0].dataType,t,4),i=Se.size(t)/4,a=Zt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:c=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${c.declareVariables(s,n,o)} + + ${so(a)} + + ${c.mainStart()} + ${c.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); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Ul=e=>{jl(e.inputs),e.compute(hi(e.inputs))}}),Vl,Wl,ir,Gl,Kl,mi,Hl,ql,_i,Xl,Ql,fi,Yl,nc=y(()=>{Ft(),zt(),Gt(),Vl=(e,t,s,n,o,i,a,c,p,h,k,u)=>{let S,B;typeof c=="string"?S=B=(V,de)=>`${c}((${V}),(${de}))`:typeof c=="function"?S=B=c:(S=c.scalar,B=c.vector);let N=gt("outputData",k,n.length,4),L=Oe("aData",p,t.length,4),se=Oe("bData",h,s.length,4),ee;if(o)if(i){let V=Se.size(t)===1,de=Se.size(s)===1,me=t.length>0&&t[t.length-1]%4===0,ye=s.length>0&&s[s.length-1]%4===0;V||de?ee=N.setByOffset("global_idx",B(V?`${L.type.value}(${L.getByOffset("0")}.x)`:L.getByOffset("global_idx"),de?`${se.type.value}(${se.getByOffset("0")}.x)`:se.getByOffset("global_idx"))):ee=` + let outputIndices = ${N.offsetToIndices("global_idx * 4u")}; + let offsetA = ${L.broadcastedIndicesToOffset("outputIndices",N)}; + let offsetB = ${se.broadcastedIndicesToOffset("outputIndices",N)}; + ${N.setByOffset("global_idx",B(a||me?L.getByOffset("offsetA / 4u"):`${L.type.value}(${L.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||ye?se.getByOffset("offsetB / 4u"):`${se.type.value}(${se.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else ee=N.setByOffset("global_idx",B(L.getByOffset("global_idx"),se.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let V=(de,me,ye="")=>{let Be=`aData[indexA${me}][componentA${me}]`,Ee=`bData[indexB${me}][componentB${me}]`;return` + let outputIndices${me} = ${N.offsetToIndices(`global_idx * 4u + ${me}u`)}; + let offsetA${me} = ${L.broadcastedIndicesToOffset(`outputIndices${me}`,N)}; + let offsetB${me} = ${se.broadcastedIndicesToOffset(`outputIndices${me}`,N)}; + let indexA${me} = offsetA${me} / 4u; + let indexB${me} = offsetB${me} / 4u; + let componentA${me} = offsetA${me} % 4u; + let componentB${me} = offsetB${me} % 4u; + ${de}[${me}] = ${ye}(${S(Be,Ee)}); + `};k===9?ee=` + var data = vec4(0); + ${V("data",0,"u32")} + ${V("data",1,"u32")} + ${V("data",2,"u32")} + ${V("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:ee=` + ${V("outputData[global_idx]",0)} + ${V("outputData[global_idx]",1)} + ${V("outputData[global_idx]",2)} + ${V("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(L,se,N)} + + ${u??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${ee} + }`},Wl=(e,t,s,n,o,i,a=s.dataType)=>{let c=s.dims.map(L=>Number(L)??1),p=n.dims.map(L=>Number(L)??1),h=!Se.areEqual(c,p),k=c,u=Se.size(c),S=!1,B=!1,N=[h];if(h){let L=gs.calcShape(c,p,!1);if(!L)throw new Error("Can't perform binary op on the given tensors");k=L.slice(),u=Se.size(k);let se=Se.size(c)===1,ee=Se.size(p)===1,V=c.length>0&&c[c.length-1]%4===0,de=p.length>0&&p[p.length-1]%4===0;N.push(se),N.push(ee),N.push(V),N.push(de);let me=1;for(let ye=1;yeL.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:L=>Vl(L,c,p,k,S,h,B,o,s.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:k,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(Se.size(k)/4)},...xt(c,p,k)]})}},ir=(e,t,s,n,o,i)=>{e.compute(Wl(t,o??"",e.inputs[0],e.inputs[1],s,n,i))},Gl=e=>{ir(e,"Add",(t,s)=>`${t}+${s}`)},Kl=e=>{ir(e,"Div",(t,s)=>`${t}/${s}`)},mi=e=>{ir(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},Hl=e=>{ir(e,"Mul",(t,s)=>`${t}*${s}`)},ql=e=>{let t=Oe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ir(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},_i=e=>{ir(e,"Sub",(t,s)=>`${t}-${s}`)},Xl=e=>{ir(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},Ql=e=>{ir(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},fi=e=>{ir(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},Yl=e=>{ir(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),gi,Jl,Zl,no,eu,tu,su=y(()=>{Ft(),zt(),It(),Gt(),gi=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],o=n.dataType,i=n.dims.length;e.forEach((a,c)=>{if(c!==s){if(a.dataType!==o)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((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},Jl=(e,t)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${t}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,Zl=(e,t)=>{let s=e.length,n=[];for(let o=0;o{let o=Se.size(s),i=new Array(e.length),a=new Array(e.length),c=0,p=[],h=[],k=[{type:12,data:o}];for(let L=0;L`uniforms.sizeInConcatAxis${L}`).join(","),N=L=>` + + ${(()=>{L.registerUniform("outputSize","u32");for(let se=0;se(${B}); + ${S} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Zl(a,u)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:k}),getShaderSource:N}},eu=(e,t)=>{let s=e.inputs,n=s[0].dims,o=Se.normalizeAxis(t.axis,n.length);gi(s,o);let i=n.slice();i[o]=s.reduce((c,p)=>c+(p.dims.length>o?p.dims[o]:0),0);let a=s.filter(c=>Se.size(c.dims)>0);e.compute(no(a,o,i,s[0].dataType),{inputs:a})},tu=e=>Qe({axis:e.axis})}),Dr,Qr,Lr,wi,Yr=y(()=>{Ft(),zt(),Dr=(e,t,s="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Qr=(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})},Lr=(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"})},wi=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[s,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=e?.activation_params||[Rs,dr];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=e?.activation_params||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Ws,yi,Mi=y(()=>{Ws=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},yi=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),ru,oc=y(()=>{ru=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)); +} +`}),mn,bi,vi=y(()=>{Ft(),zt(),Gt(),Yr(),mn=(e,t,s,n,o)=>{let i=n-s;return` + ${Array.from({length:s}).map((a,c)=>` + if (${Mt(t.shape,c,t.rank)} != 1) { + ${t.indicesSet(e,c,Mt(o,c+i,n))} + } else { + ${t.indicesSet(e,c,0)} + }`).join("")} +`},bi=(e,t,s,n,o=!1,i)=>{let a=e[0].dims,c=e[1].dims,p=a[a.length-2],h=c[c.length-1],k=a[a.length-1],u=os(h),S=os(k),B=os(p),N=Se.size(s)/u/B,L=e.length>2,se=n?n.slice(0,-2):s.slice(0,-2),ee=[Se.size(se),p,h],V=[{type:12,data:N},{type:12,data:p},{type:12,data:h},{type:12,data:k}];Qr(t,V),V.push(...xt(se,a,c)),L&&V.push(...xt(e[2].dims)),V.push(...xt(ee));let de=me=>{let ye=qr("batch_dims",e[0].dataType,se.length),Be=Oe("a",e[0].dataType,a.length,S),Ee=Oe("b",e[1].dataType,c.length,u),tt=gt("output",e[0].dataType,ee.length,u),pt=Zt(tt.type.tensor),Ct=Dr(t,tt.type.value,pt),Dt=[Be,Ee],$t="";if(L){let jt=o?u:1;Dt.push(Oe("bias",e[2].dataType,e[2].dims.length,jt)),$t=`${o?`value += bias[col / ${jt}];`:`value += ${tt.type.value}(bias[row + i]);`}`}let bt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Lr(t,bt);let Kt=()=>{let jt=`var a_data: ${Be.type.value};`;for(let Lt=0;Lt; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${S}) { + ${Kt()} + } + for (var i = 0u; i < ${B}u; i++) { + var value = values[i]; + ${$t} + ${Ct} + let cur_indices = ${tt.type.indices}(batch, row + i, col); + let offset = ${tt.indicesToOffset("cur_indices")}; + ${tt.setByOffset(`offset / ${u}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${u};${S};${B};${o}`,inputDependencies:L?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:V}),getShaderSource:de}}}),Ti,nu,xi,oo,ou,Pi,Ei,io,Ci=y(()=>{Ft(),zt(),Gt(),Yr(),vi(),Mi(),Ti=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${t?", batchIndices":""}); + `,nu=(e,t)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,xi=(e,t,s="f32",n,o=!1,i=32,a=!1,c=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=o?p:i,u=o?i:p,S=k/t[0],B=i/t[1];if(!((o&&S===4&&e[1]===4||!o&&(S===3||S===4))&&k%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${S} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${S} must be 3 or 4. + tileAWidth ${k} 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, ${k/S}>, ${u}>; +var mm_Bsub: array, ${h/e[0]}>, ${i}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${S}; +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) * ${p}; + + let num_tiles = ${a?`${Math.ceil(c/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${c}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${B}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${Ti(o,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${S===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${nu(o,S)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},oo=(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":""}); + `,ou=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Pi=(e,t,s="f32",n,o=!1,i=32,a=!1,c=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],u=o?h:i,S=o?i:h;if(!(S%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${S} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let B=S/t[1],N=u/t[0],L=i/t[1],se=p?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${h}; + let globalColStart = i32(workgroupId.x) * ${k}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${S}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) { + ${oo(o,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${h}; + +let tileRowA = i32(localId.y) * ${B}; +let tileColA = i32(localId.x) * ${N}; +let tileRowB = i32(localId.y) * ${L}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${N}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${oo(o,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${L}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${ou(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${S}>; + 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(c/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${c}`:"0"}; + + var acc : array, rowPerThread>; + ${se} + } +`},Ei=(e,t,s,n,o=!1)=>{let[i,a,c,p]=n,h=Zt(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ws(e,h)} { + var value = ${Ws(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${a.type.indices}; + ${mn("aIndices",a,a.rank-2,i.rank,"batchIndices")} + ${a.indicesSet("aIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ws(e,h)} { + var value = ${Ws(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${c.type.indices}; + ${mn("bIndices",c,c.rank-2,i.rank,"batchIndices")} + ${c.indicesSet("bIndices",c.rank-2,"u32(row)")} + ${c.indicesSet("bIndices",c.rank-1,"u32(colIn)")} + value = ${c.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ws(e,h)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${o?"bias[colIn]":`${Ws(e,h)}(bias[row])`};`:""} + ${s} + ${p.setByIndices("vec3(coords)","value")} + } + } + `},io=(e,t,s,n,o=!1,i)=>{let a=e[0].dims,c=e[1].dims,p=a.slice(0,-2),h=c.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),u=Se.size(k),S=a[a.length-2],B=a[a.length-1],N=c[c.length-1],L=B%4===0&&N%4===0,se=S<=8?[4,1,1]:[4,4,1],ee=[8,8,1],V=[Math.ceil(N/ee[0]/se[0]),Math.ceil(S/ee[1]/se[1]),Math.ceil(u/ee[2]/se[2])],de=L?4:1,me=[...p,S,B/de],ye=me.length,Be=[...h,B,N/de],Ee=Be.length,tt=[u,S,N/de],pt=[{type:6,data:S},{type:6,data:N},{type:6,data:B}];Qr(t,pt),pt.push(...xt(k,me,Be));let Ct=["rank","rank"],Dt=e.length>2;Dt&&(pt.push(...xt(e[2].dims)),Ct.push("rank")),pt.push(...xt(tt));let $t=bt=>{let Kt=k.length,jt=qr("batchDims",e[0].dataType,Kt,1),Lt=Zt(e[0].dataType),ss=Oe("a",e[0].dataType,ye,de),Jt=Oe("b",e[1].dataType,Ee,de),qt=gt("result",e[0].dataType,tt.length,de),Qs=[ss,Jt];if(Dt){let Ts=o?de:1;Qs.push(Oe("bias",e[2].dataType,e[2].dims.length,Ts))}let at=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Lr(t,at);let Pt=Zt(qt.type.tensor),ps=Dr(t,qt.type.value,Pt),vs=Ei(de,Dt,ps,[jt,ss,Jt,qt],o);return` + ${bt.registerUniforms(at).registerInternalVariables(jt).declareVariables(...Qs,qt)} + ${vs} + ${L?xi(se,ee,Lt,jt):Pi(se,ee,Lt,jt)} + `};return{name:"MatMul",shaderCache:{hint:`${se};${t.activation};${L};${o}`,inputDependencies:Ct},getRunData:()=>({outputs:[{dims:i?i(s):s,dataType:e[0].dataType}],dispatchGroup:{x:V[0],y:V[1],z:V[2]},programUniforms:pt}),getShaderSource:$t}}}),ki,iu,ic=y(()=>{Ft(),er(),Gt(),Yr(),Mi(),oc(),Ci(),ki=(e,t,s,n,o=!1,i,a=4,c=4,p=4,h="f32")=>{let k=pt=>{switch(pt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${pt} is not supported.`)}},u=pt=>{switch(pt){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 ${pt} is not supported.`)}},S=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,B=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,N=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",L=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",se=e?"row":"col",ee=e?"col":"row",V=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${se} / outWidth; + let outCol = ${se} % outWidth; + + let WRow = ${ee} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${ee} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${ee} % inChannels; + var resData = ${Ws(a,h)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${N} && xCol >= 0 && xCol < ${L}) { + ${S} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${k(a)} + } + return resData;`,de=e?t&&n?` + let col = colIn * ${a}; + ${V}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${V} + } + return ${Ws(a,h)}(0.0);`:n&&s?` + let col = colIn * ${a}; + ${V}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${V} + } + return ${Ws(a,h)}(0.0);`,me=`${u(c)}`,ye=Ws(p,h),Be=Ws(e?a:c,h),Ee=Ws(e?c:a,h),tt=Dr(i,ye,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Be} { + ${e?de:me} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ee} { + ${e?me:de} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ye}) { + let col = colIn * ${p}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${B} + ${yi(o)} + ${tt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},iu=(e,t,s,n,o,i,a,c,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],u=s[0],S=h?s[2]:s[3],B=h?s[1]:s[2],N=h?s[3]:s[1],L=h&&(k%4===0||k%3===0)&&N%4===0,se=h?N:S*B,ee=h?S*B:N,V=[8,8,1],de=n<=8?[4,1,1]:[4,4,1],me=[Math.ceil(se/V[0]/de[0]),Math.ceil(ee/V[1]/de[1]),Math.ceil(u/V[2]/de[2])];ns("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${me}`);let ye=L?h&&k%4!==0?3:4:1,Be=V[1]*de[1],Ee=V[0]*de[0],tt=Math.max(V[0]*ye,V[1]),pt=n%Be===0,Ct=o%Ee===0,Dt=i%tt===0,$t=L?[ye,4,4]:[1,1,1],bt=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Qr(t,bt),bt.push(...xt(e[0].dims,e[1].dims));let Kt=["rank","rank"];a&&(bt.push(...xt(e[2].dims)),Kt.push("rank")),bt.push(...xt(s));let jt=Lt=>{let ss=[{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}];Lr(t,ss);let Jt=L?4:1,qt=Zt(e[0].dataType),Qs=` + fn setOutputAtIndex(flatIndex : i32, value : ${L?`vec4<${qt}>`:qt}) { + result[flatIndex] = ${L?`vec4<${qt}>`:qt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${L?`vec4<${qt}>`:qt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${L?"/ 4":""}, value); + }`,at=Oe("x",e[0].dataType,e[0].dims.length,ye===3?1:ye),Pt=Oe("w",e[1].dataType,e[1].dims.length,Jt),ps=[at,Pt],vs=gt("result",e[0].dataType,s.length,Jt);if(a){let Ts=Oe("bias",e[2].dataType,e[2].dims.length,Jt);ps.push(Ts),Qs+=` + fn getBiasByOutputCoords(coords : vec4) -> ${L?`vec4<${qt}>`:qt} { + return bias[coords.${h?"w":"y"}${L?"/ 4":""}]; + }`}return` + ${ru("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 }; + ${Lt.registerUniforms(ss).declareVariables(...ps,vs)} + ${Qs} + ${ki(h,pt,Ct,Dt,a,t,$t[0],$t[1],$t[2],qt)} + ${L?xi(de,V,qt,void 0,!h,tt):Pi(de,V,qt,void 0,!h,tt,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ye};${L};${pt};${Ct};${Dt};${Be};${Ee};${tt}`,inputDependencies:Kt},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:me[0],y:me[1],z:me[2]},programUniforms:bt}),getShaderSource:jt}}}),Si,$i,Dn,au,Ai,ao,lu,uu,ac=y(()=>{Ft(),er(),zt(),Gt(),Yr(),Mi(),Si=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,Dn=(e,t)=>t<=1?e:e+(e-1)*(t-1),au=(e,t,s,n=1)=>{let o=Dn(t,n);return Math.floor((e[0]*(s-1)-s+o)/2)},Ai=(e,t,s,n,o)=>{o==null&&(o=au(e,t[0],n[0]));let i=[0,0,0,s];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},ao=(e,t,s,n,o,i,a,c,p,h)=>{let k,u,S,B;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let N=Ai([t,s,n,1],[c,p,h],1,[o,i,a],e);u=N[0],S=N[1],B=N[2]}else if(Array.isArray(e)){if(!e.every((L,se,ee)=>L===ee[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let N=Ai([t,s,n,1],[c,p,h],1,[o,i,a],e[0]);u=N[0],S=N[1],B=N[2]}else if(e==="SAME_UPPER"){u=Math.ceil(t/o),S=Math.ceil(s/i),B=Math.ceil(n/a);let N=(u-1)*o+c-t,L=(S-1)*i+p-s,se=(B-1)*a+h-n,ee=Math.floor(N/2),V=N-ee,de=Math.floor(L/2),me=L-de,ye=Math.floor(se/2),Be=se-ye;k={top:de,bottom:me,left:ye,right:Be,front:ee,back:V}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:u,outHeight:S,outWidth:B}},lu=(e,t,s,n,o,i=!1,a="channelsLast")=>{let c,p,h,k,u;if(a==="channelsLast")[c,p,h,k,u]=e;else if(a==="channelsFirst")[c,u,p,h,k]=e;else throw new Error(`Unknown dataFormat ${a}`);let[S,,B,N,L]=t,[se,ee,V]=$i(s),[de,me,ye]=$i(n),Be=Dn(B,de),Ee=Dn(N,me),tt=Dn(L,ye),{padInfo:pt,outDepth:Ct,outHeight:Dt,outWidth:$t}=ao(o,p,h,k,se,ee,V,Be,Ee,tt),bt=i?S*u:S,Kt=[0,0,0,0,0];return a==="channelsFirst"?Kt=[c,bt,Ct,Dt,$t]:a==="channelsLast"&&(Kt=[c,Ct,Dt,$t,bt]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:h,inWidth:k,inChannels:u,outDepth:Ct,outHeight:Dt,outWidth:$t,outChannels:bt,padInfo:pt,strideDepth:se,strideHeight:ee,strideWidth:V,filterDepth:B,filterHeight:N,filterWidth:L,effectiveFilterDepth:Be,effectiveFilterHeight:Ee,effectiveFilterWidth:tt,dilationDepth:de,dilationHeight:me,dilationWidth:ye,inShape:e,outShape:Kt,filterShape:t}},uu=(e,t,s,n,o,i)=>{let a=i==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let c=[64,1,1],p={x:s.map((se,ee)=>ee)},h=[Math.ceil(Si(p.x.map(se=>s[se]))/c[0]),1,1];ns("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,u=Se.size(s),S=[{type:12,data:u},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Qr(t,S),S.push(...xt(e[0].dims,e[1].dims));let B=["rank","rank"],N=e.length===3;N&&(S.push(...xt(e[2].dims)),B.push("rank")),S.push(...xt(s));let L=se=>{let ee=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Lr(t,ee);let V=1,de=Zt(e[0].dataType),me=Oe("x",e[0].dataType,e[0].dims.length,k),ye=Oe("W",e[1].dataType,e[1].dims.length,V),Be=[me,ye],Ee=gt("result",e[0].dataType,s.length,V),tt="";if(N){let Dt=Oe("bias",e[2].dataType,e[2].dims.length,V);Be.push(Dt),tt+=` + fn getBiasByOutputCoords(coords : array) -> ${de} { + return bias[${a?Mt("coords",4,5):Mt("coords",1,5)}]; + }`}let pt=Ws(k,de),Ct=Dr(t,pt,de);return` + ${tt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${me.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${ye.getByIndices("aIndices")}; + } + ${se.registerUniforms(ee).declareVariables(...Be,Ee)} + ${se.mainStart()} + ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ee.offsetToIndices("global_idx")}; + let batch = ${Mt("coords",0,me.rank)}; + let d2 = ${a?Mt("coords",me.rank-1,me.rank):Mt("coords",1,me.rank)}; + let xFRCCorner = vec3(${a?Mt("coords",1,me.rank):Mt("coords",2,me.rank)}, + ${a?Mt("coords",2,me.rank):Mt("coords",3,me.rank)}, + ${a?Mt("coords",3,me.rank):Mt("coords",4,me.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${a?Mt("uniforms.x_shape",1,me.rank):Mt("uniforms.x_shape",2,me.rank)}; + let xShapeZ = ${a?Mt("uniforms.x_shape",2,me.rank):Mt("uniforms.x_shape",3,me.rank)}; + let xShapeW = ${a?Mt("uniforms.x_shape",3,me.rank):Mt("uniforms.x_shape",4,me.rank)}; + let xShapeU = ${a?Mt("uniforms.x_shape",4,me.rank):Mt("uniforms.x_shape",1,me.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${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); + } + } + } + } + ${N?"value = value + getBiasByOutputCoords(coords)":""}; + ${Ct} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${k};${N}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:S}),getShaderSource:L}}}),du,cu,pu=y(()=>{Ft(),zt(),Gt(),Yr(),du=(e,t,s,n)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",a=e[0].dims,c=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,u=p&&k>=4?os(h):1,S=Se.size(s)/u,B=[{type:12,data:S},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:k}];Qr(t,B),B.push(...xt(a,[c[0],c[1],c[2],c[3]/u]));let N=o?["rank","rank","rank"]:["rank","rank"];B.push(...xt([s[0],s[1],s[2],s[3]/u]));let L=se=>{let ee=gt("output",e[0].dataType,s.length,u),V=Zt(ee.type.tensor),de=Dr(t,ee.type.value,V),me=Oe("x",e[0].dataType,a.length),ye=Oe("w",e[1].dataType,c.length,u),Be=[me,ye];o&&Be.push(Oe("b",e[2].dataType,e[2].dims,u));let Ee=[{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"}];Lr(t,Ee);let tt=p?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${me.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${ye.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${me.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${ye.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${se.registerUniforms(Ee).declareVariables(...Be,ee)} + + ${se.mainStart()} + ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ee.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${p?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; + + var value: ${ee.type.value} = ${ee.type.value}(0); + ${tt} + ${i} + ${de} + ${ee.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:N},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:B}),getShaderSource:L}},cu=(e,t,s,n)=>{let o=e.length>2,i=os(s[3]),a=os(s[2]),c=Se.size(s)/i/a,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],k=[s[0],s[1],s[2],s[3]/i],u=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Qr(t,u),u.push(...xt(p,h,k));let S=(a-1)*t.strides[1]+h[1],B=N=>{let L=gt("output",e[0].dataType,k.length,i),se=Zt(L.type.tensor),ee=Dr(t,L.type.value,se),V=Oe("x",e[0].dataType,p.length,i),de=Oe("w",e[1].dataType,h.length,i),me=[V,de];o&&me.push(Oe("b",e[2].dataType,e[2].dims,i));let ye=o?"value += b[output_channel];":"",Be=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Lr(t,Be),` + ${N.registerUniforms(Be).declareVariables(...me,L)} + ${N.mainStart()} + ${N.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<${V.type.value}, ${S}>; + var values: array<${L.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 < ${h[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${S}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${V.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${V.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { + let w_val = ${de.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]; + ${ye} + ${ee} + ${L.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${a};${S};${h[0]};${h[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u}),getShaderSource:B}}}),hu,lo,Ii,uo,Oi,Fi,mu,Di,Li,lc=y(()=>{zt(),ic(),ac(),Ci(),pu(),Yr(),vi(),Fr(),hu=(e,t,s,n,o,i)=>{let a=e[0],c=e.slice(i?1:2,i?3:4),p=c.length,h=t[0],k=t.slice(2).map((S,B)=>S+(S-1)*(s[B]-1)),u=c.map((S,B)=>S+n[B]+n[B+p]).map((S,B)=>Math.floor((S-k[B]+o[B])/o[B]));return u.splice(0,0,a),u.splice(i?3:1,0,h),u},lo=[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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},uo=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=wi(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,c=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:o,group:i,kernelShape:a,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Fi=(e,t,s,n)=>{let o=s.format==="NHWC",i=hu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,o);if(s.group!==1){let Be=[t[0]];if(o){let Ee=e.kernelCustomData.wT??e.compute(nr(t[1],lo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ee),Be.push(Ee)}else Be.push(t[1]);t.length===3&&Be.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(cu(Be,s,i,n),{inputs:Be}):e.compute(du(Be,s,i,n),{inputs:Be});return}let a=t.length===3,c=t[0].dims[o?1:2],p=t[0].dims[o?2:3],h=t[0].dims[o?3:1],k=t[1].dims[2],u=t[1].dims[3],S=i[o?1:2],B=i[o?2:3],N=i[o?3:1],L=o&&k===c&&u===p&&s.pads[0]===0&&s.pads[1]===0;if(L||k===1&&u===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let Be=i[0],Ee,tt,pt,Ct=[];if(o){let bt=e.kernelCustomData.wT??e.compute(nr(t[1],lo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=bt),L){let Kt=c*p*h;Ee=t[0].reshape([1,Be,Kt]),tt=bt.reshape([1,Kt,N]),pt=[1,Be,N]}else Ee=t[0].reshape([Be,c*p,h]),tt=bt.reshape([1,h,N]),pt=[Be,S*B,N];Ct.push(Ee),Ct.push(tt)}else Ee=t[0].reshape([Be,h,c*p]),tt=t[1].reshape([1,N,h]),pt=[Be,N,S*B],Ct.push(tt),Ct.push(Ee);a&&Ct.push(t[2]);let Dt=pt[2],$t=Ct[0].dims[Ct[0].dims.length-1];Dt<8&&$t<8?e.compute(bi(Ct,s,i,pt,o,n),{inputs:Ct}):e.compute(io(Ct,s,i,pt,o,n),{inputs:Ct});return}let se=!0,ee=e.kernelCustomData.wT??e.compute(nr(t[1],lo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ee);let V=[t[0],ee];a&&V.push(t[2]);let de=o?S*B:N,me=o?N:S*B,ye=k*u*h;e.compute(iu(V,s,i,de,me,ye,a,se,n),{inputs:V})},mu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),c=[1].concat(t.kernelShape),p=uo({...t,pads:o,strides:i,dilations:a,kernelShape:c},n);Fi(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Di=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",o=uo(s,t),i=s.autoPad==="NOTSET"?s.pads:s.autoPad,a=lu(t[0].dims,t[1].dims,s.strides,s.dilations,i,!1,n);e.compute(uu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},Li=(e,t)=>{if(Ii(e.inputs,t),e.inputs[0].dims.length===3)mu(e,t);else if(e.inputs[0].dims.length===5)Di(e,e.inputs,t);else{let s=uo(t,e.inputs);Fi(e,e.inputs,s)}}}),zi,uc=y(()=>{Ft(),er(),zt(),Gt(),zi=(e,t,s)=>{let n=e.length>2,o=t.outputShape,i=t.format==="NHWC",a=t.group,c=e[1].dims,p=c[2]/a,h=c[3],k=i?os(h):1,u=Se.size(o)/k,S=[Math.ceil(u/64),1,1];ns("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${S}`);let B=["rank","rank"],N=[t.strides[0],t.strides[1]],L=[t.kernelShape[i?1:2],t.kernelShape[i?2:3]],se=[t.dilations[0],t.dilations[1]],ee=[L[0]+(t.dilations[0]<=1?0:(t.kernelShape[i?1:2]-1)*(t.dilations[0]-1)),L[1]+(t.dilations[1]<=1?0:(t.kernelShape[i?2:3]-1)*(t.dilations[1]-1))],V=[ee[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),ee[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],de=[{type:12,data:u},{type:12,data:N},{type:12,data:L},{type:12,data:se},{type:12,data:ee},{type:6,data:V},{type:12,data:p},{type:12,data:h},...xt(e[0].dims,e[1].dims)];n&&(de.push(...xt(e[2].dims)),B.push("rank")),de.push(...xt(o));let me=ye=>{let Be=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:N.length},{name:"filter_dims",type:"u32",length:L.length},{name:"dilations",type:"u32",length:L.length},{name:"effective_filter_dims",type:"u32",length:ee.length},{name:"pads",type:"i32",length:V.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ee=Zt(e[0].dataType),tt=i?1:2,pt=i?2:3,Ct=i?3:1,Dt=Oe("W",e[1].dataType,e[1].dims.length,k),$t=Oe("Dy",e[0].dataType,e[0].dims.length),bt=[$t,Dt];n&&bt.push(Oe("bias",e[2].dataType,[o[Ct]].length,k));let Kt=gt("result",e[0].dataType,o.length,k),jt=` + let outputIndices = ${Kt.offsetToIndices(`global_idx * ${k}`)}; + let batch = ${Kt.indicesGet("outputIndices",0)}; + let d1 = ${Kt.indicesGet("outputIndices",Ct)}; + let r = ${Kt.indicesGet("outputIndices",tt)}; + let c = ${Kt.indicesGet("outputIndices",pt)}; + 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 = ${Kt.type.value}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${Ee}(dyRCorner) + ${Ee}(wR)) / ${Ee}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${Ee}(uniforms.Dy_shape[${tt}]) || 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 = (${Ee}(dyCCorner) + ${Ee}(wC)) / ${Ee}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${Ee}(uniforms.Dy_shape[${pt}]) || + 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 = ${i?$t.get("batch","idyR","idyC","inputChannel"):$t.get("batch","inputChannel","idyR","idyC")}; + let w_offset = ${Dt.indicesToOffset(`${Dt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${Dt.getByOffset(`w_offset / ${k}`)}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd${n?` + bias[d1 / ${k}]`:""}; + ${Kt.setByOffset("global_idx","value")}; + `;return` + ${ye.registerUniforms(Be).declareVariables(...bt,Kt)} + ${ye.mainStart()} + ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${jt}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}`,inputDependencies:B},getRunData:()=>({dispatchGroup:{x:S[0],y:S[1],z:S[2]},outputs:[{dims:s?s(o):o,dataType:e[0].dataType}],programUniforms:de}),getShaderSource:me}}}),_u,Bi,fu,Ri,Ni,gu,ji,wu,yu,dc=y(()=>{uc(),Yr(),Fr(),_u=(e,t,s,n,o,i)=>(e-1)*t+s+(n-1)*o+1-i,Bi=(e,t,s,n,o)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=i,s[o]=e-i):t==="SAME_LOWER"&&(s[n]=e-i,s[o]=i)},fu=(e,t,s,n,o,i,a,c,p,h)=>{let k=e.length-2,u=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,S)=>u*S,1)===0){s.length=0;for(let u=2;uu+S,0)===0){let u=t[0].dims.length-2;p=new Array(u).fill(1)}let h=e.strides.slice();if(h.reduce((u,S)=>u+S,0)===0){let u=t[0].dims.length-2;h=new Array(u).fill(1)}fu(c,s,p,e.autoPad,e.group,o,h,n,a,i);let k=Object.assign({},e);return Object.assign(k,{kernelShape:s,pads:o,outputPadding:a,outputShape:i,dilations:p,strides:h}),k},Ni=e=>{let t=wi(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,c=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,u=e.outputShape;return{autoPad:n,format:s,dilations:o,group:i,kernelShape:a,outputPadding:k,outputShape:u,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},gu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((a,c)=>a+c,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((a,c)=>a+c,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((a,c)=>a+c,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,c)=>a+c,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")},ji=(e,t,s,n)=>{let o=e.kernelCustomData.wT??e.compute(nr(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let i=[t[0],o];t.length===3&&i.push(t[2]),e.compute(zi(i,s,n),{inputs:i})},wu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let p=Ri({...t,pads:c,strides:a,dilations:i,kernelShape:o},n);ji(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},yu=(e,t)=>{if(gu(e.inputs,t),e.inputs[0].dims.length===3)wu(e,t);else{let s=Ri(t,e.inputs);ji(e,e.inputs,s)}}}),Mu,Ui,bu,cc=y(()=>{Ft(),zt(),It(),Gt(),Mu=(e,t,s,n)=>{let o=Se.size(t),i=t.length,a=Oe("input",e,i),c=gt("output",e,i),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=Se.normalizeAxis(p,i),k=u=>{let S=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,B=Mt("uniforms.input_shape","uniforms.axis",i),N=n.reverse?S+(n.exclusive?" + 1":""):"0",L=n.reverse?B:S+(n.exclusive?"":" + 1");return` + ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,c)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${c.offsetToIndices("global_idx")}; + var sum = ${c.type.value}(0); + let first : i32 = ${N}; + let last : i32 = ${L}; + for (var i : i32 = first; i < last; i++) { + ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${a.getByIndices("inputIndices")}; + } + ${c.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:h},...xt(t,t)]}),getShaderSource:k}},Ui=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(Mu(n,s,o,t),{inputs:[0]})},bu=e=>{let t=e.exclusive===1,s=e.reverse===1;return Qe({exclusive:t,reverse:s})}}),Vi,vu,Tu,zr,xu,pc=y(()=>{Ft(),zt(),It(),Gt(),Vi=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.")},vu=(e,t,s,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let i=0;i{let s,n,o,i,a,c,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([s,n,o,i]=e.dims,a=k?[s,n,o,h,h,i/h**2]:[s,n,o,i/h**2,h,h],c=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=k?[s,h,h,i/h**2,n,o]:[s,i/h**2,h,h,n,o],c=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),S=u.dims.length,B=e.dataType,N=Oe("a",B,S),L=gt("output",B,S),se=ee=>` + ${ee.registerUniform("output_size","u32").declareVariables(N,L)} + + ${vu(c,S,N,L)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${L.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${L.setByOffset("global_idx",N.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:ee=>{let V=p?[s,n*h,o*h,i/h**2]:[s,i/h**2,n*h,o*h],de=Se.size(V),me=u.dims,ye=Se.sortBasedOnPerm(me,c);return{outputs:[{dims:V,dataType:ee[0].dataType}],dispatchGroup:{x:Math.ceil(de/64)},programUniforms:[{type:12,data:de},...xt(me,ye)]}},getShaderSource:se}},zr=(e,t)=>{Vi(e.inputs),e.compute(Tu(e.inputs[0],t))},xu=e=>Qe({blocksize:e.blocksize,mode:e.mode,format:e.format})}),co,Ln,po,Pu,Eu,Cu,ku,zn,Su,$u,Au,ho=y(()=>{Ft(),zt(),It(),Gt(),co="[a-zA-Z]|\\.\\.\\.",Ln="("+co+")+",po="^"+Ln+"$",Pu="("+Ln+",)*"+Ln,Eu="^"+Pu+"$",Cu=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},ku=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(Eu)))throw new Error("Invalid LHS term");if(s.split(",").forEach((o,i)=>{let a=e[i].dims.slice();if(!o.match(RegExp(po)))throw new Error("Invalid LHS term");let c=this.processTerm(o,!0,a,i);this.lhs.push(c)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([o,i])=>i.count===1||o==="...").map(([o])=>o).join("");else if(!n.match(RegExp(Ln)))throw new Error("Invalid RHS");n.match(RegExp(co,"g"))?.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(o);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let o=s.length,i=!1,a=[],c=0;if(!e.match(RegExp(po))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(co,"g")),h=new Cu(n);return p?.forEach((k,u)=>{if(k==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let S=o-p.length+1;if(S<0)throw new Error("Ellipsis out of bounds");if(a=s.slice(c,c+S),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 B=0;Be+"_max",Su=(e,t,s,n)=>{let o=e.map(h=>h.length).map((h,k)=>Oe(`input${k}`,t,h)),i=Se.size(n),a=gt("output",t,n.length),c=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],u="var prod = 1.0;",S="var sum = 0.0;",B="sum += prod;",N=[],L=[],se=[],ee=[],V=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((me,ye)=>{if(s.rhs.symbolToIndices.has(ye)){let Be=s.rhs.symbolToIndices.get(ye)?.[0];Be!==void 0&&s.lhs.forEach((Ee,tt)=>{if(me.inputIndices.includes(tt)){let pt=Ee.symbolToIndices.get(ye);if(pt===void 0)throw new Error("Invalid symbol error");pt.forEach(Ct=>{k.push(`${o[tt].indicesSet(`input${tt}Indices`,Ct,a.indicesGet("outputIndices",Be))}`)})}})}else s.lhs.forEach((Be,Ee)=>{if(me.inputIndices.includes(Ee)){let tt=Be.symbolToIndices.get(ye);if(tt===void 0)throw new Error("Invalid symbol error");tt.forEach(pt=>{N.push(`${o[Ee].indicesSet(`input${Ee}Indices`,pt,`${ye}`)}`)}),ee.push(`prod *= ${o[Ee].getByIndices(`input${Ee}Indices`)};`)}}),L.push(`for(var ${ye}: u32 = 0; ${ye} < uniforms.${zn(ye)}; ${ye}++) {`),se.push("}")});let de=V?[...k,`let sum = ${o.map((me,ye)=>me.getByIndices(`input${ye}Indices`)).join(" * ")};`]:[...k,S,...L,...N,u,...ee,B,...se];return` + ${h.registerUniforms(c.map(me=>({name:`${zn(me)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,a)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${a.offsetToIndices("global_idx")}; + ${o.map((me,ye)=>`var input${ye}Indices: ${o[ye].type.indices};`).join(` +`)} + ${de.join(` +`)}; + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=c.filter(u=>s.symbolToInfo.has(u)).map(u=>({type:12,data:s.symbolToInfo.get(u)?.dimValue||0}));h.push({type:12,data:i});let k=e.map((u,S)=>[...xt(u)]).reduce((u,S)=>u.concat(S),h);return k.push(...xt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:k}},getShaderSource:p}},$u=(e,t)=>{let s=new ku(e.inputs,t.equation),n=s.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Su(o,e.inputs[0].dataType,s,n))},Au=e=>{let t=e.equation.replace(/\s+/g,"");return Qe({equation:t})}}),Iu,Wi,Ou,Fu,mo,hc=y(()=>{Ft(),zt(),Gt(),Iu=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let o=0;oe.length>t.length?Wi(e,t):Wi(t,e),Fu=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Ou(t,s),o=e[0].dataType,i=o===9||Se.size(t)===1,a=o===9||t.length>0&&t[t.length-1]%4===0?4:1,c=i||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(Se.size(n)/c),h=u=>{let S=Oe("input",o,t.length,a),B=gt("output",o,n.length,c),N;if(o===9){let L=(se,ee,V="")=>` + let outputIndices${ee} = ${B.offsetToIndices(`outputOffset + ${ee}u`)}; + let offset${ee} = ${S.broadcastedIndicesToOffset(`outputIndices${ee}`,B)}; + let index${ee} = offset${ee} / 4u; + let component${ee} = offset${ee} % 4u; + ${se}[${ee}] = ${V}(${S.getByOffset(`index${ee}`)}[component${ee}]); + `;N=` + let outputOffset = global_idx * ${c}; + var data = vec4(0); + ${L("data",0,"u32")} + ${L("data",1,"u32")} + ${L("data",2,"u32")} + ${L("data",3,"u32")} + ${B.setByOffset("global_idx","data")} + }`}else N=` + let outputIndices = ${B.offsetToIndices(`global_idx * ${c}`)}; + let inputOffset = ${S.broadcastedIndicesToOffset("outputIndices",B)}; + let data = ${B.type.value}(${S.getByOffset(`inputOffset / ${a}`)}); + ${B.setByOffset("global_idx","data")} + }`;return` + ${u.registerUniform("vec_size","u32").declareVariables(S,B)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${N}`},k=[{type:12,data:p},...xt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${a}${c}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},mo=e=>{Iu(e.inputs),e.compute(Fu(e.inputs),{inputs:[0]})}}),Du,Lu,Ep=y(()=>{Ft(),zt(),Gt(),pi(),Du=e=>{let t=e[0].dataType,s=Se.size(e[0].dims),n=Se.size(e[1].dims),o=n%4===0,i=a=>{let c=Oe("x",t,[1],4),p=Oe("bias",t,[1],4),h=gt("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=B=>` + let bias${B}_offset: u32 = (global_idx * 4 + ${B}) % uniforms.bias_size; + let bias${B} = ${p.getByOffset(`bias${B}_offset / 4`)}[bias${B}_offset % 4];`,S=o?` + let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${u(0)}${u(1)}${u(2)}${u(3)} + let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(k).declareVariables(c,p,h)} + + ${ro(us(t))} + + ${a.mainStart(zs)} + ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${c.getByOffset("global_idx")}; + ${S} + let x_in = x + bias; + ${h.setByOffset("global_idx",di("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/zs/4)}})}},Lu=e=>{e.inputs.length<2||Se.size(e.inputs[1].dims)===0?Ll(e):e.compute(Du(e.inputs))}}),zu,Bu,Ru,_n,mc=y(()=>{Ft(),zt(),It(),Gt(),zu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Bu=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,i=Se.normalizeAxis(t.axis,o),a=s.slice(0);a.splice(i,1,...n);let c=s[i],p=e[0].dataType===9?4:1,h=Math.ceil(Se.size(a)/p),k=[{type:12,data:h},{type:6,data:c},{type:12,data:i},...xt(e[0].dims,e[1].dims,a)],u=S=>{let B=Oe("data",e[0].dataType,e[0].dims.length,p),N=Oe("inputIndices",e[1].dataType,e[1].dims.length),L=gt("output",e[0].dataType,a.length,p),se=V=>{let de=n.length,me=`var indicesIndices${V} = ${N.type.indices}(0);`;for(let ye=0;ye1?`indicesIndices${V}[${ye}]`:`indicesIndices${V}`} = ${a.length>1?`outputIndices${V}[uniforms.axis + ${ye}]`:`outputIndices${V}`};`;me+=` + var idx${V} = ${N.getByIndices(`indicesIndices${V}`)}; + if (idx${V} < 0) { + idx${V} = idx${V} + uniforms.axisDimLimit; + } + var dataIndices${V} : ${B.type.indices}; + `;for(let ye=0,Be=0;ye1?`dataIndices${V}[${ye}]`:`dataIndices${V}`} = u32(idx${V});`,Be+=de):(me+=`${o>1?`dataIndices${V}[${ye}]`:`dataIndices${V}`} = ${a.length>1?`outputIndices${V}[${Be}]`:`outputIndices${V}`};`,Be++);return me},ee;if(e[0].dataType===9){let V=(de,me,ye="")=>` + let outputIndices${me} = ${L.offsetToIndices(`outputOffset + ${me}u`)}; + ${se(me)}; + let offset${me} = ${B.indicesToOffset(`dataIndices${me}`)}; + let index${me} = offset${me} / 4u; + let component${me} = offset${me} % 4u; + ${de}[${me}] = ${ye}(${B.getByOffset(`index${me}`)}[component${me}]); + `;ee=` + let outputOffset = global_idx * ${p}; + var value = vec4(0); + ${V("value",0,"u32")} + ${V("value",1,"u32")} + ${V("value",2,"u32")} + ${V("value",3,"u32")} + ${L.setByOffset("global_idx","value")} + `}else ee=` + let outputIndices = ${L.offsetToIndices("global_idx")}; + ${se("")}; + let value = ${B.getByIndices("dataIndices")}; + ${L.setByOffset("global_idx","value")}; + `;return` + ${S.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(B,N,L)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${ee} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:u}},Ru=e=>Qe({axis:e.axis}),_n=(e,t)=>{let s=e.inputs;zu(s),e.compute(Bu(e.inputs,t))}}),Nu,ju,Uu,_c=y(()=>{Ft(),zt(),Gt(),Nu=(e,t,s,n,o,i,a,c,p)=>{let h=[{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:12,data:s},{type:12,data:a},{type:12,data:c},{type:12,data:p}],k=[i];h.push(...xt(t.dims,k));let u=S=>{let B=Oe("indices_data",t.dataType,t.dims.length),N=gt("input_slice_offsets_data",12,1,1),L=[B,N],se=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${S.registerUniforms(se).declareVariables(...L)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h}),getShaderSource:u},{inputs:[t],outputs:[-1]})[0]},ju=(e,t)=>{let s=e.inputs,n=s[0].dims,o=s[0].dataType,i=s[1].dims,a=i[i.length-1],c=Se.sizeToDimension(i,i.length-1),p=Se.sizeFromDimension(n,t.batchDims+a),h=Se.sizeToDimension(n,t.batchDims),k=Se.sizeFromDimension(n,t.batchDims),u=c/h,S=new Array(a),B=p;for(let me=0;men.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let se=i.slice(0,-1).concat(n.slice(L)),ee=Se.size(se),V=[{type:12,data:ee},{type:12,data:p},...xt(s[0].dims,N.dims,se)],de=me=>{let ye=Oe("data",s[0].dataType,s[0].dims.length),Be=Oe("slice_offsets",12,N.dims.length),Ee=gt("output",s[0].dataType,se.length);return` + ${me.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(ye,Be,Ee)} + ${me.mainStart()} + ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:se,dataType:o}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:V}),getShaderSource:de},{inputs:[s[0],N]})},Uu=e=>({batchDims:e.batch_dims,cacheKey:""})}),_o,fc,Vu,Wu,gc=y(()=>{Ft(),zt(),It(),Gt(),_o=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=Se.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((c,p)=>p===s?Math.ceil(c/n)===i.dims[p]:c===i.dims[p]).reduce((c,p)=>c&&p,!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!==o.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((c,p)=>c===i.dims[p]).reduce((c,p)=>c&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},fc=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,i=Se.normalizeAxis(t.gatherAxis,o),a=Se.normalizeAxis(t.quantizeAxis,o),c=s.slice(0);c.splice(i,1,...n);let p=Se.size(c),h=e[2].dataType,k=e[0].dataType===22,u=[{type:12,data:p},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...xt(...e.map((B,N)=>B.dims),c)],S=B=>{let N=Oe("data",e[0].dataType,e[0].dims.length),L=Oe("inputIndices",e[1].dataType,e[1].dims.length),se=Oe("scales",e[2].dataType,e[2].dims.length),ee=e.length>3?Oe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,V=gt("output",h,c.length),de=[N,L,se];ee&&de.push(ee);let me=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${B.registerUniforms(me).declareVariables(...de,V)} + ${B.mainStart()} + let output_indices = ${V.offsetToIndices("global_idx")}; + var indices_indices = ${L.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${V.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${L.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${V.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${N.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${V.indicesGet("output_indices","i")}; + ${N.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${L.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${s[i]}; + } + ${N.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) { + let index = ${V.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${N.indicesSet("data_indices","i","index")}; + } + let data_offset = ${N.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${N.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${se.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${se.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${se.getByIndices("scale_indices")}; + ${ee?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${ee.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${ee.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${us(h)}(quantized_data - zero_point) * scale; + ${V.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((B,N)=>N!==1).map(B=>B.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(B,N)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:u}),getShaderSource:S}},Vu=(e,t)=>{let s=e.inputs;_o(s,t),e.compute(fc(e.inputs,t))},Wu=e=>Qe({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Gu,Ku,Gi,Hu,wc=y(()=>{Ft(),zt(),It(),Gt(),Gu=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.`)},Ku=(e,t)=>{let s=e[0].dims,n=e[0].dataType,o=s.length,i=e[1].dims,a=e[1].dataType,c=Se.normalizeAxis(t.axis,o),p=s[c],h=i.slice(0),k=Se.size(h),u=Oe("input",n,o),S=Oe("indicesInput",a,i.length),B=gt("output",n,h.length),N=[{type:12,data:k},{type:6,data:p},{type:12,data:c}];return N.push(...xt(s,i,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:N}),getShaderSource:L=>` + ${L.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,S,B)} + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${B.offsetToIndices("global_idx")}; + + var idx = ${S.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${u.type.indices}(outputIndices); + ${u.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${u.getByIndices("inputIndices")}; + + ${B.setByOffset("global_idx","value")}; + }`}},Gi=e=>Qe({axis:e.axis}),Hu=(e,t)=>{let s=e.inputs;Gu(s),e.compute(Ku(e.inputs,t))}}),Ki,qu,Xu,Hi,yc=y(()=>{Ft(),zt(),Gt(),Ki=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")},qu=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=js.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),c=[o,i];if(!c)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(i/p),k=Math.ceil(o/p),u=!0,S=Se.size(c),B=[{type:12,data:u?h:S},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],N=["type","type"];e.length===3&&(B.push(...xt(e[2].dims)),N.push("rank")),B.push(...xt(c));let L=ee=>{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 de=t.alpha===1?"":"value *= uniforms.alpha;",me=Oe("a",e[0].dataType,e[0].dims),ye=Oe("b",e[1].dataType,e[1].dims),Be=me.type.value,Ee=null,tt=[me,ye];e.length===3&&(Ee=Oe("c",e[2].dataType,e[2].dims.length),tt.push(Ee));let pt=gt("output",e[0].dataType,c.length);tt.push(pt);let Ct=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${ee.registerUniforms(Ct).declareVariables(...tt)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Be}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${V} + } + + ${de} + ${Ee!=null?`let cOffset = ${Ee.broadcastedIndicesToOffset("vec2(m, n)",pt)}; value += ${Be}(uniforms.beta) * ${Ee.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},se=ee=>{let V=Oe("a",e[0].dataType,e[0].dims),de=Oe("b",e[1].dataType,e[1].dims),me=null,ye=[V,de];e.length===3&&(me=Oe("c",e[2].dataType,e[2].dims.length),ye.push(me));let Be=gt("output",e[0].dataType,c.length);ye.push(Be);let Ee=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],tt="",pt="";t.transA&&t.transB?(pt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${de.type.value}(0); + } + `,tt="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(pt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${de.type.value}(0); + } + `,tt="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(pt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${de.type.value}(0); + } + `,tt="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(pt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${de.type.value}(0); + } + `,tt="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Ct=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${ee.registerUniforms(Ee).declareVariables(...ye)} + var tile_a: array, ${p}>; + var tile_b: array, ${p}>; + ${ee.mainStart([p,p,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; + let num_tiles = (uniforms.K - 1) / ${p} + 1; + var k_start = 0u; + var value = ${Be.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${pt} + k_start = k_start + ${p}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${p}; k++) { + ${tt} + } + workgroupBarrier(); + } + + ${Ct} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${me!=null?`let cOffset = ${me.broadcastedIndicesToOffset("vec2(m, n)",Be)}; value += ${Be.type.value}(uniforms.beta) * ${me.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return u?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:N},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:B}),getShaderSource:se}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:N},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:B}),getShaderSource:L}},Xu=e=>{let t=e.transA,s=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:s,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Hi=(e,t)=>{Ki(e.inputs),e.compute(qu(e.inputs,t))}}),yr,mr,Jr,Zr,Qu,Yu,qi,fo,Mc,Ju,Zu,Xi,ed,td,sd=y(()=>{Ft(),zt(),It(),Gt(),[yr,mr,Jr,Zr]=[0,1,2,3],Qu=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Yu=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,qi=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,fo=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,Mc=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,Ju=(e,t,s)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { + var pixel = ${t}(0); + var indices = vec4(0); + indices[${yr}] = batch; + indices[${mr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Jr}] = u32(r); + indices[${Zr}] = u32(c); + } + `;case"border":return` + indices[${Jr}] = u32(clamp(r, 0, H - 1)); + indices[${Zr}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Jr}] = gs_reflect(r, border[1], border[3]); + indices[${Zr}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,Zu=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${yr}], indices[${mr}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${yr}], indices[${mr}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${yr}], indices[${mr}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${yr}], indices[${mr}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${yr}], indices[${mr}], border); + + let dx2 = ${t}(f32(x2) - x); + let dx1 = ${t}(x - f32(x1)); + let dy2 = ${t}(f32(y2) - y); + let dy1 = ${t}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${t}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${yr}], indices[${mr}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Xi=(e,t)=>{let s=Oe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Oe("grid",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[yr,mr,Jr,Zr]=[0,3,1,2]);let a=gt("output",e[0].dataType,i.length),c=s.type.value,p=Se.size(i),h=[{type:12,data:p},...xt(e[0].dims,n,i)],k=u=>` + ${u.registerUniform("output_size","u32").declareVariables(s,o,a)} + ${Yu} + ${qi(c)} + ${fo(t)} + ${Mc(t)} + ${Ju(s,c,t)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Jr}]); + let W_in = i32(uniforms.x_shape[${Zr}]); + + ${t.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${a.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${yr}], indices[${Jr}], indices[${Zr}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${Zu(a,c,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let S=Se.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:h}},getShaderSource:k}},ed=(e,t)=>{Qu(e.inputs),e.compute(Xi(e.inputs,t))},td=e=>Qe({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Hs,rd,Qi,nd,bc,fn,Yi,od=y(()=>{Ft(),zt(),It(),Hr(),qo(),Gt(),Fr(),Hs=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,rd=(e,t)=>{let s=e[0],n=Hs(e,1),o=Hs(e,2),i=Hs(e,3),a=Hs(e,4),c=Hs(e,5),p=Hs(e,6),h=Hs(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=s.dims[0],u=s.dims[1],S=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],B=u,N=0,L=0,se=Math.floor(S/t.numHeads);if(p&&h&&Se.size(p.dims)&&Se.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==se)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==se)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');N=p.dims[2],L=p.dims[2]}else if(p&&Se.size(p.dims)||h&&Se.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee;if(n&&Se.size(n.dims)>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');ee=2,B=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==se)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');ee=5,B=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==se)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');ee=0,B=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}if(i&&Se.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 V=N+B,de=0;if(a&&Se.size(a.dims)>0){de=8;let Ee=a.dims;throw Ee.length===1?Ee[0]===k?de=1:Ee[0]===3*k+2&&(de=3):Ee.length===2&&Ee[0]===k&&Ee[1]===V&&(de=5),de===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let me=!1,ye=S;if(o&&Se.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(B!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ye=o.dims[2]}else{if(B!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ye=o.dims[1]*o.dims[3],me=!0}}let Be=!1;if(a&&Se.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(c&&Se.size(c.dims)>0){if(c.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(c.dims[0]!==k||c.dims[1]!==t.numHeads||c.dims[2]!==u||c.dims[3]!==V)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:u,pastSequenceLength:N,kvSequenceLength:B,totalSequenceLength:V,maxSequenceLength:L,inputHiddenSize:0,hiddenSize:S,vHiddenSize:ye,headSize:se,vHeadSize:Math.floor(ye/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:de,scale:t.scale,broadcastResPosBias:Be,passPastInKv:me,qkvFormat:ee}},Qi=e=>Qe({...e}),nd=Qe({perm:[0,2,1,3]}),bc=(e,t,s,n,o,i,a)=>{let c=[n,o,i],p=Se.size(c),h=[{type:12,data:p},{type:12,data:a},{type:12,data:i}],k=u=>{let S=gt("qkv_with_bias",t.dataType,c),B=Oe("qkv",t.dataType,c),N=Oe("bias",s.dataType,c),L=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${u.registerUniforms(L).declareVariables(B,N,S)} + ${u.mainStart()} + ${u.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:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},fn=(e,t,s,n,o,i,a,c)=>{let p=i;if(a&&Se.size(a.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=bc(e,i,a,t,n,s*o,c),p=p.reshape([t,n,s,o]),s===1||n===1?p:e.compute(nr(p,nd.perm),{inputs:[p],outputs:[-1]})[0]}else return i.dims.length===3&&(p=i.reshape([t,n,s,o])),s===1||n===1?p:e.compute(nr(p,nd.perm),{inputs:[p],outputs:[-1]})[0]},Yi=(e,t)=>{let s=rd(e.inputs,t),n=e.inputs[0],o=Hs(e.inputs,1),i=Hs(e.inputs,2),a=Hs(e.inputs,3),c=Hs(e.inputs,4),p=Hs(e.inputs,5),h=Hs(e.inputs,6),k=Hs(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let u=o&&i&&o.dims.length===4&&i.dims.length===4,S=fn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,a,0);if(u)return On(e,S,o,i,c,void 0,h,k,p,s);if(!o||!i)throw new Error("key and value must be provided");let B=fn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,o,a,s.hiddenSize),N=fn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,i,a,2*s.hiddenSize);On(e,S,B,N,c,void 0,h,k,p,s)}}),id,Ji,ad,ld,go,ud,dd,Zi=y(()=>{Ft(),zt(),It(),Gt(),id=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Ji=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>s.push(Number(o))),n=s.length),Qe({numOutputs:n,axis:t.axis,splitSizes:s})},ad=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${Mt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,ld=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=Se.size(s),o=e[0].dataType,i=Se.normalizeAxis(t.axis,s.length),a=new Array(t.numOutputs),c=Oe("input",o,s.length),p=new Array(t.numOutputs),h=[],k=[],u=0,S=[{type:12,data:n}];for(let N=0;N` + ${N.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(c,...a)} + ${ad(p.length)} + ${ld(a)} + + ${N.mainStart()} + ${N.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${c.offsetToIndices("global_idx")}; + var index = ${c.indicesGet("indices",i)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Mt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; + ${c.indicesSet("indices",i,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:S})}},ud=(e,t)=>{id(e.inputs);let s=e.inputs.length===1?t:Ji(e.inputs,t);e.compute(go(e.inputs,s),{inputs:[0]})},dd=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Qe({axis:t,numOutputs:n,splitSizes:s})}}),cd,pd,ea,hd,vc=y(()=>{It(),qo(),od(),Zi(),Fr(),cd=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?c?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],u=h,S=0,B=!n||n.dims.length===0,N=Math.floor(B?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);B&&(k=N*t.numHeads);let L=i&&i.dims.length!==0,se=a&&a.dims.length!==0;if(L&&i.dims.length===4&&i.dims[0]===p&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===N)throw new Error("BSNH pastKey/pastValue is not supported");if(L&&se){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');S=i.dims[2]}else if(L||se)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee=1;if(n&&n.dims.length>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==N)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==N)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}let V=0,de=!1,me=t.kvNumHeads?N*t.kvNumHeads:k;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=o.dims[1]*o.dims[3],de=!0}}let ye=e.length>4?e[5]:void 0;if(ye&&ye.dims.length!==1&&ye.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:S,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:me,headSize:N,vHeadSize:Math.floor(me/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:V,scale:t.scale,broadcastResPosBias:!1,passPastInKv:de,qkvFormat:ee}},pd=Qe({perm:[0,2,1,3]}),ea=(e,t,s)=>{let n=t,o=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize]),n=e.compute(nr(n,pd.perm),{inputs:[n],outputs:[-1]})[0]),n},hd=(e,t)=>{let s=cd(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=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=s.kvNumHeads?s.kvNumHeads:s.numHeads,u=Qe({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[S,B,N]=!o&&!i?e.compute(go([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],L=fn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,S,void 0,0);On(e,L,ea(e,B,s),ea(e,N,s),void 0,void 0,a,c,void 0,s,p,h)}}),ta,md,_d,fd,gd=y(()=>{Ft(),zt(),Fr(),Gt(),ta=(e,t,s,n,o,i,a,c)=>{let p=os(i),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,u=o*a,S=64;u===1&&(S=256);let B=[o,a,i/p],N=[o,a,2],L=["rank","type","type"],se=[];se.push(...xt(B,N));let ee=V=>{let de=Oe("x",t.dataType,3,p),me=Oe("scale",s.dataType,s.dims),ye=Oe("bias",n.dataType,n.dims),Be=gt("output",1,3,2),Ee=[de,me,ye,Be];return` + var workgroup_shared : array<${k}, ${S}>; + const workgroup_size = ${S}u; + ${V.declareVariables(...Ee)} + ${V.mainStart(S)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${h}(0); + var squared_sum = ${h}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${h}(${de.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${k}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Vs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); + let squared_sum_final = ${Vs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${c})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${c};${S}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:N,dataType:1}],dispatchGroup:{x:u},programUniforms:se}),getShaderSource:ee},{inputs:[t,s,n],outputs:[-1]})[0]},md=(e,t,s)=>{let n=t[0].dims,o=n,i=2,a=n[0],c=n[1],p=Se.sizeFromDimension(n,i),h=os(p),k=Se.size(o)/h,u=ta(e,t[0],t[1],t[2],a,p,c,s.epsilon),S=[a,c,p/h],B=[a,c],N=["type","none"],L=se=>{let ee=Oe("x",t[0].dataType,S.length,h),V=Oe("scale_shift",1,B.length,2),de=gt("output",t[0].dataType,S.length,h),me=[ee,V,de];return` + ${se.registerUniform("output_size","u32").declareVariables(...me)} + ${se.mainStart()} + ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${de.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${V.getByIndices("vec2(batch, channel)")}; + let value = ${ee.getByOffset("global_idx")} * ${de.type.value}(scale_shift.x) + ${de.type.value}(scale_shift.y); + ${de.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:N},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...xt(S,B,S)]}),getShaderSource:L},{inputs:[t[0],u]})},_d=(e,t,s)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],c=Se.sizeFromDimension(n,1)/a,p=os(a),h=Se.size(o)/p,k=[{type:12,data:c},{type:12,data:Math.floor(a/p)}],u=["type","type"],S=!1,B=[0,n.length-1];for(let ee=0;een[B[V]])),L=ta(e,N,t[1],t[2],i,c,a,s.epsilon),se=ee=>{let V=Zt(t[0].dataType),de=p===1?"vec2f":`mat${p}x2f`,me=Ee=>{let tt=Ee===0?"x":"y",pt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${V}(${pt}(scale.${tt}))`;case 2:return`vec2<${V}>(${pt}(scale[0].${tt}, scale[1].${tt}))`;case 4:return`vec4<${V}>(${pt}(scale[0].${tt}, scale[1].${tt}, scale[2].${tt}, scale[3].${tt}))`;default:throw new Error(`Not supported compoents ${p}`)}},ye=Oe("input",t[0].dataType,t[0].dims,p),Be=gt("output",t[0].dataType,o,p);return` + @group(0) @binding(0) var input : array<${ye.type.storage}>; + @group(0) @binding(1) var scale_input : array<${de}>; + @group(0) @binding(2) var output : array<${Be.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${ee.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${me(0)}, ${me(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:se},{inputs:[t[0],L]})},fd=(e,t)=>{t.format==="NHWC"?_d(e,e.inputs,t):md(e,e.inputs,t)}}),wd,yd,sa,Tc=y(()=>{Ft(),zt(),Gt(),wd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},yd=(e,t,s)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],c=o,p=Se.normalizeAxis(t.axis,o.length),h=Se.sizeToDimension(o,p),k=Se.sizeFromDimension(o,p),u=Se.size(i.dims),S=a?Se.size(a.dims):0;if(u!==k||a&&S!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. + Size of scale and bias (if provided) must match this. + Got scale size of ${u} and bias size of ${S}`);let B=[];for(let ye=0;ye1,V=s>2,de=ye=>{let Be=Zt(e[0].dataType),Ee=[Oe("x",e[0].dataType,e[0].dims,N),Oe("scale",i.dataType,i.dims,N)];a&&Ee.push(Oe("bias",a.dataType,a.dims,N)),Ee.push(gt("output",e[0].dataType,c,N)),ee&&Ee.push(gt("mean_data_output",1,B)),V&&Ee.push(gt("inv_std_output",1,B));let tt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${ye.registerUniforms(tt).declareVariables(...Ee)} + ${ye.mainStart()} + ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${wr("f32",N)}; + var mean_square_vector = ${wr("f32",N)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${As(Be,N,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Vs("mean_vector",N)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Vs("mean_square_vector",N)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${As(Be,N,"x[j + offset]")}; + let f32scale = ${As(Be,N,"scale[j]")}; + output[j + offset] = ${Ee[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${a?`+ ${As(Be,N,"bias[j]")}`:""} + ); + } + + ${ee?"mean_data_output[global_idx] = mean":""}; + ${V?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},me=[{dims:c,dataType:e[0].dataType}];return ee&&me.push({dims:B,dataType:1}),V&&me.push({dims:B,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${N};${s};${n}`,inputDependencies:L},getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:se}),getShaderSource:de}},sa=(e,t)=>{wd(e.inputs),e.compute(yd(e.inputs,t,e.outputCount))}}),Md,ms,Cp=y(()=>{zt(),vi(),Ci(),Md=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.")},ms=e=>{Md(e.inputs);let t=gs.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(bi(e.inputs,{activation:""},t));else{let o=t[t.length-2],i=Se.size(e.inputs[0].dims.slice(0,-2)),a=Se.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let c=e.inputs[0].reshape([1,i,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,i,s],k=[c,p];e.compute(io(k,{activation:""},t,h),{inputs:k})}else e.compute(io(e.inputs,{activation:""},t))}}}),xc,Pc,ra,bd,vd,Ec=y(()=>{Ft(),zt(),It(),Gt(),xc=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!Se.areEqual(a.dims,[t.n,o,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let c=e[2].dims;if(Se.size(c)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(Se.size(p)!==h)throw new Error("zeroPoints input size error.")}},Pc=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],i=t.k,a=t.n,c=s.slice(0,n-2),p=Se.size(c),h=e[1].dims[2]/4,k=e[0].dataType,u=os(t.k),S=os(h),B=os(a),N=c.concat([o,a]),L=o>1&&a/B%2===0?2:1,se=Se.size(N)/B/L,ee=64,V=[],de=[p,o,i/u],me=Se.convertShape(e[1].dims).slice();me.splice(-1,1,h/S),V.push(...xt(de)),V.push(...xt(me)),V.push(...xt(e[2].dims)),e.length===4&&V.push(...xt(Se.convertShape(e[3].dims)));let ye=[p,o,a/B];V.push(...xt(ye));let Be=Ee=>{let tt=de.length,pt=Oe("a",e[0].dataType,tt,u),Ct=Oe("b",12,me.length,S),Dt=Oe("scales",e[2].dataType,e[2].dims.length),$t=[pt,Ct,Dt],bt=e.length===4?Oe("zero_points",12,e[3].dims.length):void 0;bt&&$t.push(bt);let Kt=ye.length,jt=gt("output",e[0].dataType,Kt,B),Lt=Zt(e[0].dataType),ss=(()=>{switch(u){case 1:return`array<${Lt}, 8>`;case 2:return`mat4x2<${Lt}>`;case 4:return`mat2x4<${Lt}>`;default:throw new Error(`${u}-component is not supported.`)}})(),Jt=()=>{let at=` + // reuse a data + var input_offset = ${pt.indicesToOffset(`${pt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ss}; + for (var j: u32 = 0; j < ${8/u}; j++) { + a_data[j] = ${pt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let Pt=0;Pt> 4) & b_mask); + b_quantized_values = ${ss}(${Array.from({length:4},(ps,vs)=>`${Lt}(b_value_lower[${vs}]), ${Lt}(b_value_upper[${vs}])`).join(", ")}); + b_dequantized_values = ${u===1?`${ss}(${Array.from({length:8},(ps,vs)=>`(b_quantized_values[${vs}] - ${bt?`zero_point${Pt}`:"zero_point"}) * scale${Pt}`).join(", ")});`:`(b_quantized_values - ${ss}(${Array(8).fill(`${bt?`zero_point${Pt}`:"zero_point"}`).join(",")})) * scale${Pt};`}; + workgroup_shared[local_id.x * ${L} + ${Math.floor(Pt/B)}]${B>1?`[${Pt%B}]`:""} += ${Array.from({length:8/u},(ps,vs)=>`${u===1?`a_data[${vs}] * b_dequantized_values[${vs}]`:`dot(a_data[${vs}], b_dequantized_values[${vs}])`}`).join(" + ")}; + `;return at},qt=()=>{let at=` + var col_index = col * ${B}; + ${bt?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Lt}(8);`} + `;for(let Pt=0;Pt> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${bt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${Pt} = ${Lt}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return at},Qs=()=>{let at=`col_index = col * ${B};`;for(let Pt=0;Pt; + var b_value_upper: vec4; + var b_quantized_values: ${ss}; + var b_dequantized_values: ${ss};`,at};return` + var workgroup_shared: array<${jt.type.value}, ${L*ee}>; + ${Ee.declareVariables(...$t,jt)} + ${Ee.mainStart([ee,1,1])} + let output_indices = ${jt.offsetToIndices(`(global_idx / ${ee}) * ${L}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${ee}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/u}; + ${qt()} + for (var word: u32 = 0; word < ${h}; word += ${S}) { + ${Qs()} + for (var i: u32 = 0; i < ${S}; i++) { + ${Jt()} + word_offset += ${8/u}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${L}) { + var output_value: ${jt.type.value} = ${jt.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${ee}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${L}; + } + ${jt.setByIndices(`${jt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${u};${S};${B};${L};${ee}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:N,dataType:k}],dispatchGroup:{x:se},programUniforms:V}),getShaderSource:Be}},ra=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],i=t.k,a=t.n,c=s.slice(0,n-2),p=Se.size(c),h=e[1].dims[2]/4,k=e[0].dataType,u=os(t.k),S=os(h),B=c.concat([o,a]),N=128,L=a%8===0?8:a%4===0?4:1,se=N/L,ee=se*S*8,V=ee/u,de=ee/t.blockSize,me=Se.size(B)/L,ye=[],Be=[p,o,i/u],Ee=Se.convertShape(e[1].dims).slice();Ee.splice(-1,1,h/S),ye.push(...xt(Be)),ye.push(...xt(Ee)),ye.push(...xt(e[2].dims)),e.length===4&&ye.push(...xt(Se.convertShape(e[3].dims)));let tt=[p,o,a];ye.push(...xt(tt));let pt=Ct=>{let Dt=Be.length,$t=Oe("a",e[0].dataType,Dt,u),bt=Oe("b",12,Ee.length,S),Kt=Oe("scales",e[2].dataType,e[2].dims.length),jt=[$t,bt,Kt],Lt=e.length===4?Oe("zero_points",12,e[3].dims.length):void 0;Lt&&jt.push(Lt);let ss=tt.length,Jt=gt("output",e[0].dataType,ss),qt=Zt(e[0].dataType),Qs=()=>{switch(u){case 1:return` + let a_data0 = vec4<${qt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${qt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${qt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${qt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${u}-component is not supported.`)}};return` + var sub_a: array<${$t.type.value}, ${V}>; + var inter_results: array, ${L}>; + ${Ct.declareVariables(...jt,Jt)} + ${Ct.mainStart([se,L,1])} + let output_indices = ${Jt.offsetToIndices(`workgroup_index * ${L}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${de} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${V}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${V}; a_offset += ${N}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${$t.getByIndices(`${$t.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${$t.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${de} + local_id.x; + ${Lt?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${Lt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${qt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${qt}(8);`} + let scale = ${Kt.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${bt.getByIndices(`${bt.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/u}; + for (var i: u32 = 0; i < ${S}; i++) { + ${Qs()} + let b_value = ${S===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${qt}>(${Array.from({length:4},(at,Pt)=>`${qt}(b_value_lower[${Pt}]), ${qt}(b_value_upper[${Pt}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${qt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(at,Pt)=>`${`dot(a_data${Pt}, b_dequantized_values[${Pt}])`}`).join(" + ")}; + word_offset += ${8/u}; + } + workgroupBarrier(); + } + + if (local_idx < ${L}) { + var output_value: ${Jt.type.value} = ${Jt.type.value}(0); + for (var b = 0u; b < ${se}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Jt.setByIndices(`${Jt.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${u};${S};${se};${L}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:me},programUniforms:ye}),getShaderSource:pt}},bd=(e,t)=>{xc(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(ra(e.inputs,t)):e.compute(Pc(e.inputs,t))},vd=e=>Qe(e)}),Td,na,oa,Cc,xd,Pd,ia,kc,Sc,$c=y(()=>{Ft(),zt(),Gt(),Td=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].")}},na=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { + break; + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},oa=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Mt("uniforms.x_shape",o,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${Mt("uniforms.x_shape",o,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Cc=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { + k = i32(${Mt("uniforms.x_shape",o,t)}) - 1; + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},xd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,s)}; + if (k < 0) { + k += i32(${Mt("uniforms.x_shape",o,t)}]); + } + if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { + k -= i32(${Mt("uniforms.x_shape",o,t)}); + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Pd=(e,t,s)=>{switch(s.mode){case 0:return na(e,t,s.pads.length);case 1:return oa(e,t,s.pads.length);case 2:return Cc(e,t,s.pads.length);case 3:return xd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},ia=(e,t)=>{let s=Se.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=Se.size(s),i=[{type:12,data:o},{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(...xt(e[0].dims,s));let c=["rank"],p=h=>{let k=gt("output",e[0].dataType,s.length),u=Oe("x",e[0].dataType,n.length),S=u.type.value,B=Pd(k,n.length,t),N=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&N.push({name:"constant_value",type:a?S:"f32"}),` + ${h.registerUniforms(N).declareVariables(u,k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + + var value = ${S}(0); + ${B} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(s)/64)},programUniforms:i}),getShaderSource:p}},kc=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let p=0;pi[Number(p)]=Number(c));let a=[];return i.forEach(c=>a.push(c)),{mode:t.mode,value:n,pads:a}}else return t},Sc=(e,t)=>{Td(e.inputs);let s=kc(e.inputs,t);e.compute(ia(e.inputs,s),{inputs:[0]})}}),Bn,aa,la,ua,da,Ed,Cd,ca,pa,kd,Sd,$d,Ad,Id,ha,Od,Fd,Dd,Ac,kp=y(()=>{He(),Ft(),zt(),Gt(),Bn=e=>{if(x.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},aa=(e,t,s)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),c=t.strides.slice(),p=i?t.dilations.slice():[],h=t.pads.slice();Ps.adjustPoolAttributes(s,o,a,c,p,h);let k=Ps.computePoolOutputShape(s,o,c,p,a,h,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:c,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:c,pads:h,cacheKey:t.cacheKey});let S=k.slice();return S.push(S.splice(1,1)[0]),[u,n?S:k]},la=(e,t)=>{let s=t.format==="NHWC",n=Se.size(e),o=Se.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],u=!!(h+k);i.push({type:12,data:c},{type:12,data:p},{type:12,data:h},{type:12,data:k}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let S=!1;if(t.kernelShape.length===2){let B=t.kernelShape[t.kernelShape.length-2],N=t.strides[t.strides.length-2],L=t.pads[t.pads.length/2-2],se=t.pads[t.pads.length-2];S=!!(L+se),i.push({type:12,data:B},{type:12,data:N},{type:12,data:L},{type:12,data:se}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,u,S]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=Se.computeStrides(t.kernelShape);i.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[i,a,!!p,!1,!1]}},ua=(e,t,s,n,o,i,a,c,p,h,k,u)=>{let S=o.format==="NHWC",B=t.type.value,N=gt("output",t.type.tensor,n);if(o.kernelShape.length<=2){let L="",se="",ee="",V=s-(S?2:1);if(k?L=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${V}] = indices[${V}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${V}] < 0 || xIndices[${V}] + >= uniforms.x_shape[${V}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + }`:L=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${V}] = indices[${V}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + }`,o.kernelShape.length===2){let de=s-(S?3:2);u?se=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${de}] = indices[${de}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${de}] < 0 || xIndices[${de}] >= uniforms.x_shape[${de}]) { + pad += i32(uniforms.kw); + continue; + } + `:se=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${de}] = indices[${de}] * uniforms.sh - uniforms.phStart + j; + `,ee=` + } + `}return` + ${e.registerUniforms(p).declareVariables(t,N)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${N.offsetToIndices("global_idx")}; + var xIndices = ${N.offsetToIndices("global_idx")}; + + var value = ${B}(${c}); + var pad = 0; + ${se} + ${L} + ${ee} + ${a} + + output[global_idx] = value; + }`}else{if(S)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let L=o.kernelShape.length,se=o.pads.length,ee="";return h?ee=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + }`:ee=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + `,` + ${e.registerUniforms(p).declareVariables(t,N)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${N.offsetToIndices("global_idx")}; + var xIndices = ${N.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${B}(${c}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${L-1}u; j++) { + offsets[j] = offset / ${Mt("uniforms.kernelStrides","j",L)}; + offset -= offsets[j] * ${Mt("uniforms.kernelStrides","j",L)}; + } + offsets[${L-1}] = offset; + + isPad = false; + for (var j = ${s-L}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Mt("uniforms.strides",`j - ${s-L}u`,L)} + + offsets[j - ${s-L}u] - ${Mt("uniforms.pads","j - 2u",se)}; + ${ee} + } + ${a} + + output[global_idx] = value; + }`}},da=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Ed=e=>`${da(e)};${e.countIncludePad}`,Cd=e=>`${da(e)};${e.storageOrder};${e.dilations}`,ca=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}),pa=(e,t,s,n)=>{let[o,i]=aa(t,n,s),a=Oe("x",t.dataType,t.dims.length),c=a.type.value,p="value += x_val;",h="";o.countIncludePad?h+=`value /= ${c}(uniforms.kernelSize);`:h+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[k,u,S,B,N]=la(i,o);k.push(...xt(t.dims,i));let L=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${S};${B};${N}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(i)/64)},programUniforms:k}),getShaderSource:se=>ua(se,a,t.dims.length,i.length,o,p,h,0,u,S,B,N)}},kd=e=>{let t=e.count_include_pad!==0,s=ca(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:Ed(n)}},Sd=(e,t)=>{Bn(e.inputs),e.compute(pa("AveragePool",e.inputs[0],!1,t))},$d={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Ad=e=>{let t=e.format;return{format:t,...$d,cacheKey:t}},Id=(e,t)=>{Bn(e.inputs),e.compute(pa("GlobalAveragePool",e.inputs[0],!0,t))},ha=(e,t,s,n)=>{let[o,i]=aa(t,n,s),a=` + value = max(x_val, value); + `,c="",p=Oe("x",t.dataType,t.dims.length),h=["rank"],[k,u,S,B,N]=la(i,o);return k.push(...xt(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${S};${B};${N}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(i)/64)},programUniforms:k}),getShaderSource:L=>ua(L,p,t.dims.length,i.length,o,a,c,t.dataType===10?-65504:-1e5,u,S,B,N)}},Od=(e,t)=>{Bn(e.inputs),e.compute(ha("MaxPool",e.inputs[0],!1,t))},Fd=e=>{let t=e.storage_order,s=e.dilations,n=ca(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:s,...n,cacheKey:""};return{...o,cacheKey:Cd(o)}},Dd=e=>{let t=e.format;return{format:t,...$d,cacheKey:t}},Ac=(e,t)=>{Bn(e.inputs),e.compute(ha("GlobalMaxPool",e.inputs[0],!0,t))}}),Ic,Oc,Fc,Dc,Sp=y(()=>{Ft(),zt(),It(),Gt(),Ic=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&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 s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Oc=(e,t)=>{let s=Se.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,c=Se.size(i),p=n===3||n===2,h=p?[Math.ceil(Se.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,u=e.length>2?e[2]:void 0,S=u?p?[Math.ceil(Se.size(u.dims)/4)]:u.dims:void 0,B=k.length===0||k.length===1&&k[0]===1,N=B===!1&&k.length===1,L=os(c),se=B&&(!p||L===4),ee=se?L:1,V=se&&!p?L:1,de=Oe("input",p?12:n,h.length,V),me=Oe("scale",a,k.length),ye=u?Oe("zero_point",p?12:n,S.length):void 0,Be=gt("output",a,i.length,ee),Ee=[de,me];ye&&Ee.push(ye);let tt=[h,k];u&&tt.push(S);let pt=[{type:12,data:c/ee},{type:12,data:s},{type:12,data:t.blockSize},...xt(...tt,i)],Ct=Dt=>{let $t=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${Dt.registerUniforms($t).declareVariables(...Ee,Be)} + ${Dt.mainStart()} + ${Dt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Be.offsetToIndices("global_idx")}; + + // Set input x + ${p?` + let input = ${de.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${ee===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${de.getByOffset("global_idx")};`}; + + // Set scale input + ${B?`let scale_value= ${me.getByOffset("0")}`:N?` + let scale_index = ${Be.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${me.getByOffset("scale_index")};`:` + var scale_indices: ${me.type.indices} = output_indices; + let index = ${me.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${me.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${me.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${ye?B?p?` + let zero_point_input = ${ye.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ye.getByOffset("0")}`:N?p?` + let zero_point_index = ${Be.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${ye.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Be.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${ye.getByOffset("zero_point_index")};`:p?` + let zero_point_offset = ${me.indicesToOffset("scale_indices")}; + let zero_point_input = ${ye.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ye.getByIndices("scale_indices")};`:`let zero_point_value = ${p?o?"i32":"u32":de.type.value}(0);`}; + // Compute and write output + ${Be.setByOffset("global_idx",`${Be.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:ye?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Ct,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(c/ee/64),y:1,z:1},programUniforms:pt})}},Fc=(e,t)=>{Ic(e.inputs,t),e.compute(Oc(e.inputs,t))},Dc=e=>Qe({axis:e.axis,blockSize:e.blockSize})}),Lc,zc,Bc,$p=y(()=>{He(),Ft(),Gt(),Lc=(e,t,s)=>{let n=e===t,o=et&&s>0;if(n||o||i)throw new Error("Range these inputs' contents are invalid.")},zc=(e,t,s,n)=>{let o=Math.abs(Math.ceil((t-e)/s)),i=[o],a=o,c=[{type:12,data:a},{type:n,data:e},{type:n,data:s},...xt(i)],p=h=>{let k=gt("output",n,i.length),u=k.type.value,S=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` + ${h.registerUniforms(S).declareVariables(k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c})}},Bc=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),x.webgpu.validateInputContent&&Lc(t,s,n),e.compute(zc(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Rc,Nc,jc,Uc,Ap=y(()=>{Ft(),zt(),It(),Gt(),Rc=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,i=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` + ${o}bitcast<${n}>(oldValue) + (${s})${i}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` + ${o}max(bitcast(oldValue), (${s}))${i}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${o}min(bitcast<${n}>(oldValue), (${s}))${i}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${s}))${i}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Nc=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s,i=1,a=Math.ceil(Se.size(n)/i),c=n[n.length-1],p=Se.sizeFromDimension(s,c),h=[{type:12,data:a},{type:12,data:c},{type:12,data:p},...xt(e[1].dims,e[2].dims,o)],k=u=>{let S=Oe("indices",e[1].dataType,e[1].dims.length),B=Oe("updates",e[2].dataType,e[2].dims.length,i),N=t.reduction!=="none"&&t.reduction!==""?tr("output",e[0].dataType,o.length):gt("output",e[0].dataType,o.length,i);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(S,B,N)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var data_offset = 0u; + let indices_start = uniforms.last_index_dimension * global_idx; + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${Rc(t.reduction,"output[data_offset + i]","value",N.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:k}},jc=e=>Qe({reduction:e.reduction}),Uc=(e,t)=>{e.compute(Nc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Vc,Wc,Gc,Kc,Hc,qc,Xc,Qc,Yc,Jc,Zc,Ld,ep,tp,sp,Ht,zd,Ns,Us,qs=y(()=>{Ft(),zt(),It(),Gt(),Vc=(e,t)=>{if(e.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Wc=(e,t,s)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Gc=(e,t,s,n,o,i)=>{let[a,c,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(k=>i.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&s>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Vc(n,t),t.axes.length>0&&Wc(n,t.axes,h).forEach((k,u)=>n[u]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>o.push(Number(k))),o.length!==0&&o.length!==h&&s>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Kc=(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`)}})()+"}",Hc=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",qc=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+s]=o[t.length+a]}),n):o},Xc=(e,t,s,n)=>{let o=[];if(s.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((i,a)=>o[i]=s[a])}else s.forEach(i=>o.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Qc=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return s.axes.length>0?(s.axes.forEach(i=>t[i]=n),s.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},Yc=(e,t,s,n,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { + var original_indices: array<${e.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${Mt("uniforms.scales","i",n)}; + var roi_low = ${Mt("uniforms.roi","i",o)}; + var roi_hi = ${Mt("uniforms.roi",`i + ${t.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${Mt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Mt("uniforms.output_shape","i",s.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Jc=(e,t,s,n,o,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 = ${Mt("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Mt("uniforms.roi","i",i)}; + var roi_hi = ${Mt("uniforms.roi",`i + ${s.length}`,i)}; + var input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Mt("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${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; + }`,Zc=(e,t)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${Mt("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Ld=(e,t,s,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",s,"batch")}; +`:"",ep=(e,t,s,n,o)=>{let[i,a,c,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",a,`max(0, min(row, ${s[a]} - 1))`)}; + ${e.indicesSet("input_indices",c,`max(0, min(col, ${s[c]} - 1))`)}; + ${Ld(e,p,i,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${h} = originalIndices[${a}]; + var col:${h} = originalIndices[${c}]; + ${n?`if (row < 0 || row > (${s[a]} - 1) || col < 0 || col > (${s[c]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${s[a]} - 1)); + col = max(0, min(col, ${s[c]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${i}])`:"0"}; + var x11: ${h} = getInputValue(batch, channel, row1, col1); + var x12: ${h} = getInputValue(batch, channel, row1, col2); + var x21: ${h} = getInputValue(batch, channel, row2, col1); + var x22: ${h} = getInputValue(batch, channel, row2, col2); + var dx1: ${h} = abs(row - ${h}(row1)); + var dx2: ${h} = abs(${h}(row2) - row); + var dy1: ${h} = abs(col - ${h}(col1)); + var dy2: ${h} = abs(${h}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},tp=(e,t,s,n,o,i,a,c,p,h)=>{let k=s.length===2,[u,S]=k?[0,1]:[2,3],B=e.type.value,N=L=>{let se=L===u?"row":"col";return` + fn ${se}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { + var output_index = ${t.indicesGet("output_indices",L)}; + var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[L]}, + ${n[L]}, ${s[L]}, ${i[L]}, ${i[L]} + ${s.length}); + var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${c} && (originalIdx < 0 || originalIdx > (${s[L]} - 1))) { + return ${p}; + } + var data: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${se}: ${B} = originalIdx + ${B}(i); + if (${se} < 0 || ${se} >= ${s[L]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:c?`return ${p};`:`${se} = max(0, min(${se}, ${s[L]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",L,`u32(${se})`)}; + data[i + 1] = ${L===u?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${N(u)}; + ${N(S)}; + fn getCubicInterpolationCoefs(s: ${B}) -> array<${B}, 4> { + var absS = abs(s); + var coeffs: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${B} = 1.0 - absS; + var twoMinusAbsS: ${B} = 2.0 - absS; + var onePlusAbsS: ${B} = 1.0 + absS; + coeffs[0] = ((${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<${B}, 4>, coefs: array<${B}, 4>) -> ${B} { + var coefsSum: ${B} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${B} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},sp=(e,t,s,n,o)=>{let[i,a,c,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",a,`max(0, min(depth, ${s[a]} - 1))`)}; + ${e.indicesSet("input_indices",c,`max(0, min(height, ${s[c]} - 1))`)}; + ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; + ${Ld(e,h,i,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${k} = originalIndices[${a}]; + var height:${k} = originalIndices[${c}]; + var width:${k} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${s[a]} - 1) || height < 0 || height > (${s[c]} - 1) || width < 0 || (width > ${s[p]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${s[a]} - 1)); + height = max(0, min(height, ${s[c]} - 1)); + width = max(0, min(width, ${s[p]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${i}])`:"0"}; + + var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${k} = abs(depth - ${k}(depth1)); + var dx2: ${k} = abs(${k}(depth2) - depth); + var dy1: ${k} = abs(height - ${k}(height1)); + var dy2: ${k} = abs(${k}(height2) - height); + var dz1: ${k} = abs(width - ${k}(width1)); + var dz2: ${k} = abs(${k}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},Ht=(e,t,s,n,o,i)=>{let a=e.dims,c=qc(i,t.axes,a.length),p=Xc(a,n,o,t.axes),h=n.slice();n.length===0&&(h=a.map((V,de)=>V===0?1:p[de]/V),t.keepAspectRatioPolicy!=="stretch"&&(p=Qc(a,h,t)));let k=gt("output",e.dataType,p.length),u=Oe("input",e.dataType,a.length),S=Se.size(p),B=a.length===p.length&&a.every((V,de)=>V===p[de]),N=t.coordinateTransformMode==="tf_crop_and_resize",L=t.extrapolationValue,se=u.type.value,ee=V=>` + ${B?"":` + ${Kc(t.coordinateTransformMode,se)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${Zc(u,a)}; + ${Hc(t.nearestMode,s,se)}; + ${Jc(u,k,a,p,h.length,c.length,N)}; + `;case"linear":return` + ${Yc(k,a,p,h.length,c.length)}; + ${(()=>{if(a.length===2||a.length===4)return`${ep(u,k,a,N,L)}`;if(a.length===3||a.length===5)return`${sp(u,k,a,N,L)}`;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`${tp(u,k,a,p,h,c,t.cubicCoeffA,N,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")}})()}; + `} + ${V.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",c.length).declareVariables(u,k)} + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${B?"output[global_idx] = input[global_idx];":` + let output_indices = ${k.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${u.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}|${s}|${h.length>0?h:""}|${o.length>0?o:""}|${c.length>0?c:""}|${B}|${a}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},{type:1,data:h},{type:1,data:c},...xt(a,p)]})}},zd=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Ns=(e,t)=>{let s=[],n=[],o=[],i=zd(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Gc(e.inputs,t,i,s,n,o),e.compute(Ht(e.inputs[0],t,i,s,n,o),{inputs:[0]})},Us=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,c=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return Qe({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:c,mode:p,nearestMode:h})}}),en,rp,Bd,np=y(()=>{Ft(),zt(),It(),Gt(),en=(e,t)=>{let[s,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:c}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!Se.areEqual(n.dims,[])&&!Se.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!Se.areEqual(o.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(c>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=s.dims[0],h=s.dims[s.dims.length-2],k=o.dims[0],u=Se.sizeFromDimension(s.dims,1)/h,S=c===0?o.dims[1]*2:u/a;if(c>S)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(S/2!==o.dims[1]&&c/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},rp=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],c=Se.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=c/p,k=e[2].dims[1],u=o===0?k*2:h/n,S=new Array(a,p,h/u,u-k),B=Se.computeStrides(S),N=[{type:1,data:i},{type:12,data:S},{type:12,data:B},...e[0].dims.length===3?new Array({type:12,data:[c,h,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,u,p*u,1]}):[],...xt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],L=se=>{let ee=Oe("input",e[0].dataType,e[0].dims.length),V=Oe("position_ids",e[1].dataType,e[1].dims.length),de=Oe("cos_cache",e[2].dataType,e[2].dims.length),me=Oe("sin_cache",e[3].dataType,e[3].dims.length),ye=gt("output",e[0].dataType,e[0].dims.length);return se.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:S.length},{name:"global_strides",type:"u32",length:B.length},{name:"input_output_strides",type:"u32",length:B.length}]),` + ${se.declareVariables(ee,V,de,me,ye)} + + ${se.mainStart(zs)} + let half_rotary_emb_dim = uniforms.${de.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${se.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${V.broadcastedIndicesToOffset("bsnh.xy",gt("",V.type.tensor,2))}; + let position_id = + u32(${V.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); + let j = i + select(half_rotary_emb_dim, 1, ${s}); + let re = ${ee.getByOffset("i")} * ${de.get("position_id","bsnh[3]")} - + ${ee.getByOffset("j")} * ${me.get("position_id","bsnh[3]")}; + ${ye.setByOffset("i","re")} + let im = ${ee.getByOffset("i")} * ${me.get("position_id","bsnh[3]")} + + ${ee.getByOffset("j")} * ${de.get("position_id","bsnh[3]")}; + ${ye.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${ye.setByOffset("k",ee.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Qe({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(S)/zs)},programUniforms:N})}},Bd=(e,t)=>{en(e.inputs,t),e.compute(rp(e.inputs,t))}}),f,_,Y,xe=y(()=>{Ft(),zt(),Gt(),f=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==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]!==o)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]!==o)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]!==o)throw new Error("Bias must have the same hidden size as input")}},_=(e,t,s,n)=>{let o=t.simplified,i=e[0].dims,a=Se.size(i),c=i,p=a,h=i.slice(-1)[0],k=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,S=e.length>4,B=n&&s>1,N=n&&s>2,L=s>3,se=64,ee=os(h),V=[{type:12,data:p},{type:12,data:ee},{type:12,data:h},{type:1,data:t.epsilon}],de=ye=>{let Be=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ee=[Oe("x",e[0].dataType,e[0].dims,ee),Oe("skip",e[1].dataType,e[1].dims,ee),Oe("gamma",e[2].dataType,e[2].dims,ee)];u&&Ee.push(Oe("beta",e[3].dataType,e[3].dims,ee)),S&&Ee.push(Oe("bias",e[4].dataType,e[4].dims,ee)),Ee.push(gt("output",e[0].dataType,c,ee)),B&&Ee.push(gt("mean_output",1,k)),N&&Ee.push(gt("inv_std_output",1,k)),L&&Ee.push(gt("input_skip_bias_sum",e[0].dataType,c,ee));let tt=Zt(e[0].dataType),pt=Zt(1,ee);return` + + ${ye.registerUniforms(Be).declareVariables(...Ee)} + var sum_shared : array<${pt}, ${se}>; + var sum_squared_shared : array<${pt}, ${se}>; + + ${ye.mainStart([se,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${se}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${se}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${se-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${S?"bias[offset1d + i]":tt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${L?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${As(tt,ee,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${se}; + 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 = ${Vs("sum",ee)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Vs("square_sum",ee)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${B?"mean_output[global_idx] = mean;":""} + ${N?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${tt}(mean)`}) * + ${tt}(inv_std_dev) * gamma[offset1d + i] + ${u?"+ beta[offset1d + i]":""}; + } + }`},me=[{dims:c,dataType:e[0].dataType}];return s>1&&me.push({dims:k,dataType:1}),s>2&&me.push({dims:k,dataType:1}),s>3&&me.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${ee};${B};${N};${L}`,inputDependencies:e.map((ye,Be)=>"type")},getShaderSource:de,getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:V})}},Y=(e,t)=>{f(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(_(e.inputs,t,e.outputCount,!1),{outputs:s})}}),ke,Fe,st,rt,ct,kt,Yt,Ut,Bt=y(()=>{Ft(),zt(),It(),Gt(),ke=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((s,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Fe=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},st=(e,t)=>{if(e.length>1){let s=Fe(e,1),n=Fe(e,2),o=Fe(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Qe({starts:s,ends:n,axes:o})}else return t},rt=(e,t,s,n,o)=>{let i=e;return e<0&&(i+=s[n[t]]),o[t]<0?Math.max(0,Math.min(i,s[n[t]]-1)):Math.max(0,Math.min(i,s[n[t]]))},ct=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${Mt("uniforms.input_shape","i",s.length)}; + let steps_i = ${Mt("uniforms.steps","i",s.length)}; + let signs_i = ${Mt("uniforms.signs","i",s.length)}; + let starts_i = ${Mt("uniforms.starts","i",s.length)}; + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,kt=(e,t)=>{let s=e[0].dims,n=Se.size(s),o=t.axes.length>0?Se.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],i=Fe(e,4);i.forEach(ee=>ee!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map((ee,V)=>rt(ee,V,s,o,i)),c=t.ends.map((ee,V)=>rt(ee,V,s,o,i));if(o.length!==a.length||o.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==s.length)for(let ee=0;eeMath.sign(ee));i.forEach((ee,V,de)=>{if(ee<0){let me=(c[V]-a[V])/ee,ye=a[V],Be=ye+me*i[V];a[V]=Be,c[V]=ye,de[V]=-ee}});let h=s.slice(0);o.forEach((ee,V)=>{h[ee]=Math.ceil((c[ee]-a[ee])/i[ee])});let k={dims:h,dataType:e[0].dataType},u=gt("output",e[0].dataType,h.length),S=Oe("input",e[0].dataType,e[0].dims.length),B=Se.size(h),N=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:i.length}],L=[{type:12,data:B},{type:12,data:a},{type:6,data:p},{type:12,data:i},...xt(e[0].dims,h)],se=ee=>` + ${ee.registerUniforms(N).declareVariables(S,u)} + ${ct(S,u,s)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${u.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${u.setByOffset("global_idx",S.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:se,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:L})}},Yt=(e,t)=>{ke(e.inputs,t);let s=st(e.inputs,t);e.compute(kt(e.inputs,s),{inputs:[0]})},Ut=e=>{let t=e.starts,s=e.ends,n=e.axes;return Qe({starts:t,ends:s,axes:n})}}),At,bs,Vt,Wt,_s=y(()=>{Ft(),zt(),It(),Fr(),Gt(),At=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},bs=(e,t)=>{let s=e.inputs[0],n=s.dims,o=Se.size(n),i=n.length,a=Se.normalizeAxis(t.axis,i),c=att),h[a]=i-1,h[i-1]=a,p=e.compute(nr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,u=k[i-1],S=o/u,B=os(u),N=u/B,L=64;S===1&&(L=256);let se=(Ee,tt)=>tt===4?`max(max(${Ee}.x, ${Ee}.y), max(${Ee}.z, ${Ee}.w))`:tt===2?`max(${Ee}.x, ${Ee}.y)`:tt===3?`max(max(${Ee}.x, ${Ee}.y), ${Ee}.z)`:Ee,ee=Oe("x",p.dataType,p.dims,B),V=gt("result",p.dataType,p.dims,B),de=ee.type.value,me=Zt(p.dataType)==="f32"?`var threadMax = ${de}(-3.402823e+38f);`:`var threadMax = ${de}(-65504.0h);`,ye=Ee=>` + var rowMaxShared : ${de}; + var rowSumShared : ${de}; + var threadShared : array<${de}, ${L}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${de} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${de}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Ee.registerUniform("packedCols","i32").declareVariables(ee,V)} + ${Ee.mainStart(L)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${L}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${me} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${de}(${se("threadShared[0]",B)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${de}(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 = ${de}(${Vs("threadShared[0]",B)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,Be=e.compute({name:"Softmax",shaderCache:{hint:`${B};${L}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:S},programUniforms:[{type:6,data:N}]}),getShaderSource:ye},{inputs:[p],outputs:[c?-1:0]})[0];c&&e.compute(nr(Be,h),{inputs:[Be]})},Vt=(e,t)=>{At(e.inputs),bs(e,t)},Wt=e=>Qe({axis:e.axis})}),ws,es,Is,Os,ks,Bs=y(()=>{Ft(),zt(),Gt(),ws=e=>Array.from(e.getBigInt64Array(),Number),es=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(ws(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")},Is=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??ws(e[1]),o=Is(s,n),i=Se.size(o),a=e[0].dataType,c=Oe("input",a,s.length),p=gt("output",a,o.length),h=k=>` + const inputShape = ${c.indices(...s)}; + ${k.registerUniform("output_size","u32").declareVariables(c,p)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${c.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${c.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; + + ${c.indicesSet("input_indices","i","input_dim_value")} + } + ${p.setByOffset("global_idx",c.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...xt(e[0].dims,o)]}),getShaderSource:h}},ks=e=>{es(e.inputs),e.compute(Os(e.inputs),{inputs:[0]})}}),Xs,ar,ma,lr=y(()=>{Ft(),zt(),Gt(),Xs=(e,t,s,n,o)=>{let i=gt("output_data",o,s.length,4),a=Oe("a_data",t[1].dataType,t[1].dims.length,4),c=Oe("b_data",t[2].dataType,t[2].dims.length,4),p=Oe("c_data",t[0].dataType,t[0].dims.length,4),h,k=(u,S,B)=>`select(${S}, ${u}, ${B})`;if(!n)h=i.setByOffset("global_idx",k(a.getByOffset("global_idx"),c.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let u=(S,B,N="")=>{let L=`a_data[index_a${B}][component_a${B}]`,se=`b_data[index_b${B}][component_b${B}]`,ee=`bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`;return` + let output_indices${B} = ${i.offsetToIndices(`global_idx * 4u + ${B}u`)}; + let offset_a${B} = ${a.broadcastedIndicesToOffset(`output_indices${B}`,i)}; + let offset_b${B} = ${c.broadcastedIndicesToOffset(`output_indices${B}`,i)}; + let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`,i)}; + let index_a${B} = offset_a${B} / 4u; + let index_b${B} = offset_b${B} / 4u; + let index_c${B} = offset_c${B} / 4u; + let component_a${B} = offset_a${B} % 4u; + let component_b${B} = offset_b${B} % 4u; + let component_c${B} = offset_c${B} % 4u; + ${S}[${B}] = ${N}(${k(L,se,ee)}); + `};o===9?h=` + var data = vec4(0); + ${u("data",0,"u32")} + ${u("data",1,"u32")} + ${u("data",2,"u32")} + ${u("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` + ${u("output_data[global_idx]",0)} + ${u("output_data[global_idx]",1)} + ${u("output_data[global_idx]",2)} + ${u("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(p,a,c,i)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},ar=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(Se.areEqual(t,s)&&Se.areEqual(s,n)),a=t,c=Se.size(t);if(i){let h=gs.calcShape(gs.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");a=h,c=Se.size(a)}let p=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Xs(h,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:p},...xt(n,t,s,a)]})}},ma=e=>{e.compute(ar(e.inputs))}}),xr,wo=y(()=>{ec(),qo(),tc(),sc(),rc(),nc(),su(),lc(),dc(),cc(),pc(),ho(),hc(),Ep(),mc(),_c(),gc(),wc(),yc(),sd(),vc(),gd(),Tc(),Cp(),Ec(),od(),$c(),kp(),Sp(),$p(),Ap(),eo(),qs(),np(),xe(),Bt(),_s(),Zi(),Bs(),Fr(),pi(),lr(),xr=new Map([["Abs",[ml]],["Acos",[Zo]],["Acosh",[_l]],["Add",[Gl]],["ArgMax",[Vo,Wo]],["ArgMin",[il,Wo]],["Asin",[fl]],["Asinh",[ei]],["Atan",[gl]],["Atanh",[wl]],["Attention",[ul]],["AveragePool",[Sd,kd]],["BatchNormalization",[Qo]],["BiasAdd",[hl]],["BiasSplitGelu",[Ul]],["Cast",[yl,ti]],["Ceil",[vl]],["Clip",[bl]],["Concat",[eu,tu]],["Conv",[Li,Oi]],["ConvTranspose",[yu,Ni]],["Cos",[si]],["Cosh",[Tl]],["CumSum",[Ui,bu]],["DepthToSpace",[zr,xu]],["DequantizeLinear",[Fc,Dc]],["Div",[Kl]],["Einsum",[$u,Au]],["Elu",[ri,Fn]],["Equal",[mi]],["Erf",[xl]],["Exp",[ni]],["Expand",[mo]],["FastGelu",[Lu]],["Floor",[Pl]],["FusedConv",[Li,Oi]],["Gather",[_n,Ru]],["GatherElements",[Hu,Gi]],["GatherBlockQuantized",[Vu,Wu]],["GatherND",[ju,Uu]],["Gelu",[El]],["Gemm",[Hi,Xu]],["GlobalAveragePool",[Id,Ad]],["GlobalMaxPool",[Ac,Dd]],["Greater",[Xl]],["GreaterOrEqual",[fi]],["GridSample",[ed,td]],["GroupQueryAttention",[hd]],["HardSigmoid",[Al,ai]],["InstanceNormalization",[fd]],["LayerNormalization",[sa]],["LeakyRelu",[oi,Fn]],["Less",[Ql]],["LessOrEqual",[Yl]],["Log",[Bl]],["MatMul",[ms]],["MatMulNBits",[bd,vd]],["MaxPool",[Od,Fd]],["Mul",[Hl]],["MultiHeadAttention",[Yi,Qi]],["Neg",[kl]],["Not",[Cl]],["Pad",[Sc]],["Pow",[ql]],["QuickGelu",[Nl,Fn]],["Range",[Bc]],["Reciprocal",[ii]],["ReduceMin",[sl]],["ReduceMean",[Za]],["ReduceMax",[No]],["ReduceSum",[jo]],["ReduceProd",[rl]],["ReduceL1",[Ro]],["ReduceL2",[el]],["ReduceLogSum",[ol]],["ReduceLogSumExp",[tl]],["ReduceSumSquare",[nl]],["Relu",[Sl]],["Resize",[Ns,Us]],["RotaryEmbedding",[Bd]],["ScatterND",[Uc,jc]],["Sigmoid",[$l]],["Sin",[Il]],["Sinh",[li]],["Slice",[Yt,Ut]],["SkipLayerNormalization",[Y]],["Split",[ud,dd]],["Sqrt",[Ol]],["Softmax",[Vt,Wt]],["Sub",[_i]],["Tan",[Fl]],["Tanh",[Dl]],["ThresholdedRelu",[zl,Fn]],["Tile",[ks]],["Transpose",[Ia,Ao]],["Where",[ma]]])}),_a,fa=y(()=>{He(),er(),Gt(),_a=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,n,o){We(e.programInfo.name);let i=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let h of t)c.push({binding:c.length,resource:{buffer:h.buffer}});for(let h of s)c.push({binding:c.length,resource:{buffer:h.buffer}});o&&c.push({binding:c.length,resource:o});let p=i.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}a.setPipeline(e.computePipeline),a.setBindGroup(0,p),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(),ze(e.programInfo.name)}dispose(){}build(e,t){We(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let o=ka(t,this.backend.device.limits),i=e.getShaderSource(o),a=`${n.join(` +`)} +${o.additionalImplementations} +${i}`,c=s.createShaderModule({code:a,label:e.name});ns("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let p=s.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return ze(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&n<=o)return[t,s,n];let i=t*s*n,a=Math.ceil(Math.sqrt(i));if(a>o){if(a=Math.ceil(Math.cbrt(i)),a>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),Rn,op,ys,Fs,Br,gn=y(()=>{He(),Ft(),er(),An(),ft(),wo(),fa(),Rn=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${Rn(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},ys=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Fs=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;!this.subgroupsSupported||!t.minSubgroupSize||!t.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]}},Br=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let s=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},o=i=>t.features.has(i)&&s.push(i)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups")&&o("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new Fs(this.device),this.adapterInfo=new ys(t.info||await t.requestAdapterInfo()),this.gpuDataManager=_t(this),this.programManager=new _a(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,pn(e.logLevel,!!e.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.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;We(),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()),s=this.pendingQueries.get(e);for(let n=0;n"u"&&(this.queryTimeBase=S);let N=Number(S-this.queryTimeBase),L=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(N)||!Number.isSafeInteger(L))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:k.map(se=>({dims:se.dims,dataType:fr(se.dataType)})),outputsMetadata:u.map(se=>({dims:se.dims,dataType:fr(se.dataType)})),kernelId:i,kernelType:c,kernelName:p,programName:h,startTime:N,endTime:L});else{let se="";k.forEach((V,de)=>{se+=`input[${de}]: [${V.dims}] | ${fr(V.dataType)}, `});let ee="";u.forEach((V,de)=>{ee+=`output[${de}]: [${V.dims}] | ${fr(V.dataType)}, `}),console.log(`[profiling] kernel "${i}|${c}|${p}|${h}" ${se}${ee}execution time: ${L-N} ns`)}je("GPU",`${h}::${S}::${B}`)}e.unmap(),this.pendingQueries.delete(e)}),ze()}run(e,t,s,n,o,i){We(e.name);let a=[];for(let V=0;Vde):s;if(k.length!==c.length)throw new Error(`Output size ${k.length} must be equal to ${c.length}.`);let u=[],S=[];for(let V=0;V=i)throw new Error(`Invalid output index: ${k[V]}`);if(k[V]===-3)continue;let de=k[V]===-1,me=k[V]===-2,ye=de||me?o(c[V].dataType,c[V].dims):n(k[V],c[V].dataType,c[V].dims);if(u.push(ye),ye.data===0)continue;let Be=this.gpuDataManager.get(ye.data);if(!Be)throw new Error(`no GPU data for output: ${ye.data}`);if(de&&this.temporaryData.push(Be),me){let Ee=this.kernelPersistentData.get(this.currentKernelId);Ee||(Ee=[],this.kernelPersistentData.set(this.currentKernelId,Ee)),Ee.push(Be)}S.push(Be)}if(a.length!==t.length||S.length!==u.length){if(S.length===0)return ze(e.name),u;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let B;if(h){let V=0,de=[];h.forEach(Ee=>{let tt=typeof Ee.data=="number"?[Ee.data]:Ee.data;if(tt.length===0)return;let pt=Ee.type===10?2:4,Ct,Dt;Ee.type===10?(Dt=tt.length>4?16:tt.length>2?8:tt.length*pt,Ct=tt.length>4?16:pt*tt.length):(Dt=tt.length<=2?tt.length*pt:16,Ct=16),V=Math.ceil(V/Dt)*Dt,de.push(V);let $t=Ee.type===10?8:4;V+=tt.length>4?Math.ceil(tt.length/$t)*Ct:tt.length*pt});let me=16;V=Math.ceil(V/me)*me;let ye=new ArrayBuffer(V);h.forEach((Ee,tt)=>{let pt=de[tt],Ct=typeof Ee.data=="number"?[Ee.data]:Ee.data;if(Ee.type===6)new Int32Array(ye,pt,Ct.length).set(Ct);else if(Ee.type===12)new Uint32Array(ye,pt,Ct.length).set(Ct);else if(Ee.type===10)new Uint16Array(ye,pt,Ct.length).set(Ct);else if(Ee.type===1)new Float32Array(ye,pt,Ct.length).set(Ct);else throw new Error(`Unsupported uniform type: ${fr(Ee.type)}`)});let Be=this.gpuDataManager.create(V,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Be.buffer,0,ye,0,V),this.gpuDataManager.release(Be.id),B={offset:0,size:V,buffer:Be.buffer}}let N=this.programManager.normalizeDispatchGroupSize(p),L=N[1]===1&&N[2]===1,se=op(e,t,L),ee=this.programManager.getArtifact(se);if(ee||(ee=this.programManager.build(e,N),this.programManager.setArtifact(se,ee),ns("info",()=>`[artifact] key: ${se}, programName: ${e.name}`)),h&&ee.uniformVariablesInfo){if(h.length!==ee.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${ee.uniformVariablesInfo.length}, got ${h.length} in program "${ee.programInfo.name}".`);for(let V=0;V`[ProgramManager] run "${e.name}" (key=${se}) with ${N[0]}x${N[1]}x${N[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let V={kernelId:this.currentKernelId,programName:ee.programInfo.name,inputTensorViews:t,outputTensorViews:u};this.pendingKernels.push(V),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(V)}return this.programManager.run(ee,a,S,N,B),ze(e.name),u}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let o=xr.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let i={kernelType:e,kernelName:n,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,i)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let o=n.kernelType,i=n.kernelName,a=n.kernelEntry,c=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${i}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),ns("info",()=>`[WebGPU] Start to run kernel "[${o}] ${i}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),a(t,c[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${i}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${o}] ${i}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let i=o.get(t),a=this.gpuDataManager.registerExternalBuffer(s,n,i);return o.set(t,[a,s]),a}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await Ie(this,e,t);return hn(n.buffer,s)}}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(){ns("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(){ns("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ns("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),wn,Nn,ga,yo,Mo,Rd,wa,bo,Nd=y(()=>{er(),wn=1,Nn=()=>wn++,ga=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),yo=(e,t)=>{let s=ga.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*s/8):0},Mo=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return yo(this.dataType,this.tensorShape)}destroy(){ns("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}},Rd=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==yo(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else ns("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},wa=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Nn();return this.tensorTrackersById.set(e,new Rd(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n){ns("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){ns("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let o=Nn(),i=new Mo({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(o,new Rd(this,i)),this.externalTensors.add(i),o}async getCachedTensor(e,t,s,n,o){let i=this.backend.currentSessionId;for(let[p,h]of this.freeTensors.entries())if(h.sameTypeAndShape(e,t)){ns("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=i,k}let a=this.backend.currentContext;ns("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let c=await a.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new Mo({sessionId:i,context:a,tensor:c,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},bo=(...e)=>new wa(...e)}),ya,Ma,vo,Ip=y(()=>{Ft(),St(),An(),Nd(),er(),ya=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Ma=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((o,i)=>o===n[i]&&e[o]===t[o])},vo=class{constructor(e){this.tensorManager=bo(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],pn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>Ma(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(o=>o.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ns("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let o=ya.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,o,s,n)}uploadTensor(e,t){if(!dt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ns("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return hn(s,t)}}registerMLTensor(e,t,s){let n=ya.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(this.currentContext,e,n,s);return ns("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,s,n,o,i){if(!i)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let c=i.get(a);if(!c)throw new Error(`File with name ${a} not found in preloaded files.`);if(t+s>c.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=c.slice(t,t+s).buffer,h;switch(o.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return ns("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`),n.constant(o,h)}flush(){}}}),ip={};P(ip,{init:()=>_r});var ba,tn,_r,a_=y(()=>{Ft(),gn(),er(),zt(),Ip(),ba=class n_{constructor(t,s,n,o){this.module=t,this.dataType=s,this.data=n,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Se.size(t)!==Se.size(this.dims))throw new Error("Invalid new shape");return new n_(this.module,this.dataType,this.data,t)}},tn=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,o=s/e.PTR_SIZE,i=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*o++,i));let a=Number(e.getValue(n*o++,i));this.outputCount=Number(e.getValue(n*o++,i)),this.customDataOffset=Number(e.getValue(n*o++,"*")),this.customDataSize=Number(e.getValue(n*o++,i));let c=[];for(let p=0;ptypeof a=="number"?this.inputs[a]:a)??this.inputs,n=t?.outputs??[],o=(a,c,p)=>new ba(this.module,c,this.output(a,p),p),i=(a,c)=>{let p=Zs(a,c);if(!p)throw new Error(`Unsupported data type: ${a}`);let h=p>0?this.backend.gpuDataManager.create(p).id:0;return new ba(this.module,a,h,c)};return this.backend.run(e,s,n,o,i,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,o=n===4?"i32":"i64",i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,o);for(let a=0;a{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new Br;await i.initialize(s,n),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,c,p,h=!1)=>{if(h)ns("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(c)}, size=${Number(p)}`),i.memcpy(Number(a),Number(c));else{ns("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(c)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(p));i.upload(Number(c),k)}},async(a,c,p)=>{ns("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${c}, size=${p}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(c)>>>0,Number(c+p)>>>0))},(a,c,p)=>i.createKernel(a,Number(c),p,t.UTF8ToString(t._JsepGetNodeName(Number(c)))),a=>i.releaseKernel(a),(a,c,p,h)=>{ns("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${c}`);let k=new tn(t,i,Number(c));return i.computeKernel(Number(a),k,h)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new vo(s);o("webnn",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,c,p,h)=>i.ensureTensor(a,c,p,h),(a,c)=>{i.uploadTensor(a,c)},async(a,c)=>i.downloadTensor(a,c)])}}}),wh,Op,Fp,jn,yh,ap,Dp,Lp,zp,Bp,Rp,Np,Mh=y(()=>{qn(),Xn(),Ft(),St(),Vr(),En(),wh=(e,t)=>{dt()._OrtInit(e,t)!==0&&rs("Can't initialize onnxruntime.")},Op=async e=>{wh(e.wasm.numThreads,Gr(e.logLevel))},Fp=async(e,t)=>{{let s=(a_(),T(ip)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let 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:o,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 s("webgpu",dt(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",dt(),e)}}},jn=new Map,yh=e=>{let t=dt(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&rs("Can't get session input/output count.");let i=n===4?"i32":"i64";return[Number(t.getValue(o,i)),Number(t.getValue(o+n,i))]}finally{t.stackRestore(s)}},ap=e=>{let t=dt(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Dp=async(e,t)=>{let s,n,o=dt();Array.isArray(e)?[s,n]=e:e.buffer===o.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=ap(e);let i=0,a=0,c=0,p=[],h=[],k=[];try{if([a,p]=Pn(t),t?.externalData&&o.mountExternalData){let V=[];for(let de of t.externalData){let me=typeof de=="string"?de:de.path;V.push(cn(typeof de=="string"?de:de.data).then(ye=>{o.mountExternalData(me,ye)}))}await Promise.all(V)}for(let V of t?.executionProviders??[])if((typeof V=="string"?V:V.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof V!="string"){let de=V,me=de?.context,ye=de?.gpuDevice,Be=de?.deviceType,Ee=de?.powerPreference;me?o.currentContext=me:ye?o.currentContext=await o.jsepCreateMLContext(ye):o.currentContext=await o.jsepCreateMLContext({deviceType:Be,powerPreference:Ee})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(s,n,a),i===0&&rs("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,S]=yh(i),B=!!t?.enableGraphCapture,N=[],L=[],se=[];for(let V=0;VV==="gpu-buffer"||V==="ml-tensor")&&(c=o._OrtCreateBinding(i),c===0&&rs("Can't create IO binding."),ee={handle:c,outputPreferredLocations:se,outputPreferredLocationsEncoded:se.map(V=>dn(V))}),jn.set(i,[i,h,k,ee,B,!1]),[i,N,L]}catch(u){throw h.forEach(S=>o._OrtFree(S)),k.forEach(S=>o._OrtFree(S)),c!==0&&o._OrtReleaseBinding(c)!==0&&rs("Can't release IO binding."),i!==0&&o._OrtReleaseSession(i)!==0&&rs("Can't release session."),u}finally{o._free(s),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&rs("Can't release session options."),p.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Lp=e=>{let t=dt(),s=jn.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,c]=s;a&&(c&&t._OrtClearBoundOutputs(a.handle)!==0&&rs("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&rs("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),o.forEach(p=>t._OrtFree(p)),i.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n)!==0&&rs("Can't release session."),jn.delete(e)},zp=(e,t,s,n,o,i=!1)=>{if(!e){t.push(0);return}let a=dt(),c=a.PTR_SIZE,p=e[0],h=e[1],k=e[3],u,S;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let L=e[2].gpuBuffer;S=Zs(Ir(p),h);let se=a.jsepRegisterBuffer;if(!se)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');u=se(n,o,L,S)}else if(k==="ml-tensor"){let L=e[2].mlTensor;S=Zs(Ir(p),h);let se=a.jsepRegisterMLTensor;if(!se)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');u=se(L,Ir(p),h)}else{let L=e[2];if(Array.isArray(L)){S=c*L.length,u=a._malloc(S),s.push(u);for(let se=0;sea.setValue(N+ee*c,se,c===4?"i32":"i64"));let L=a._OrtCreateTensor(Ir(p),u,S,N,h.length,dn(k));L===0&&rs(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(L)}finally{a.stackRestore(B)}},Bp=async(e,t,s,n,o,i)=>{let a=dt(),c=a.PTR_SIZE,p=jn.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],u=p[2],S=p[3],B=p[4],N=p[5],L=t.length,se=n.length,ee=0,V=[],de=[],me=[],ye=[],Be=a.stackSave(),Ee=a.stackAlloc(L*c),tt=a.stackAlloc(L*c),pt=a.stackAlloc(se*c),Ct=a.stackAlloc(se*c);try{a.jsepOnRunStart?.(h),[ee,V]=$r(i);for(let bt=0;btGs*Cs,1);Jt=fr(at);let yn=S?.outputPreferredLocations[n[bt]];if(Jt==="string"){if(yn==="gpu-buffer"||yn==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Gs=[];for(let Cs=0;Cs0){let Gs=a.jsepGetBuffer;if(!Gs)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Cs=Gs(qt),Ys=Zs(at,Ts);if(Ys===void 0||!un(Jt))throw new Error(`Unsupported data type: ${Jt}`);ss=!0,$t.push([Jt,vs,{gpuBuffer:Cs,download:a.jsepCreateDownloader(Cs,Ys,Jt),dispose:()=>{a._OrtReleaseTensor(Kt)!==0&&rs("Can't release tensor.")}},"gpu-buffer"])}else if(yn==="ml-tensor"&&Ts>0){let Gs=a.jsepEnsureTensor;if(!Gs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Zs(at,Ts)===void 0||!Kr(Jt))throw new Error(`Unsupported data type: ${Jt}`);let Cs=await Gs(qt,at,vs,!1);ss=!0,$t.push([Jt,vs,{mlTensor:Cs,download:a.jsepCreateMLTensorDownloader(qt,Jt),dispose:()=>{a.jsepReleaseTensorId(qt),a._OrtReleaseTensor(Kt)}},"ml-tensor"])}else{let Gs=ln(Jt),Cs=new Gs(Ts);new Uint8Array(Cs.buffer,Cs.byteOffset,Cs.byteLength).set(a.HEAPU8.subarray(qt,qt+Cs.byteLength)),$t.push([Jt,vs,Cs,"cpu"])}}finally{a.stackRestore(jt),Jt==="string"&&qt&&a._free(qt),ss||a._OrtReleaseTensor(Kt)}}return S&&!B&&(a._OrtClearBoundOutputs(S.handle)!==0&&rs("Can't clear bound outputs."),jn.set(e,[h,k,u,S,B,!1])),$t}finally{a.stackRestore(Be),de.forEach(Dt=>a._OrtReleaseTensor(Dt)),me.forEach(Dt=>a._OrtReleaseTensor(Dt)),ye.forEach(Dt=>a._free(Dt)),ee!==0&&a._OrtReleaseRunOptions(ee),V.forEach(Dt=>a._free(Dt))}},Rp=e=>{let t=dt(),s=jn.get(e);if(!s)throw new Error("invalid session id");let n=s[0],o=t._OrtEndProfiling(n);o===0&&rs("Can't get an profile file name."),t._OrtFree(o)},Np=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Un,Pr,va,jd,Ud,lp,jp,up,To,xo,bh,vh,Th,xh,Ph,Eh,Ch,kh,Sh=y(()=>{He(),Mh(),St(),vr(),Un=()=>!!x.wasm.proxy&&typeof document<"u",va=!1,jd=!1,Ud=!1,up=new Map,To=(e,t)=>{let s=up.get(e);s?s.push(t):up.set(e,[t])},xo=()=>{if(va||!jd||Ud||!Pr)throw new Error("worker not ready")},bh=e=>{switch(e.data.type){case"init-wasm":va=!1,e.data.err?(Ud=!0,jp[1](e.data.err)):(jd=!0,jp[0]()),lp&&(URL.revokeObjectURL(lp),lp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=up.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},vh=async()=>{if(!jd){if(va)throw new Error("multiple calls to 'initWasm()' detected.");if(Ud)throw new Error("previous call to 'initWasm()' failed.");if(va=!0,Un())return new Promise((e,t)=>{Pr?.terminate(),Nr().then(([s,n])=>{try{Pr=n,Pr.onerror=i=>t(i),Pr.onmessage=bh,jp=[e,t];let o={type:"init-wasm",in:x};Pr.postMessage(o),lp=s}catch(o){t(o)}},t)});try{await it(x.wasm),await Op(x),jd=!0}catch(e){throw Ud=!0,e}finally{va=!1}}},Th=async e=>{if(Un())return xo(),new Promise((t,s)=>{To("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:x}};Pr.postMessage(n)});await Fp(x,e)},xh=async e=>Un()?(xo(),new Promise((t,s)=>{To("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};Pr.postMessage(n,[e.buffer])})):ap(e),Ph=async(e,t)=>{if(Un()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xo(),new Promise((s,n)=>{To("create",[s,n]);let o={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Pr.postMessage(o,i)})}else return Dp(e,t)},Eh=async e=>{if(Un())return xo(),new Promise((t,s)=>{To("release",[t,s]);let n={type:"release",in:e};Pr.postMessage(n)});Lp(e)},Ch=async(e,t,s,n,o,i)=>{if(Un()){if(s.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return xo(),new Promise((a,c)=>{To("run",[a,c]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:i}};Pr.postMessage(h,Np(p))})}else return Bp(e,t,s,n,o,i)},kh=async e=>{if(Un())return xo(),new Promise((t,s)=>{To("end-profiling",[t,s]);let n={type:"end-profiling",in:e};Pr.postMessage(n)});Rp(e)}}),Up,$h,Ah,l_=y(()=>{He(),Sh(),Ft(),et(),En(),Up=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},$h=e=>{switch(e[3]){case"cpu":return new oe(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!un(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:o}=e[2];return oe.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!Kr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:o}=e[2];return oe.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Ah=class{async fetchModelAndCopyToWasmMemory(e){return xh(await cn(e))}async loadModel(e,t){We();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Ph(s,t),ze()}async dispose(){return Eh(this.sessionId)}async run(e,t,s){We();let n=[],o=[];Object.entries(e).forEach(u=>{let S=u[0],B=u[1],N=this.inputNames.indexOf(S);if(N===-1)throw new Error(`invalid input '${S}'`);n.push(B),o.push(N)});let i=[],a=[];Object.entries(t).forEach(u=>{let S=u[0],B=u[1],N=this.outputNames.indexOf(S);if(N===-1)throw new Error(`invalid output '${S}'`);i.push(B),a.push(N)});let c=n.map((u,S)=>Up(u,()=>`input "${this.inputNames[o[S]]}"`)),p=i.map((u,S)=>u?Up(u,()=>`output "${this.outputNames[a[S]]}"`):null),h=await Ch(this.sessionId,o,c,a,p,s),k={};for(let u=0;uWp,initializeFlags:()=>Vp,wasmBackend:()=>Oh});var Vp,Wp,Oh,u_=y(()=>{He(),Sh(),l_(),vr(),Vp=()=>{if((typeof x.wasm.initTimeout!="number"||x.wasm.initTimeout<0)&&(x.wasm.initTimeout=0),x.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 x.wasm.proxy!="boolean"&&(x.wasm.proxy=!1),typeof x.wasm.trace!="boolean"&&(x.wasm.trace=!1),typeof x.wasm.numThreads!="number"||!Number.isInteger(x.wasm.numThreads)||x.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)x.wasm.numThreads=1;else{let e=typeof navigator>"u"?U("node:os").cpus().length:navigator.hardwareConcurrency;x.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Wp=class{async init(e){Vp(),await vh(),await Th(e)}async createInferenceSessionHandler(e,t){let s=new Ah;return await s.loadModel(e,t),Promise.resolve(s)}},Oh=new Wp});He(),He(),He();var d_="1.21.0-dev.20241205-d27fecd3d3",c_=$e;{let e=(u_(),T(Ih)).wasmBackend;K("webgpu",e,5),K("webnn",e,5),K("cpu",e,10),K("wasm",e,10)}Object.defineProperty(x.versions,"web",{value:d_,enumerable:!0});/** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */},"./src/backends/onnx.js":(Ce,A,r)=>{var g;r.r(A),r.d(A,{Tensor:()=>U.Tensor,createInferenceSession:()=>ae,deviceToExecutionProviders:()=>K,isONNXProxy:()=>H,isONNXTensor:()=>R});var O=r("./src/env.js"),j=r("?2ce3"),te=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"),U=r("./node_modules/onnxruntime-common/dist/esm/index.js");const y=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"}}),P=[];let b,T;const v=Symbol.for("onnxruntime");if(v in globalThis)T=globalThis[v];else if(O.apis.IS_NODE_ENV){switch(T=j??(g||(g=r.t(j,2))),process.platform){case"win32":P.push("dml");break;case"linux":process.arch==="x64"&&P.push("cuda");break}P.push("cpu"),b=["cpu"]}else T=te,O.apis.IS_WEBNN_AVAILABLE&&P.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),O.apis.IS_WEBGPU_AVAILABLE&&P.push("webgpu"),P.push("wasm"),b=["wasm"];const z=T.InferenceSession;function K(D=null){if(!D)return b;switch(D){case"auto":return P;case"gpu":return P.filter($=>["webgpu","cuda","dml","webnn-gpu"].includes($))}if(P.includes(D))return[y[D]??D];throw new Error(`Unsupported device: "${D}". Should be one of: ${P.join(", ")}.`)}let re=null;async function ae(D,$,w){re&&await re;const C=z.create(D,$);re??=C;const x=await C;return x.config=w,x}function R(D){return D instanceof T.Tensor}const G=T?.env;G?.wasm&&(G.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${O.env.version}/dist/`,G.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(G.wasm.numThreads=1)),G?.webgpu&&(G.webgpu.powerPreference="high-performance");function H(){return G?.wasm?.proxy}O.env.backends.onnx=G},"./src/base/feature_extraction_utils.js":(Ce,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>te,validate_audio_inputs:()=>U});var g=r("./src/utils/constants.js"),O=r("./src/utils/generic.js"),j=r("./src/utils/hub.js");class te extends O.Callable{constructor(P){super(),this.config=P}static async from_pretrained(P,b){const T=await(0,j.getModelJSON)(P,g.FEATURE_EXTRACTOR_NAME,!0,b);return new this(T)}}function U(y,P){if(!(y instanceof Float32Array||y instanceof Float64Array))throw new Error(`${P} expects input to be a Float32Array or a Float64Array, but got ${y?.constructor?.name??typeof y} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(Ce,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>D,post_process_instance_segmentation:()=>H,post_process_object_detection:()=>v,post_process_panoptic_segmentation:()=>G,post_process_semantic_segmentation:()=>z});var g=r("./src/utils/generic.js"),O=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");r("./src/utils/image.js");var te=r("./src/utils/core.js"),U=r("./src/utils/hub.js"),y=r("./src/utils/constants.js");function P($,w,C=0,x=null){const J=$/w;let q=(0,j.bankers_round)(J)*w;return x!==null&&q>x&&(q=Math.floor(J)*w),qw&&he.push(Le)}else{let Le=(0,j.max)(Z.data)[1];if(Le===fe-1||(ve=(0,j.softmax)(Z.data),ve[Le]Ke*De[(ne+1)%2])),Ge.boxes.push(Ze),Ge.classes.push(Le),Ge.scores.push(ve[Le])}}Pe.push(Ge)}return Pe}function z($,w=null){const C=$.logits,x=C.dims[0];if(w!==null&&w.length!==x)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const J=[];for(let q=0;qDe[he]&&(De[he]=Z[he],Ge[he]=ue)}const Ne=new Array(ce.dims[0]);for(let ue=0;ueue!==void 0);J.push({segmentation:be,labels:lt})}return J}function K($,w,C,x){const J=[],q=[],le=[];for(let ce=0;ce<$.dims[0];++ce){const fe=$[ce],Pe=w[ce],be=(0,j.max)(fe.data)[1];if(be===x)continue;const Ge=(0,j.softmax)(fe.data)[be];Ge>C&&(J.push(Pe),q.push(Ge),le.push(be))}return[J,q,le]}function re($,w,C,x=.5,J=.8){const q=[];let le=0,ce=0;const fe=w[C].data;for(let be=0;be<$.length;++be)$[be]===C&&(q.push(be),++le),fe[be]>=x&&++ce;let Pe=le>0&&ce>0;return Pe&&(Pe=le/ce>J),[Pe,q]}function ae($,w,C,x,J,q=null,le=null){const[ce,fe]=le??$[0].dims,Pe=new O.Tensor("int32",new Int32Array(ce*fe),[ce,fe]),be=[];if(le!==null)for(let ue=0;ue<$.length;++ue)$[ue]=(0,O.interpolate)($[ue],le,"bilinear",!1);const De=new Int32Array($[0].data.length),Ge=new Float32Array($[0].data.length);for(let ue=0;ue<$.length;++ue){let Z=w[ue];const he=$[ue].data;for(let ve=0;veGe[ve]&&(De[ve]=ue,Ge[ve]=he[ve])}let Ne=0;const lt=Pe.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max($,w)/Math.min($,w)}`);let q=Math.round($/C)*C,le=Math.round(w/C)*C;if(q*le>J){const ce=Math.sqrt($*w/J);q=Math.floor($/ce/C)*C,le=Math.floor(w/ce/C)*C}else if(q*leq?Pe=Math.floor(q*fe/J):q>J&&(fe=Math.floor(J*Pe/q)),await w.resize(Pe,fe,{resample:x}))}async crop_margin(w,C=200){const x=w.clone().grayscale(),J=(0,j.min)(x.data)[0],le=(0,j.max)(x.data)[0]-J;if(le===0)return w;const ce=C/255;let fe=x.width,Pe=x.height,be=0,De=0;const Ge=x.data;for(let Ne=0;Nethis.preprocess(q)));return{pixel_values:(0,O.stack)(x.map(q=>q.pixel_values),0),original_sizes:x.map(q=>q.original_size),reshaped_input_sizes:x.map(q=>q.reshaped_input_size)}}static async from_pretrained(w,C){const x=await(0,U.getModelJSON)(w,y.IMAGE_PROCESSOR_NAME,!0,C);return new this(x)}}},"./src/base/processing_utils.js":(Ce,A,r)=>{r.r(A),r.d(A,{Processor:()=>te});var g=r("./src/utils/constants.js"),O=r("./src/utils/generic.js"),j=r("./src/utils/hub.js");class te extends O.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(y,P){super(),this.config=y,this.components=P}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(y,P={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(y,{tokenize:!1,...P})}batch_decode(...y){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...y)}async _call(y,...P){for(const b of[this.image_processor,this.feature_extractor,this.tokenizer])if(b)return b(y,...P);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(y,P){const[b,T]=await Promise.all([this.uses_processor_config?(0,j.getModelJSON)(y,g.PROCESSOR_NAME,!0,P):{},Promise.all(this.classes.filter(v=>v in this).map(async v=>{const z=await this[v].from_pretrained(y,P);return[v.replace(/_class$/,""),z]})).then(Object.fromEntries)]);return new this(b,T)}}},"./src/configs.js":(Ce,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>P,PretrainedConfig:()=>y,getKeyValueShapes:()=>U});var g=r("./src/utils/core.js"),O=r("./src/utils/hub.js");async function j(b,T){return await(0,O.getModelJSON)(b,"config.json",!0,T)}function te(b){const T={};let v={};switch(b.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":v=te(b.text_config);break;case"moondream1":v=te(b.phi_config);break;case"musicgen":v=te(b.decoder);break;case"multi_modality":v=te(b.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":T.num_heads="n_head",T.num_layers="n_layer",T.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":T.num_heads="num_attention_heads",T.num_layers="num_hidden_layers",T.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":T.num_heads="num_key_value_heads",T.num_layers="num_hidden_layers",T.hidden_size="hidden_size",T.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":T.num_heads="num_key_value_heads",T.num_layers="num_hidden_layers",T.dim_kv="head_dim";break;case"openelm":T.num_heads="num_kv_heads",T.num_layers="num_transformer_layers",T.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":T.num_heads="num_heads",T.num_layers="num_layers",T.hidden_size="hidden_size";break;case"bloom":T.num_heads="n_head",T.num_layers="n_layer",T.hidden_size="hidden_size";break;case"mpt":T.num_heads="n_heads",T.num_layers="n_layers",T.hidden_size="d_model";break;case"exaone":T.num_heads="num_key_value_heads",T.num_layers="num_layers",T.dim_kv="head_dim",T.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":T.num_decoder_layers="num_decoder_layers",T.num_decoder_heads="num_heads",T.decoder_dim_kv="d_kv",T.num_encoder_layers="num_layers",T.num_encoder_heads="num_heads",T.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":T.num_decoder_layers="decoder_layers",T.num_decoder_heads="decoder_attention_heads",T.decoder_hidden_size="d_model",T.num_encoder_layers="encoder_layers",T.num_encoder_heads="encoder_attention_heads",T.encoder_hidden_size="d_model";break;case"speecht5":T.num_decoder_layers="decoder_layers",T.num_decoder_heads="decoder_attention_heads",T.decoder_hidden_size="hidden_size",T.num_encoder_layers="encoder_layers",T.num_encoder_heads="encoder_attention_heads",T.encoder_hidden_size="hidden_size";break;case"trocr":T.num_encoder_layers=T.num_decoder_layers="decoder_layers",T.num_encoder_heads=T.num_decoder_heads="decoder_attention_heads",T.encoder_hidden_size=T.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":T.num_encoder_layers=T.num_decoder_layers="num_hidden_layers",T.num_encoder_heads=T.num_decoder_heads="num_attention_heads",T.encoder_hidden_size=T.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const K=te(b.decoder),re="num_decoder_layers"in K,ae=(0,g.pick)(b,["model_type","is_encoder_decoder"]);return re?(ae.num_decoder_layers=K.num_decoder_layers,ae.num_decoder_heads=K.num_decoder_heads,ae.decoder_hidden_size=K.decoder_hidden_size,ae.num_encoder_layers=K.num_encoder_layers,ae.num_encoder_heads=K.num_encoder_heads,ae.encoder_hidden_size=K.encoder_hidden_size):(ae.num_layers=K.num_layers,ae.num_heads=K.num_heads,ae.hidden_size=K.hidden_size),ae}const z={...v,...(0,g.pick)(b,["model_type","multi_query","is_encoder_decoder"])};for(const K in T)z[K]=b[T[K]];return z}function U(b,{prefix:T="past_key_values",batch_size:v=1}={}){const z={},K=b.normalized_config;if(K.is_encoder_decoder&&"num_encoder_heads"in K&&"num_decoder_heads"in K){const re=K.encoder_dim_kv??K.encoder_hidden_size/K.num_encoder_heads,ae=K.decoder_dim_kv??K.decoder_hidden_size/K.num_decoder_heads,R=[v,K.num_encoder_heads,0,re],G=[v,K.num_decoder_heads,0,ae];for(let H=0;H{r.r(A),r.d(A,{apis:()=>ae,env:()=>w});var g=r("?569f"),O=r("?3f59"),j=r("?154a");const te="3.2.0",U=typeof window<"u"&&typeof window.document<"u",y=typeof self<"u"&&self.constructor?.name==="DedicatedWorkerGlobalScope",P=typeof self<"u"&&"caches"in self,b=typeof navigator<"u"&&"gpu"in navigator,T=typeof navigator<"u"&&"ml"in navigator,v=typeof process<"u",z=v&&process?.release?.name==="node",K=!C(g),re=!C(O),ae=Object.freeze({IS_BROWSER_ENV:U,IS_WEBWORKER_ENV:y,IS_WEB_CACHE_AVAILABLE:P,IS_WEBGPU_AVAILABLE:b,IS_WEBNN_AVAILABLE:T,IS_PROCESS_AVAILABLE:v,IS_NODE_ENV:z,IS_FS_AVAILABLE:K,IS_PATH_AVAILABLE:re}),R=K&&re;let G="./";if(R){const x=Object(import.meta).url;x?G=O.dirname(O.dirname(j.fileURLToPath(x))):typeof __dirname<"u"&&(G=O.dirname(__dirname))}const H=R?O.join(G,"/.cache/"):null,D="/models/",$=R?O.join(G,D):D,w={version:te,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(U||y),localModelPath:$,useFS:K,useBrowserCache:P,useFSCache:K,cacheDir:H,useCustomCache:!1,customCache:null};function C(x){return Object.keys(x).length===0}},"./src/generation/configuration_utils.js":(Ce,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>O});var g=r("./src/utils/core.js");class O{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;streamer=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(te){Object.assign(this,(0,g.pick)(te,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Ce,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>R,ForcedBOSTokenLogitsProcessor:()=>y,ForcedEOSTokenLogitsProcessor:()=>P,LogitsProcessor:()=>j,LogitsProcessorList:()=>U,LogitsWarper:()=>te,MinLengthLogitsProcessor:()=>K,MinNewTokensLengthLogitsProcessor:()=>re,NoBadWordsLogitsProcessor:()=>ae,NoRepeatNGramLogitsProcessor:()=>v,RepetitionPenaltyLogitsProcessor:()=>z,SuppressTokensAtBeginLogitsProcessor:()=>b,TemperatureLogitsWarper:()=>G,TopKLogitsWarper:()=>D,TopPLogitsWarper:()=>H,WhisperTimeStampLogitsProcessor:()=>T});var g=r("./src/utils/generic.js");r("./src/utils/tensor.js");var O=r("./src/utils/maths.js");class j extends g.Callable{_call(w,C){throw Error("`_call` should be implemented in a subclass")}}class te extends g.Callable{_call(w,C){throw Error("`_call` should be implemented in a subclass")}}class U extends g.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,C){let x=C;for(const J of this.processors)x=J(w,x);return x}[Symbol.iterator](){return this.processors.values()}}class y extends j{constructor(w){super(),this.bos_token_id=w}_call(w,C){for(let x=0;x=1&&q[q.length-1]>=this.timestamp_begin,ce=q.length<2||q[q.length-2]>=this.timestamp_begin;if(le&&(ce?J.subarray(this.timestamp_begin).fill(-1/0):J.subarray(0,this.eos_token_id).fill(-1/0)),w[x].length===this.begin_index&&this.max_initial_timestamp_index!==null){const De=this.timestamp_begin+this.max_initial_timestamp_index;J.subarray(De+1).fill(-1/0)}const fe=(0,O.log_softmax)(J),Pe=Math.log(fe.subarray(this.timestamp_begin).map(Math.exp).reduce((De,Ge)=>De+Ge)),be=(0,O.max)(fe.subarray(0,this.timestamp_begin))[0];Pe>be&&J.subarray(0,this.timestamp_begin).fill(-1/0)}return C}}class v extends j{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const C=w.length,x=[];for(let q=0;q1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,C){if(C.dims[0]!==2*w.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${C.dims[0]} for the logits and ${w.length} for the input ids.`);const x=w.length,J=C.slice([0,x],null),q=C.slice([x,C.dims[0]],null);for(let le=0;le1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(x)||x<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${x}`);this.top_p=w,this.filter_value=C,this.min_tokens_to_keep=x}}class D extends te{constructor(w,{filter_value:C=-1/0,min_tokens_to_keep:x=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,x),this.filter_value=C}}},"./src/generation/logits_sampler.js":(Ce,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>te});var g=r("./src/utils/generic.js"),O=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class te extends g.Callable{constructor(T){super(),this.generation_config=T}async _call(T){return this.sample(T)}async sample(T){throw Error("sample should be implemented in subclasses.")}getLogits(T,v){let z=T.dims.at(-1),K=T.data;if(v===-1)K=K.slice(-z);else{let re=v*z;K=K.slice(re,re+z)}return K}randomSelect(T){let v=0;for(let K=0;K1)return new P(T);if(T.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${T.num_return_sequences}.`);return new U(T)}}class U extends te{async sample(T){const v=(0,j.max)(T.data)[1];return[[BigInt(v),0]]}}class y extends te{async sample(T){let v=T.dims.at(-1);this.generation_config.top_k>0&&(v=Math.min(this.generation_config.top_k,v));const[z,K]=await(0,O.topk)(T,v),re=(0,j.softmax)(z.data);return Array.from({length:this.generation_config.num_beams},()=>{const ae=this.randomSelect(re);return[K.data[ae],Math.log(re[ae])]})}}class P extends te{async sample(T){let v=T.dims.at(-1);this.generation_config.top_k>0&&(v=Math.min(this.generation_config.top_k,v));const[z,K]=await(0,O.topk)(T,v),re=(0,j.softmax)(z.data);return Array.from({length:this.generation_config.num_beams},(ae,R)=>[K.data[R],Math.log(re[R])])}}},"./src/generation/stopping_criteria.js":(Ce,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>U,InterruptableStoppingCriteria:()=>y,MaxLengthCriteria:()=>te,StoppingCriteria:()=>O,StoppingCriteriaList:()=>j});var g=r("./src/utils/generic.js");class O extends g.Callable{_call(b,T){throw Error("StoppingCriteria needs to be subclassed")}}class j extends g.Callable{constructor(){super(),this.criteria=[]}push(b){this.criteria.push(b)}extend(b){b instanceof j?b=b.criteria:b instanceof O&&(b=[b]),this.criteria.push(...b)}_call(b,T){const v=new Array(b.length).fill(!1);for(const z of this.criteria){const K=z(b,T);for(let re=0;reT.length>=this.max_length)}}class U extends O{constructor(b){super(),Array.isArray(b)||(b=[b]),this.eos_token_id=b}_call(b,T){return b.map(v=>{const z=v.at(-1);return this.eos_token_id.some(K=>z==K)})}}class y extends O{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(b,T){return new Array(b.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Ce,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>te,TextStreamer:()=>y,WhisperTextStreamer:()=>P});var g=r("./src/utils/core.js"),O=r("./src/tokenizers.js"),j=r("./src/env.js");class te{put(T){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const U=j.apis.IS_PROCESS_AVAILABLE?b=>process.stdout.write(b):b=>console.log(b);class y extends te{constructor(T,{skip_prompt:v=!1,callback_function:z=null,token_callback_function:K=null,decode_kwargs:re={},...ae}={}){super(),this.tokenizer=T,this.skip_prompt=v,this.callback_function=z??U,this.token_callback_function=K,this.decode_kwargs={...re,...ae},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(T){if(T.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const v=T[0];this.token_callback_function?.(v),this.token_cache=(0,g.mergeArrays)(this.token_cache,v);const z=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let K;z.endsWith(` +`)?(K=z.slice(this.print_len),this.token_cache=[],this.print_len=0):z.length>0&&(0,O.is_chinese_char)(z.charCodeAt(z.length-1))?(K=z.slice(this.print_len),this.print_len+=K.length):(K=z.slice(this.print_len,z.lastIndexOf(" ")+1),this.print_len+=K.length),this.on_finalized_text(K,!1)}end(){let T;this.token_cache.length>0?(T=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):T="",this.next_tokens_are_prompt=!0,this.on_finalized_text(T,!0)}on_finalized_text(T,v){T.length>0&&this.callback_function?.(T),v&&this.callback_function===U&&j.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}}class P extends y{constructor(T,{skip_prompt:v=!1,callback_function:z=null,token_callback_function:K=null,on_chunk_start:re=null,on_chunk_end:ae=null,on_finalize:R=null,time_precision:G=.02,skip_special_tokens:H=!0,decode_kwargs:D={}}={}){super(T,{skip_prompt:v,callback_function:z,token_callback_function:K,decode_kwargs:{skip_special_tokens:H,...D}}),this.timestamp_begin=T.timestamp_begin,this.on_chunk_start=re,this.on_chunk_end=ae,this.on_finalize=R,this.time_precision=G,this.waiting_for_timestamp=!1}put(T){if(T.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const v=T[0];if(v.length===1){const z=Number(v[0])-this.timestamp_begin;if(z>=0){const K=z*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(K):this.on_chunk_start?.(K),this.waiting_for_timestamp=!this.waiting_for_timestamp,T=[[]]}}return super.put(T)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(Ce,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>ko,ASTModel:()=>Sa,ASTPreTrainedModel:()=>Gt,AlbertForMaskedLM:()=>ns,AlbertForQuestionAnswering:()=>$n,AlbertForSequenceClassification:()=>pn,AlbertModel:()=>Sn,AlbertPreTrainedModel:()=>Or,AutoModel:()=>kp,AutoModelForAudioClassification:()=>Hc,AutoModelForAudioFrameClassification:()=>Xc,AutoModelForCTC:()=>Kc,AutoModelForCausalLM:()=>zc,AutoModelForDepthEstimation:()=>Zc,AutoModelForDocumentQuestionAnswering:()=>Qc,AutoModelForImageClassification:()=>Nc,AutoModelForImageFeatureExtraction:()=>tp,AutoModelForImageMatting:()=>Yc,AutoModelForImageSegmentation:()=>jc,AutoModelForImageToImage:()=>Jc,AutoModelForMaskGeneration:()=>Gc,AutoModelForMaskedLM:()=>Bc,AutoModelForNormalEstimation:()=>Ld,AutoModelForObjectDetection:()=>Vc,AutoModelForPoseEstimation:()=>ep,AutoModelForQuestionAnswering:()=>$p,AutoModelForSemanticSegmentation:()=>Uc,AutoModelForSeq2SeqLM:()=>Fc,AutoModelForSequenceClassification:()=>Ic,AutoModelForSpeechSeq2Seq:()=>Dc,AutoModelForTextToSpectrogram:()=>Sp,AutoModelForTextToWaveform:()=>Lc,AutoModelForTokenClassification:()=>Oc,AutoModelForUniversalSegmentation:()=>Ap,AutoModelForVision2Seq:()=>Rc,AutoModelForXVector:()=>qc,AutoModelForZeroShotObjectDetection:()=>Wc,BartForConditionalGeneration:()=>Xe,BartForSequenceClassification:()=>_t,BartModel:()=>Ie,BartPretrainedModel:()=>ge,BaseModelOutput:()=>Ae,BeitForImageClassification:()=>Zl,BeitModel:()=>Jl,BeitPreTrainedModel:()=>gi,BertForMaskedLM:()=>je,BertForQuestionAnswering:()=>ze,BertForSequenceClassification:()=>Re,BertForTokenClassification:()=>We,BertModel:()=>Me,BertPreTrainedModel:()=>oe,BlenderbotForConditionalGeneration:()=>Ps,BlenderbotModel:()=>Se,BlenderbotPreTrainedModel:()=>gs,BlenderbotSmallForConditionalGeneration:()=>dr,BlenderbotSmallModel:()=>Rs,BlenderbotSmallPreTrainedModel:()=>js,BloomForCausalLM:()=>El,BloomModel:()=>Pl,BloomPreTrainedModel:()=>ni,CLIPModel:()=>ja,CLIPPreTrainedModel:()=>Xr,CLIPSegForImageSegmentation:()=>qa,CLIPSegModel:()=>Ha,CLIPSegPreTrainedModel:()=>Do,CLIPTextModel:()=>Yd,CLIPTextModelWithProjection:()=>Ua,CLIPVisionModel:()=>Jd,CLIPVisionModelWithProjection:()=>Va,CamembertForMaskedLM:()=>sr,CamembertForQuestionAnswering:()=>an,CamembertForSequenceClassification:()=>Rr,CamembertForTokenClassification:()=>Cr,CamembertModel:()=>Ks,CamembertPreTrainedModel:()=>Ms,CausalLMOutput:()=>en,CausalLMOutputWithPast:()=>rp,ChineseCLIPModel:()=>cr,ChineseCLIPPreTrainedModel:()=>Zd,ClapAudioModelWithProjection:()=>Qu,ClapModel:()=>Jr,ClapPreTrainedModel:()=>mr,ClapTextModelWithProjection:()=>Zr,CodeGenForCausalLM:()=>il,CodeGenModel:()=>Uo,CodeGenPreTrainedModel:()=>eo,CohereForCausalLM:()=>sc,CohereModel:()=>hl,CoherePreTrainedModel:()=>Yo,ConvBertForMaskedLM:()=>He,ConvBertForQuestionAnswering:()=>yt,ConvBertForSequenceClassification:()=>et,ConvBertForTokenClassification:()=>ot,ConvBertModel:()=>$e,ConvBertPreTrainedModel:()=>_e,ConvNextForImageClassification:()=>lc,ConvNextModel:()=>Li,ConvNextPreTrainedModel:()=>Di,ConvNextV2ForImageClassification:()=>_u,ConvNextV2Model:()=>uc,ConvNextV2PreTrainedModel:()=>zi,DPTForDepthEstimation:()=>Dn,DPTModel:()=>$i,DPTPreTrainedModel:()=>Si,DebertaForMaskedLM:()=>br,DebertaForQuestionAnswering:()=>Sr,DebertaForSequenceClassification:()=>kr,DebertaForTokenClassification:()=>vr,DebertaModel:()=>Nr,DebertaPreTrainedModel:()=>Ot,DebertaV2ForMaskedLM:()=>Tr,DebertaV2ForQuestionAnswering:()=>it,DebertaV2ForSequenceClassification:()=>jr,DebertaV2ForTokenClassification:()=>rr,DebertaV2Model:()=>ur,DebertaV2PreTrainedModel:()=>Js,DecisionTransformerModel:()=>hd,DecisionTransformerPreTrainedModel:()=>ea,DeiTForImageClassification:()=>vi,DeiTModel:()=>bi,DeiTPreTrainedModel:()=>mn,DepthAnythingForDepthEstimation:()=>Ai,DepthAnythingPreTrainedModel:()=>au,DepthProForDepthEstimation:()=>cu,DepthProPreTrainedModel:()=>du,DetrForObjectDetection:()=>tu,DetrForSegmentation:()=>su,DetrModel:()=>eu,DetrObjectDetectionOutput:()=>Dr,DetrPreTrainedModel:()=>no,DetrSegmentationOutput:()=>Qr,Dinov2ForImageClassification:()=>Ri,Dinov2Model:()=>fu,Dinov2PreTrainedModel:()=>Bi,DistilBertForMaskedLM:()=>Vr,DistilBertForQuestionAnswering:()=>rs,DistilBertForSequenceClassification:()=>cs,DistilBertForTokenClassification:()=>Ur,DistilBertModel:()=>St,DistilBertPreTrainedModel:()=>dt,DonutSwinModel:()=>mu,DonutSwinPreTrainedModel:()=>Fi,EfficientNetForImageClassification:()=>rd,EfficientNetModel:()=>Hs,EfficientNetPreTrainedModel:()=>sd,ElectraForMaskedLM:()=>ts,ElectraForQuestionAnswering:()=>$s,ElectraForSequenceClassification:()=>xs,ElectraForTokenClassification:()=>hs,ElectraModel:()=>Qt,ElectraPreTrainedModel:()=>mt,EsmForMaskedLM:()=>Tn,EsmForSequenceClassification:()=>Wr,EsmForTokenClassification:()=>xn,EsmModel:()=>qn,EsmPreTrainedModel:()=>$r,ExaoneForCausalLM:()=>al,ExaoneModel:()=>to,ExaonePreTrainedModel:()=>Go,FalconForCausalLM:()=>yr,FalconModel:()=>yc,FalconPreTrainedModel:()=>Hi,FastViTForImageClassification:()=>rc,FastViTModel:()=>Ul,FastViTPreTrainedModel:()=>hi,Florence2ForConditionalGeneration:()=>La,Florence2PreTrainedModel:()=>Da,GLPNForDepthEstimation:()=>Oi,GLPNModel:()=>uo,GLPNPreTrainedModel:()=>Ii,GPT2LMHeadModel:()=>Qa,GPT2Model:()=>Xa,GPT2PreTrainedModel:()=>Lo,GPTBigCodeForCausalLM:()=>ol,GPTBigCodeModel:()=>nl,GPTBigCodePreTrainedModel:()=>jo,GPTJForCausalLM:()=>rl,GPTJModel:()=>sl,GPTJPreTrainedModel:()=>No,GPTNeoForCausalLM:()=>Za,GPTNeoModel:()=>hr,GPTNeoPreTrainedModel:()=>Bo,GPTNeoXForCausalLM:()=>tl,GPTNeoXModel:()=>el,GPTNeoXPreTrainedModel:()=>Ro,Gemma2ForCausalLM:()=>fl,Gemma2Model:()=>_l,Gemma2PreTrainedModel:()=>Zo,GemmaForCausalLM:()=>ml,GemmaModel:()=>as,GemmaPreTrainedModel:()=>Jo,GraniteForCausalLM:()=>pl,GraniteModel:()=>tc,GranitePreTrainedModel:()=>Qo,GroupViTModel:()=>jl,GroupViTPreTrainedModel:()=>pi,HieraForImageClassification:()=>xi,HieraModel:()=>nu,HieraPreTrainedModel:()=>Ti,HubertForCTC:()=>Bu,HubertForSequenceClassification:()=>Ru,HubertModel:()=>zu,HubertPreTrainedModel:()=>Ep,IJepaForImageClassification:()=>Fl,IJepaModel:()=>Ol,IJepaPreTrainedModel:()=>li,Idefics3ForConditionalGeneration:()=>Io,Idefics3PreTrainedModel:()=>Ra,ImageMattingOutput:()=>Bd,JAISLMHeadModel:()=>Ja,JAISModel:()=>Ya,JAISPreTrainedModel:()=>zo,JinaCLIPModel:()=>Zn,JinaCLIPPreTrainedModel:()=>Jn,JinaCLIPTextModel:()=>Fo,JinaCLIPVisionModel:()=>pr,LlamaForCausalLM:()=>ec,LlamaModel:()=>Wo,LlamaPreTrainedModel:()=>Vo,LlavaForConditionalGeneration:()=>Yn,LlavaOnevisionForConditionalGeneration:()=>Oa,LlavaPreTrainedModel:()=>Fr,LongT5ForConditionalGeneration:()=>Te,LongT5Model:()=>In,LongT5PreTrainedModel:()=>Hr,M2M100ForConditionalGeneration:()=>Tu,M2M100Model:()=>vu,M2M100PreTrainedModel:()=>Vi,MBartForCausalLM:()=>Xt,MBartForConditionalGeneration:()=>Qe,MBartForSequenceClassification:()=>It,MBartModel:()=>vt,MBartPreTrainedModel:()=>ft,MPNetForMaskedLM:()=>Gr,MPNetForQuestionAnswering:()=>dn,MPNetForSequenceClassification:()=>un,MPNetForTokenClassification:()=>Kr,MPNetModel:()=>ln,MPNetPreTrainedModel:()=>Zs,MT5ForConditionalGeneration:()=>pe,MT5Model:()=>Q,MT5PreTrainedModel:()=>M,MarianMTModel:()=>cc,MarianModel:()=>bu,MarianPreTrainedModel:()=>Ui,MaskFormerForInstanceSegmentation:()=>lo,MaskFormerModel:()=>hu,MaskFormerPreTrainedModel:()=>pu,MaskedLMOutput:()=>Us,MgpstrForSceneTextRecognition:()=>fd,MgpstrModelOutput:()=>md,MgpstrPreTrainedModel:()=>_d,MistralForCausalLM:()=>wc,MistralModel:()=>Hu,MistralPreTrainedModel:()=>Gi,MobileBertForMaskedLM:()=>Xn,MobileBertForQuestionAnswering:()=>fr,MobileBertForSequenceClassification:()=>Ir,MobileBertModel:()=>Pn,MobileBertPreTrainedModel:()=>Ar,MobileLLMForCausalLM:()=>On,MobileLLMModel:()=>ll,MobileLLMPreTrainedModel:()=>Ko,MobileNetV1ForImageClassification:()=>id,MobileNetV1Model:()=>od,MobileNetV1PreTrainedModel:()=>Yi,MobileNetV2ForImageClassification:()=>ld,MobileNetV2Model:()=>ad,MobileNetV2PreTrainedModel:()=>Ji,MobileNetV3ForImageClassification:()=>dd,MobileNetV3Model:()=>ud,MobileNetV3PreTrainedModel:()=>go,MobileNetV4ForImageClassification:()=>pd,MobileNetV4Model:()=>cd,MobileNetV4PreTrainedModel:()=>Zi,MobileViTForImageClassification:()=>Kl,MobileViTModel:()=>Gl,MobileViTPreTrainedModel:()=>ir,MobileViTV2ForImageClassification:()=>ql,MobileViTV2Model:()=>Hl,MobileViTV2PreTrainedModel:()=>mi,ModelOutput:()=>qe,Moondream1ForConditionalGeneration:()=>Fa,MoonshineForConditionalGeneration:()=>Ia,MoonshineModel:()=>nr,MoonshinePreTrainedModel:()=>$o,MptForCausalLM:()=>kl,MptModel:()=>Cl,MptPreTrainedModel:()=>oi,MultiModalityCausalLM:()=>ta,MultiModalityPreTrainedModel:()=>vc,MusicgenForCausalLM:()=>bc,MusicgenForConditionalGeneration:()=>fn,MusicgenModel:()=>nd,MusicgenPreTrainedModel:()=>Qi,NomicBertModel:()=>nt,NomicBertPreTrainedModel:()=>Ye,OPTForCausalLM:()=>$l,OPTModel:()=>Sl,OPTPreTrainedModel:()=>ii,Olmo2ForCausalLM:()=>cl,Olmo2Model:()=>dl,Olmo2PreTrainedModel:()=>Xo,OlmoForCausalLM:()=>qo,OlmoModel:()=>ul,OlmoPreTrainedModel:()=>Ho,OpenELMForCausalLM:()=>wl,OpenELMModel:()=>gl,OpenELMPreTrainedModel:()=>ei,OwlViTForObjectDetection:()=>Ql,OwlViTModel:()=>Xl,OwlViTPreTrainedModel:()=>_i,Owlv2ForObjectDetection:()=>nc,Owlv2Model:()=>Yl,Owlv2PreTrainedModel:()=>fi,PaliGemmaForConditionalGeneration:()=>Ba,PaliGemmaPreTrainedModel:()=>za,PatchTSMixerForPrediction:()=>Md,PatchTSMixerModel:()=>Tc,PatchTSMixerPreTrainedModel:()=>sa,PatchTSTForPrediction:()=>yd,PatchTSTModel:()=>wd,PatchTSTPreTrainedModel:()=>gd,Phi3ForCausalLM:()=>xl,Phi3Model:()=>so,Phi3PreTrainedModel:()=>ri,Phi3VForCausalLM:()=>or,Phi3VPreTrainedModel:()=>Na,PhiForCausalLM:()=>Fn,PhiModel:()=>Tl,PhiPreTrainedModel:()=>si,PreTrainedModel:()=>ne,PretrainedMixin:()=>ms,PvtForImageClassification:()=>Ll,PvtModel:()=>di,PvtPreTrainedModel:()=>ro,PyAnnoteForAudioFrameClassification:()=>Eu,PyAnnoteModel:()=>Pu,PyAnnotePreTrainedModel:()=>po,QuestionAnsweringModelOutput:()=>qs,Qwen2ForCausalLM:()=>Ml,Qwen2Model:()=>yl,Qwen2PreTrainedModel:()=>ti,Qwen2VLForConditionalGeneration:()=>vl,Qwen2VLPreTrainedModel:()=>bl,RTDetrForObjectDetection:()=>Yr,RTDetrModel:()=>wi,RTDetrObjectDetectionOutput:()=>Ws,RTDetrPreTrainedModel:()=>Lr,ResNetForImageClassification:()=>Pi,ResNetModel:()=>ou,ResNetPreTrainedModel:()=>oo,RoFormerForMaskedLM:()=>ht,RoFormerForQuestionAnswering:()=>X,RoFormerForSequenceClassification:()=>I,RoFormerForTokenClassification:()=>ie,RoFormerModel:()=>ut,RoFormerPreTrainedModel:()=>wt,RobertaForMaskedLM:()=>gr,RobertaForQuestionAnswering:()=>xt,RobertaForSequenceClassification:()=>Zt,RobertaForTokenClassification:()=>us,RobertaModel:()=>zs,RobertaPreTrainedModel:()=>zt,SamImageSegmentationOutput:()=>Mu,SamModel:()=>dc,SamPreTrainedModel:()=>yu,SapiensForDepthEstimation:()=>uu,SapiensForNormalEstimation:()=>ac,SapiensForSemanticSegmentation:()=>lu,SapiensPreTrainedModel:()=>ao,SegformerForImageClassification:()=>Ju,SegformerForSemanticSegmentation:()=>Zu,SegformerModel:()=>Mc,SegformerPreTrainedModel:()=>fo,Seq2SeqLMOutput:()=>sp,SequenceClassifierOutput:()=>Ht,SiglipModel:()=>Wa,SiglipPreTrainedModel:()=>Oo,SiglipTextModel:()=>Ga,SiglipVisionModel:()=>Ka,SpeechT5ForSpeechToText:()=>Vu,SpeechT5ForTextToSpeech:()=>Wu,SpeechT5HifiGan:()=>gc,SpeechT5Model:()=>fc,SpeechT5PreTrainedModel:()=>_o,SqueezeBertForMaskedLM:()=>En,SqueezeBertForQuestionAnswering:()=>kn,SqueezeBertForSequenceClassification:()=>Cn,SqueezeBertModel:()=>cn,SqueezeBertPreTrainedModel:()=>Ft,StableLmForCausalLM:()=>td,StableLmModel:()=>ed,StableLmPreTrainedModel:()=>Xi,Starcoder2ForCausalLM:()=>Xu,Starcoder2Model:()=>qu,Starcoder2PreTrainedModel:()=>Ki,Swin2SRForImageSuperResolution:()=>ic,Swin2SRModel:()=>iu,Swin2SRPreTrainedModel:()=>ki,SwinForImageClassification:()=>Ci,SwinModel:()=>io,SwinPreTrainedModel:()=>Ei,T5ForConditionalGeneration:()=>An,T5Model:()=>hn,T5PreTrainedModel:()=>er,TableTransformerForObjectDetection:()=>ru,TableTransformerModel:()=>Mi,TableTransformerObjectDetectionOutput:()=>oc,TableTransformerPreTrainedModel:()=>yi,TokenClassifierOutput:()=>Ns,TrOCRForCausalLM:()=>Ku,TrOCRPreTrainedModel:()=>Gu,UniSpeechForCTC:()=>$u,UniSpeechForSequenceClassification:()=>Au,UniSpeechModel:()=>Su,UniSpeechPreTrainedModel:()=>zn,UniSpeechSatForAudioFrameClassification:()=>Fu,UniSpeechSatForCTC:()=>Wi,UniSpeechSatForSequenceClassification:()=>Ou,UniSpeechSatModel:()=>Iu,UniSpeechSatPreTrainedModel:()=>ho,ViTForImageClassification:()=>Il,ViTMAEModel:()=>Bl,ViTMAEPreTrainedModel:()=>zl,ViTMSNForImageClassification:()=>Nl,ViTMSNModel:()=>Rl,ViTMSNPreTrainedModel:()=>ci,ViTModel:()=>Al,ViTPreTrainedModel:()=>ai,VisionEncoderDecoderModel:()=>Ao,VitMatteForImageMatting:()=>Wl,VitMattePreTrainedModel:()=>Vl,VitPoseForPoseEstimation:()=>Dl,VitPosePreTrainedModel:()=>ui,VitsModel:()=>qi,VitsModelOutput:()=>np,VitsPreTrainedModel:()=>Yu,Wav2Vec2BertForCTC:()=>Du,Wav2Vec2BertForSequenceClassification:()=>Lu,Wav2Vec2BertModel:()=>hc,Wav2Vec2BertPreTrainedModel:()=>mo,Wav2Vec2ForAudioFrameClassification:()=>Ln,Wav2Vec2ForCTC:()=>pc,Wav2Vec2ForSequenceClassification:()=>co,Wav2Vec2Model:()=>xu,Wav2Vec2PreTrainedModel:()=>zr,WavLMForAudioFrameClassification:()=>_c,WavLMForCTC:()=>Nu,WavLMForSequenceClassification:()=>ju,WavLMForXVector:()=>Uu,WavLMModel:()=>mc,WavLMPreTrainedModel:()=>_n,WeSpeakerResNetModel:()=>ku,WeSpeakerResNetPreTrainedModel:()=>Cu,WhisperForConditionalGeneration:()=>Aa,WhisperModel:()=>$a,WhisperPreTrainedModel:()=>So,XLMForQuestionAnswering:()=>Es,XLMForSequenceClassification:()=>Vs,XLMForTokenClassification:()=>Mt,XLMModel:()=>wr,XLMPreTrainedModel:()=>os,XLMRobertaForMaskedLM:()=>tr,XLMRobertaForQuestionAnswering:()=>ka,XLMRobertaForSequenceClassification:()=>qr,XLMRobertaForTokenClassification:()=>Qn,XLMRobertaModel:()=>gt,XLMRobertaPreTrainedModel:()=>Oe,XLMWithLMHeadModel:()=>As,XVectorOutput:()=>zd,YolosForObjectDetection:()=>ji,YolosModel:()=>gu,YolosObjectDetectionOutput:()=>wu,YolosPreTrainedModel:()=>Ni});var g=r("./src/configs.js"),O=r("./src/backends/onnx.js"),j=r("./src/utils/dtypes.js"),te=r("./src/utils/generic.js"),U=r("./src/utils/core.js"),y=r("./src/utils/hub.js"),P=r("./src/utils/constants.js"),b=r("./src/generation/logits_process.js"),T=r("./src/generation/configuration_utils.js"),v=r("./src/utils/tensor.js"),z=r("./src/utils/image.js"),K=r("./src/utils/maths.js"),re=r("./src/generation/stopping_criteria.js"),ae=r("./src/generation/logits_sampler.js"),R=r("./src/env.js"),G=r("./src/models/whisper/generation_whisper.js"),H=r("./src/models/whisper/common_whisper.js");const D={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},$=new Map,w=new Map,C=new Map;async function x(f,_,Y){const xe=Y.config?.["transformers.js_config"]??{};let ke=Y.device??xe.device;ke&&typeof ke!="string"&&(ke.hasOwnProperty(_)?ke=ke[_]:(console.warn(`device not specified for "${_}". Using the default device.`),ke=null));const Fe=ke??(R.apis.IS_NODE_ENV?"cpu":"wasm"),st=(0,O.deviceToExecutionProviders)(Fe);let rt=Y.dtype??xe.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(_)?rt=rt[_]:(rt=j.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??j.DATA_TYPES.fp32,console.warn(`dtype not specified for "${_}". Using the default dtype (${rt}) for this device (${Fe}).`))),rt===j.DATA_TYPES.auto){let es=xe.dtype;typeof es!="string"&&(es=es[_]),es&&es!==j.DATA_TYPES.auto&&j.DATA_TYPES.hasOwnProperty(es)?rt=es:rt=j.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??j.DATA_TYPES.fp32}const ct=rt;if(j.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(ct)){if(ct===j.DATA_TYPES.fp16&&Fe==="webgpu"&&!await(0,j.isWebGpuFp16Supported)())throw new Error(`The device (${Fe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${ct}. Should be one of: ${Object.keys(j.DATA_TYPES).join(", ")}`);const kt=xe.kv_cache_dtype?typeof xe.kv_cache_dtype=="string"?xe.kv_cache_dtype:xe.kv_cache_dtype[ct]??"float32":void 0;if(kt&&!["float32","float16"].includes(kt))throw new Error(`Invalid kv_cache_dtype: ${kt}. Should be one of: float32, float16`);const Yt={dtype:ct,kv_cache_dtype:kt},Ut=j.DEFAULT_DTYPE_SUFFIX_MAPPING[ct],Bt=`${Y.subfolder??""}/${_}${Ut}.onnx`,At={...Y.session_options};At.executionProviders??=st;const bs=xe.free_dimension_overrides;bs?At.freeDimensionOverrides??=bs:Fe.startsWith("webnn")&&!At.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const Vt=(0,y.getModelFile)(f,Bt,!0,Y),Wt=Y.use_external_data_format??xe.use_external_data_format;let _s=[];if(Wt&&(Wt===!0||typeof Wt=="object"&&Wt.hasOwnProperty(_)&&Wt[_]===!0)){if(R.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const es=`${_}${Ut}.onnx_data`,Is=`${Y.subfolder??""}/${es}`;_s.push(new Promise(async(Os,ks)=>{const Bs=await(0,y.getModelFile)(f,Is,!0,Y);Os({path:es,data:Bs})}))}else At.externalData!==void 0&&(_s=At.externalData.map(async es=>{if(typeof es.data=="string"){const Is=await(0,y.getModelFile)(f,es.data,!0,Y);return{...es,data:Is}}return es}));if(_s.length>0&&(At.externalData=await Promise.all(_s)),Fe==="webgpu"){const es=(0,g.getKeyValueShapes)(Y.config,{prefix:"present"});if(Object.keys(es).length>0&&!(0,O.isONNXProxy)()){const Is={};for(const Os in es)Is[Os]="gpu-buffer";At.preferredOutputLocation=Is}}return{buffer:await Vt,session_options:At,session_config:Yt}}async function J(f,_,Y){return Object.fromEntries(await Promise.all(Object.keys(_).map(async xe=>{const{buffer:ke,session_options:Fe,session_config:st}=await x(f,_[xe],Y),rt=await(0,O.createInferenceSession)(ke,Fe,st);return[xe,rt]})))}async function q(f,_,Y){return Object.fromEntries(await Promise.all(Object.keys(_).map(async xe=>{const ke=await(0,y.getModelJSON)(f,_[xe],!1,Y);return[xe,ke]})))}function le(f,_){const Y=Object.create(null),xe=[];for(const st of f.inputNames){const rt=_[st];if(!(rt instanceof v.Tensor)){xe.push(st);continue}Y[st]=(0,O.isONNXProxy)()?rt.clone():rt}if(xe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${xe.join(", ")}.`);const ke=Object.keys(_).length,Fe=f.inputNames.length;if(ke>Fe){let st=Object.keys(_).filter(rt=>!f.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${ke} > ${Fe}). The following inputs will be ignored: "${st.join(", ")}".`)}return Y}async function ce(f,_){const Y=le(f,_);try{const xe=Object.fromEntries(Object.entries(Y).map(([Fe,st])=>[Fe,st.ort_tensor]));let ke=await f.run(xe);return ke=fe(ke),ke}catch(xe){const ke=Object.fromEntries(Object.entries(Y).map(([Fe,{type:st,dims:rt,data:ct}])=>[Fe,{type:st,dims:rt,data:ct}]));throw console.error(`An error occurred during model execution: "${xe}".`),console.error("Inputs given to model:",ke),xe}}function fe(f){for(let _ in f)(0,O.isONNXTensor)(f[_])?f[_]=new v.Tensor(f[_]):typeof f[_]=="object"&&fe(f[_]);return f}function Pe(f){if(f instanceof v.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(_=>_.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new v.Tensor("int64",BigInt64Array.from(f.flat().map(_=>BigInt(_))),[f.length,f[0].length])}else return new v.Tensor("int64",BigInt64Array.from(f.map(_=>BigInt(_))),[1,f.length])}function be(f){return new v.Tensor("bool",[f],[1])}async function De(f,_){let{encoder_outputs:Y,input_ids:xe,decoder_input_ids:ke,...Fe}=_;if(!Y){const rt=(0,U.pick)(_,f.sessions.model.inputNames);Y=(await Ge(f,rt)).last_hidden_state}return Fe.input_ids=ke,Fe.encoder_hidden_states=Y,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Fe.encoder_attention_mask=_.attention_mask),await Ne(f,Fe,!0)}async function Ge(f,_){const Y=f.sessions.model,xe=(0,U.pick)(_,Y.inputNames);if(Y.inputNames.includes("inputs_embeds")&&!xe.inputs_embeds){if(!_.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");xe.inputs_embeds=await f.encode_text({input_ids:_.input_ids})}return Y.inputNames.includes("token_type_ids")&&!xe.token_type_ids&&(xe.token_type_ids=new v.Tensor("int64",new BigInt64Array(xe.input_ids.data.length),xe.input_ids.dims)),await ce(Y,xe)}async function Ne(f,_,Y=!1){const xe=f.sessions[Y?"decoder_model_merged":"model"],{past_key_values:ke,...Fe}=_;if(xe.inputNames.includes("use_cache_branch")&&(Fe.use_cache_branch=be(!!ke)),xe.inputNames.includes("position_ids")&&Fe.attention_mask&&!Fe.position_ids){const rt=f.config.model_type==="paligemma"?1:0;Fe.position_ids=he(Fe,ke,rt)}f.addPastKeyValues(Fe,ke);const st=(0,U.pick)(Fe,xe.inputNames);return await ce(xe,st)}function lt({image_token_id:f,inputs_embeds:_,image_features:Y,input_ids:xe,attention_mask:ke}){const Fe=xe.tolist().map(kt=>kt.reduce((Yt,Ut,Bt)=>(Ut==f&&Yt.push(Bt),Yt),[])),st=Fe.reduce((kt,Yt)=>kt+Yt.length,0),rt=Y.dims[0];if(st!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${st}, features ${rt}`);let ct=0;for(let kt=0;ktFe.dims[1])){if(kert==f.config.image_token_index)){const rt=f.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const ct=Fe.dims[1]-(ke-rt);Y.input_ids=Fe.slice(null,[-ct,null]),Y.attention_mask=(0,v.ones)([1,ke+ct])}}}return Y}function Le(f,_,Y,xe){return Y.past_key_values&&(_=_.map(ke=>[ke.at(-1)])),{...Y,decoder_input_ids:Pe(_)}}function Ze(f,..._){return f.config.is_encoder_decoder?Le(f,..._):ve(f,..._)}function Ke(f,_,Y,xe){const ke=!!Y.past_key_values;return xe.guidance_scale!==null&&xe.guidance_scale>1&&(ke?Y.input_ids=(0,v.cat)([Y.input_ids,Y.input_ids],0):(Y.input_ids=(0,v.cat)([Y.input_ids,(0,v.full_like)(Y.input_ids,BigInt(xe.pad_token_id))],0),Y.attention_mask=(0,v.cat)([Y.attention_mask,(0,v.full_like)(Y.attention_mask,0n)],0))),(ke||!Y.pixel_values)&&(Y.pixel_values=(0,v.full)([0,0,3,384,384],1)),ke&&(Y.images_seq_mask=new v.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),Y.images_emb_mask=new v.Tensor("bool",new Array(0).fill(!1),[1,1,0])),Y}class ne extends te.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(_,Y,xe){super(),this.config=_,this.sessions=Y,this.configs=xe;const ke=C.get(this.constructor),Fe=$.get(ke);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Fe){case D.DecoderOnly:this.can_generate=!0,this._forward=Ne,this._prepare_inputs_for_generation=ve;break;case D.Seq2Seq:case D.Vision2Seq:case D.Musicgen:this.can_generate=!0,this._forward=De,this._prepare_inputs_for_generation=Le;break;case D.EncoderDecoder:this._forward=De;break;case D.ImageTextToText:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=Ze;break;case D.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Ze;break;case D.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Ke;break;default:this._forward=Ge;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const _=[];for(const Y of Object.values(this.sessions))Y?.handler?.dispose&&_.push(Y.handler.dispose());return await Promise.all(_)}static async from_pretrained(_,{progress_callback:Y=null,config:xe=null,cache_dir:ke=null,local_files_only:Fe=!1,revision:st="main",model_file_name:rt=null,subfolder:ct="onnx",device:kt=null,dtype:Yt=null,use_external_data_format:Ut=null,session_options:Bt={}}={}){let At={progress_callback:Y,config:xe,cache_dir:ke,local_files_only:Fe,revision:st,model_file_name:rt,subfolder:ct,device:kt,dtype:Yt,use_external_data_format:Ut,session_options:Bt};const bs=C.get(this),Vt=$.get(bs);xe=At.config=await g.AutoConfig.from_pretrained(_,At);let Wt;if(Vt===D.DecoderOnly)Wt=await Promise.all([J(_,{model:At.model_file_name??"model"},At),q(_,{generation_config:"generation_config.json"},At)]);else if(Vt===D.Seq2Seq||Vt===D.Vision2Seq)Wt=await Promise.all([J(_,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},At),q(_,{generation_config:"generation_config.json"},At)]);else if(Vt===D.MaskGeneration)Wt=await Promise.all([J(_,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},At)]);else if(Vt===D.EncoderDecoder)Wt=await Promise.all([J(_,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},At)]);else if(Vt===D.ImageTextToText){const _s={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};xe.is_encoder_decoder&&(_s.model="encoder_model"),Wt=await Promise.all([J(_,_s,At),q(_,{generation_config:"generation_config.json"},At)])}else if(Vt===D.Musicgen)Wt=await Promise.all([J(_,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},At),q(_,{generation_config:"generation_config.json"},At)]);else if(Vt===D.MultiModality)Wt=await Promise.all([J(_,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},At),q(_,{generation_config:"generation_config.json"},At)]);else if(Vt===D.Phi3V)Wt=await Promise.all([J(_,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},At),q(_,{generation_config:"generation_config.json"},At)]);else{if(Vt!==D.EncoderOnly){const _s=bs??xe?.model_type;_s!=="custom"&&console.warn(`Model type for '${_s}' not found, assuming encoder-only architecture. Please report this at ${P.GITHUB_ISSUE_URL}.`)}Wt=await Promise.all([J(_,{model:At.model_file_name??"model"},At)])}return new this(xe,...Wt)}async _call(_){return await this.forward(_)}async forward(_){return await this._forward(this,_)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(_){const Y=new b.LogitsProcessorList;return _.temperature!==null&&_.temperature!==1&&Y.push(new b.TemperatureLogitsWarper(_.temperature)),_.top_k!==null&&_.top_k!==0&&Y.push(new b.TopKLogitsWarper(_.top_k)),_.top_p!==null&&_.top_p<1&&Y.push(new b.TopPLogitsWarper(_.top_p)),Y}_get_logits_processor(_,Y,xe=null){const ke=new b.LogitsProcessorList;if(_.repetition_penalty!==null&&_.repetition_penalty!==1&&ke.push(new b.RepetitionPenaltyLogitsProcessor(_.repetition_penalty)),_.no_repeat_ngram_size!==null&&_.no_repeat_ngram_size>0&&ke.push(new b.NoRepeatNGramLogitsProcessor(_.no_repeat_ngram_size)),_.bad_words_ids!==null&&ke.push(new b.NoBadWordsLogitsProcessor(_.bad_words_ids,_.eos_token_id)),_.min_length!==null&&_.eos_token_id!==null&&_.min_length>0&&ke.push(new b.MinLengthLogitsProcessor(_.min_length,_.eos_token_id)),_.min_new_tokens!==null&&_.eos_token_id!==null&&_.min_new_tokens>0&&ke.push(new b.MinNewTokensLengthLogitsProcessor(Y,_.min_new_tokens,_.eos_token_id)),_.forced_bos_token_id!==null&&ke.push(new b.ForcedBOSTokenLogitsProcessor(_.forced_bos_token_id)),_.forced_eos_token_id!==null&&ke.push(new b.ForcedEOSTokenLogitsProcessor(_.max_length,_.forced_eos_token_id)),_.begin_suppress_tokens!==null){const Fe=Y>1||_.forced_bos_token_id===null?Y:Y+1;ke.push(new b.SuppressTokensAtBeginLogitsProcessor(_.begin_suppress_tokens,Fe))}return _.guidance_scale!==null&&_.guidance_scale>1&&ke.push(new b.ClassifierFreeGuidanceLogitsProcessor(_.guidance_scale)),xe!==null&&ke.extend(xe),ke}_prepare_generation_config(_,Y,xe=T.GenerationConfig){const ke={...this.config};for(const st of["decoder","generator","text_config"])st in ke&&Object.assign(ke,ke[st]);const Fe=new xe(ke);return Object.assign(Fe,this.generation_config??{}),_&&Object.assign(Fe,_),Y&&Object.assign(Fe,(0,U.pick)(Y,Object.getOwnPropertyNames(Fe))),Fe}_get_stopping_criteria(_,Y=null){const xe=new re.StoppingCriteriaList;return _.max_length!==null&&xe.push(new re.MaxLengthCriteria(_.max_length,this.config.max_position_embeddings??null)),_.eos_token_id!==null&&xe.push(new re.EosTokenCriteria(_.eos_token_id)),Y&&xe.extend(Y),xe}_validate_model_class(){if(!this.can_generate){const _=[oa,ia,na,ra],Y=C.get(this.constructor),xe=new Set,ke=this.config.model_type;for(const st of _){const rt=st.get(ke);rt&&xe.add(rt[0])}let Fe=`The current model class (${Y}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw xe.size>0&&(Fe+=` Please use the following class instead: ${[...xe].join(", ")}`),Error(Fe)}}prepare_inputs_for_generation(..._){return this._prepare_inputs_for_generation(this,..._)}_update_model_kwargs_for_generation({generated_input_ids:_,outputs:Y,model_inputs:xe,is_encoder_decoder:ke}){return xe.past_key_values=this.getPastKeyValues(Y,xe.past_key_values),xe.input_ids=new v.Tensor("int64",_.flat(),[_.length,1]),ke||(xe.attention_mask=(0,v.cat)([xe.attention_mask,(0,v.ones)([xe.attention_mask.dims[0],1])],1)),xe.position_ids=null,xe}_prepare_model_inputs({inputs:_,bos_token_id:Y,model_kwargs:xe}){const ke=(0,U.pick)(xe,this.forward_params),Fe=this.main_input_name;if(Fe in ke){if(_)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ke[Fe]=_;return{inputs_tensor:ke[Fe],model_inputs:ke,model_input_name:Fe}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:_,model_inputs:Y,model_input_name:xe,generation_config:ke}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Y.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:st,pixel_values:rt,attention_mask:ct,...kt}=Y,Yt=await this._prepare_inputs_embeds(Y);Y={...kt,...(0,U.pick)(Yt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Fe}=await Ge(this,Y);if(ke.guidance_scale!==null&&ke.guidance_scale>1)Fe=(0,v.cat)([Fe,(0,v.full_like)(Fe,0)],0),"attention_mask"in Y&&(Y.attention_mask=(0,v.cat)([Y.attention_mask,(0,v.zeros_like)(Y.attention_mask)],0));else if(Y.decoder_input_ids){const st=Pe(Y.decoder_input_ids).dims[0];if(st!==Fe.dims[0]){if(Fe.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Fe.dims[0]}) than the decoder inputs (${st}).`);Fe=(0,v.cat)(Array.from({length:st},()=>Fe),0)}}return Y.encoder_outputs=Fe,Y}_prepare_decoder_input_ids_for_generation({batch_size:_,model_input_name:Y,model_kwargs:xe,decoder_start_token_id:ke,bos_token_id:Fe,generation_config:st}){let{decoder_input_ids:rt,...ct}=xe;if(!(rt instanceof v.Tensor)){if(rt)Array.isArray(rt[0])||(rt=Array.from({length:_},()=>rt));else if(ke??=Fe,this.config.model_type==="musicgen")rt=Array.from({length:_*this.config.decoder.num_codebooks},()=>[ke]);else if(Array.isArray(ke)){if(ke.length!==_)throw new Error(`\`decoder_start_token_id\` expcted to have length ${_} but got ${ke.length}`);rt=ke}else rt=Array.from({length:_},()=>[ke]);rt=Pe(rt)}return xe.decoder_attention_mask=(0,v.ones_like)(rt),{input_ids:rt,model_inputs:ct}}async generate({inputs:_=null,generation_config:Y=null,logits_processor:xe=null,stopping_criteria:ke=null,streamer:Fe=null,...st}){this._validate_model_class(),Y=this._prepare_generation_config(Y,st);let{inputs_tensor:rt,model_inputs:ct,model_input_name:kt}=this._prepare_model_inputs({inputs:_,model_kwargs:st});const Yt=this.config.is_encoder_decoder;Yt&&("encoder_outputs"in ct||(ct=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:rt,model_inputs:ct,model_input_name:kt,generation_config:Y})));let Ut;Yt?{input_ids:Ut,model_inputs:ct}=this._prepare_decoder_input_ids_for_generation({batch_size:ct[kt].dims.at(0),model_input_name:kt,model_kwargs:ct,decoder_start_token_id:Y.decoder_start_token_id,bos_token_id:Y.bos_token_id,generation_config:Y}):Ut=ct[kt];let Bt=Ut.dims.at(-1);Y.max_new_tokens!==null&&(Y.max_length=Bt+Y.max_new_tokens);const At=this._get_logits_processor(Y,Bt,xe),bs=this._get_stopping_criteria(Y,ke),Vt=ct[kt].dims.at(0),Wt=ae.LogitsSampler.getSampler(Y),_s=new Array(Vt).fill(0),ws=Ut.tolist();Fe&&Fe.put(ws);let es,Is={};for(;;){if(ct=this.prepare_inputs_for_generation(ws,ct,Y),es=await this.forward(ct),Y.output_attentions&&Y.return_dict_in_generate){const lr=this.getAttentions(es);for(const xr in lr)xr in Is||(Is[xr]=[]),Is[xr].push(lr[xr])}const Bs=es.logits.slice(null,-1,null),Xs=At(ws,Bs),ar=[];for(let lr=0;lrlr))break;ct=this._update_model_kwargs_for_generation({generated_input_ids:ar,outputs:es,model_inputs:ct,is_encoder_decoder:Yt})}Fe&&Fe.end();const Os=this.getPastKeyValues(es,ct.past_key_values,!0),ks=new v.Tensor("int64",ws.flat(),[ws.length,ws[0].length]);if(Y.return_dict_in_generate)return{sequences:ks,past_key_values:Os,...Is};for(const Bs of Object.values(es))Bs.location==="gpu-buffer"&&Bs.dispose();return ks}getPastKeyValues(_,Y,xe=!1){const ke=Object.create(null);for(const Fe in _)if(Fe.startsWith("present")){const st=Fe.replace("present","past_key_values"),rt=Fe.includes("encoder");if(rt&&Y?ke[st]=Y[st]:ke[st]=_[Fe],Y&&(!rt||xe)){const ct=Y[st];ct.location==="gpu-buffer"&&ct.dispose()}}return ke}getAttentions(_){const Y={};for(const xe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const ke in _)ke.startsWith(xe)&&(xe in Y||(Y[xe]=[]),Y[xe].push(_[ke]));return Y}addPastKeyValues(_,Y){if(Y)Object.assign(_,Y);else{const ke=(this.sessions.decoder_model_merged??this.sessions.model)?.config?.kv_cache_dtype??"float32",Fe=ke==="float16"?new Uint16Array:[],st=(_[this.main_input_name]??_.attention_mask)?.dims?.[0]??1,rt=(0,g.getKeyValueShapes)(this.config,{batch_size:st});for(const ct in rt)_[ct]=new v.Tensor(ke,Fe,rt[ct])}}async encode_image({pixel_values:_}){const Y=(await ce(this.sessions.vision_encoder,{pixel_values:_})).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 (${Y.dims[1]}).`),this.config.num_image_tokens=Y.dims[1]),Y}async encode_text({input_ids:_}){return(await ce(this.sessions.embed_tokens,{input_ids:_})).inputs_embeds}}class qe{}class Ae extends qe{constructor({last_hidden_state:_,hidden_states:Y=null,attentions:xe=null}){super(),this.last_hidden_state=_,this.hidden_states=Y,this.attentions=xe}}class oe extends ne{}class Me extends oe{}class je extends oe{async _call(_){return new Us(await super._call(_))}}class Re extends oe{async _call(_){return new Ht(await super._call(_))}}class We extends oe{async _call(_){return new Ns(await super._call(_))}}class ze extends oe{async _call(_){return new qs(await super._call(_))}}class Ye extends ne{}class nt extends Ye{}class wt extends ne{}class ut extends wt{}class ht extends wt{async _call(_){return new Us(await super._call(_))}}class I extends wt{async _call(_){return new Ht(await super._call(_))}}class ie extends wt{async _call(_){return new Ns(await super._call(_))}}class X extends wt{async _call(_){return new qs(await super._call(_))}}class _e extends ne{}class $e extends _e{}class He extends _e{async _call(_){return new Us(await super._call(_))}}class et extends _e{async _call(_){return new Ht(await super._call(_))}}class ot extends _e{async _call(_){return new Ns(await super._call(_))}}class yt extends _e{async _call(_){return new qs(await super._call(_))}}class mt extends ne{}class Qt extends mt{}class ts extends mt{async _call(_){return new Us(await super._call(_))}}class xs extends mt{async _call(_){return new Ht(await super._call(_))}}class hs extends mt{async _call(_){return new Ns(await super._call(_))}}class $s extends mt{async _call(_){return new qs(await super._call(_))}}class Ms extends ne{}class Ks extends Ms{}class sr extends Ms{async _call(_){return new Us(await super._call(_))}}class Rr extends Ms{async _call(_){return new Ht(await super._call(_))}}class Cr extends Ms{async _call(_){return new Ns(await super._call(_))}}class an extends Ms{async _call(_){return new qs(await super._call(_))}}class Ot extends ne{}class Nr extends Ot{}class br extends Ot{async _call(_){return new Us(await super._call(_))}}class kr extends Ot{async _call(_){return new Ht(await super._call(_))}}class vr extends Ot{async _call(_){return new Ns(await super._call(_))}}class Sr extends Ot{async _call(_){return new qs(await super._call(_))}}class Js extends ne{}class ur extends Js{}class Tr extends Js{async _call(_){return new Us(await super._call(_))}}class jr extends Js{async _call(_){return new Ht(await super._call(_))}}class rr extends Js{async _call(_){return new Ns(await super._call(_))}}class it extends Js{async _call(_){return new qs(await super._call(_))}}class dt extends ne{}class St extends dt{}class cs extends dt{async _call(_){return new Ht(await super._call(_))}}class Ur extends dt{async _call(_){return new Ns(await super._call(_))}}class rs extends dt{async _call(_){return new qs(await super._call(_))}}class Vr extends dt{async _call(_){return new Us(await super._call(_))}}class $r extends ne{}class qn extends $r{}class Tn extends $r{async _call(_){return new Us(await super._call(_))}}class Wr extends $r{async _call(_){return new Ht(await super._call(_))}}class xn extends $r{async _call(_){return new Ns(await super._call(_))}}class Ar extends ne{}class Pn extends Ar{}class Xn extends Ar{async _call(_){return new Us(await super._call(_))}}class Ir extends Ar{async _call(_){return new Ht(await super._call(_))}}class fr extends Ar{async _call(_){return new qs(await super._call(_))}}class Zs extends ne{}class ln extends Zs{}class Gr extends Zs{async _call(_){return new Us(await super._call(_))}}class un extends Zs{async _call(_){return new Ht(await super._call(_))}}class Kr extends Zs{async _call(_){return new Ns(await super._call(_))}}class dn extends Zs{async _call(_){return new qs(await super._call(_))}}class Ft extends ne{}class cn extends Ft{}class En extends Ft{async _call(_){return new Us(await super._call(_))}}class Cn extends Ft{async _call(_){return new Ht(await super._call(_))}}class kn extends Ft{async _call(_){return new qs(await super._call(_))}}class Or extends ne{}class Sn extends Or{}class pn extends Or{async _call(_){return new Ht(await super._call(_))}}class $n extends Or{async _call(_){return new qs(await super._call(_))}}class ns extends Or{async _call(_){return new Us(await super._call(_))}}class er extends ne{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class hn extends er{}class An extends er{}class Hr extends ne{}class In extends Hr{}class Te extends Hr{}class M extends ne{}class Q extends M{}class pe extends M{}class ge extends ne{}class Ie extends ge{}class Xe extends ge{}class _t extends ge{async _call(_){return new Ht(await super._call(_))}}class ft extends ne{}class vt extends ft{}class Qe extends ft{}class It extends ft{async _call(_){return new Ht(await super._call(_))}}class Xt extends ft{}class gs extends ne{}class Se extends gs{}class Ps extends gs{}class js extends ne{}class Rs extends js{}class dr extends js{}class zt extends ne{}class zs extends zt{}class gr extends zt{async _call(_){return new Us(await super._call(_))}}class Zt extends zt{async _call(_){return new Ht(await super._call(_))}}class us extends zt{async _call(_){return new Ns(await super._call(_))}}class xt extends zt{async _call(_){return new qs(await super._call(_))}}class os extends ne{}class wr extends os{}class As extends os{async _call(_){return new Us(await super._call(_))}}class Vs extends os{async _call(_){return new Ht(await super._call(_))}}class Mt extends os{async _call(_){return new Ns(await super._call(_))}}class Es extends os{async _call(_){return new qs(await super._call(_))}}class Oe extends ne{}class gt extends Oe{}class tr extends Oe{async _call(_){return new Us(await super._call(_))}}class qr extends Oe{async _call(_){return new Ht(await super._call(_))}}class Qn extends Oe{async _call(_){return new Ns(await super._call(_))}}class ka extends Oe{async _call(_){return new qs(await super._call(_))}}class Gt extends ne{}class Sa extends Gt{}class ko extends Gt{}class So extends ne{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class $a extends So{}class Aa extends So{_prepare_generation_config(_,Y){return super._prepare_generation_config(_,Y,G.WhisperGenerationConfig)}_retrieve_init_tokens(_){const Y=[_.decoder_start_token_id];let xe=_.language;const ke=_.task;if(_.is_multilingual){xe||(console.warn("No language specified - defaulting to English (en)."),xe="en");const st=`<|${(0,H.whisper_language_to_code)(xe)}|>`;Y.push(_.lang_to_id[st]),Y.push(_.task_to_id[ke??"transcribe"])}else if(xe||ke)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!_.return_timestamps&&_.no_timestamps_token_id&&Y.at(-1)!==_.no_timestamps_token_id?Y.push(_.no_timestamps_token_id):_.return_timestamps&&Y.at(-1)===_.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),Y.pop()),Y.filter(Fe=>Fe!=null)}async generate({inputs:_=null,generation_config:Y=null,logits_processor:xe=null,stopping_criteria:ke=null,...Fe}){Y=this._prepare_generation_config(Y,Fe);const st=Fe.decoder_input_ids??this._retrieve_init_tokens(Y);if(Y.return_timestamps&&(xe??=new b.LogitsProcessorList,xe.push(new b.WhisperTimeStampLogitsProcessor(Y,st))),Y.begin_suppress_tokens&&(xe??=new b.LogitsProcessorList,xe.push(new b.SuppressTokensAtBeginLogitsProcessor(Y.begin_suppress_tokens,st.length))),Y.return_token_timestamps){if(!Y.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.");Y.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),Y.output_attentions=!0,Y.return_dict_in_generate=!0}const rt=await super.generate({inputs:_,generation_config:Y,logits_processor:xe,decoder_input_ids:st,...Fe});return Y.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,Y.alignment_heads,Y.num_frames)),rt}_extract_token_timestamps(_,Y,xe=null,ke=.02){if(!_.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`.");xe==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let Fe=this.config.median_filter_width;Fe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Fe=7);const st=_.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(Vt,Wt)=>(0,v.cat)(st.map(_s=>_s[Wt]),2)),ct=(0,v.stack)(Y.map(([Vt,Wt])=>{if(Vt>=rt.length)throw new Error(`Layer index ${Vt} is out of bounds for cross attentions (length ${rt.length}).`);return xe?rt[Vt].slice(null,Wt,null,[0,xe]):rt[Vt].slice(null,Wt)})).transpose(1,0,2,3),[kt,Yt]=(0,v.std_mean)(ct,-2,0,!0),Ut=ct.clone();for(let Vt=0;Vt_s[Bs+1]-_s[Bs]),Is=(0,U.mergeArrays)([1],es).map(ks=>!!ks),Os=[];for(let ks=0;ksBt.findIndex(At=>At==Fe)),ct=rt.every(Bt=>Bt===-1),kt=rt.every(Bt=>Bt!==-1);if(!ct&&!kt)throw new Error("Every input should contain either 0 or 1 image token.");if(ct)return{inputs_embeds:_,attention_mask:ke};const Yt=[],Ut=[];for(let Bt=0;BtArray.from({length:_.dims[0]},es=>Array.from({length:_.dims[1]},Is=>1))),bs=Y?Y.tolist():[],Vt=xe?xe.tolist():[];let Wt=0,_s=0;for(let ws=0;wsBt[ws][Fs]==1),Os=es.reduce((ys,Fs,Br)=>(Fs==ct&&ys.push(Br),ys),[]).map(ys=>es[ys+1]),ks=Os.filter(ys=>ys==st).length,Bs=Os.filter(ys=>ys==rt).length;let Xs=[],ar=0,ma=ks,lr=Bs;for(let ys=0;ys_r>ar&&tn==st),Br=es.findIndex((tn,_r)=>_r>ar&&tn==rt),gn=ma>0&&Fs!==-1?Fs:es.length+1,wn=lr>0&&Br!==-1?Br:es.length+1;let Nn,ga,yo,Mo;gn0?(0,K.max)(Xs.at(-1))[0]+1:0;Xs.push(Array.from({length:3*Nd},(tn,_r)=>ya+_r%Nd));const Ma=Nd+ya,vo=Rd*wa*bo,Ip=Array.from({length:vo},(tn,_r)=>Ma+Math.floor(_r/(wa*bo))),ip=Array.from({length:vo},(tn,_r)=>Ma+Math.floor(_r/bo)%wa),ba=Array.from({length:vo},(tn,_r)=>Ma+_r%bo);Xs.push([Ip,ip,ba].flat()),ar=Nn+vo}if(ar0?(0,K.max)(Xs.at(-1))[0]+1:0,Fs=es.length-ar;Xs.push(Array.from({length:3*Fs},(Br,gn)=>ys+gn%Fs))}const xr=Xs.reduce((ys,Fs)=>ys+Fs.length,0),wo=new Array(xr);let _a=0;for(let ys=0;ys<3;++ys)for(let Fs=0;FsUt[Wt%Ut.length]),bs=Array.from({length:Bt[0]},(Vt,Wt)=>(0,K.max)(Ut.subarray(Bt[1]*Wt,Bt[1]*(Wt+1)))[0]+1+Bt[1]);return[new v.Tensor("int64",At,[3,...Bt]),new v.Tensor("int64",bs,[bs.length,1])]}else{const[Ut,Bt]=_.dims,At=BigInt64Array.from({length:3*Ut*Bt},(bs,Vt)=>BigInt(Math.floor(Vt%Bt/Ut)));return[new v.Tensor("int64",At,[3,..._.dims]),(0,v.zeros)([Ut,1])]}}async encode_image({pixel_values:_,image_grid_thw:Y}){return(await ce(this.sessions.vision_encoder,{pixel_values:_,grid_thw:Y})).image_features}_merge_input_ids_with_image_features(_){return lt({image_token_id:this.config.image_token_id,..._})}prepare_inputs_for_generation(_,Y,xe){if(Y.attention_mask&&!Y.position_ids)if(!Y.past_key_values)[Y.position_ids,Y.rope_deltas]=this.get_rope_index(Y.input_ids,Y.image_grid_thw,Y.video_grid_thw,Y.attention_mask);else{Y.pixel_values=null;const ke=BigInt(Object.values(Y.past_key_values)[0].dims.at(-2)),Fe=Y.rope_deltas.map(st=>ke+st);Y.position_ids=(0,v.stack)([Fe,Fe,Fe],0)}return Y}}class si extends ne{}class Tl extends si{}class Fn extends si{}class ri extends ne{}class so extends ri{}class xl extends ri{}class ni extends ne{}class Pl extends ni{}class El extends ni{}class oi extends ne{}class Cl extends oi{}class kl extends oi{}class ii extends ne{}class Sl extends ii{}class $l extends ii{}class ai extends ne{}class Al extends ai{}class Il extends ai{async _call(_){return new Ht(await super._call(_))}}class li extends ne{}class Ol extends li{}class Fl extends li{async _call(_){return new Ht(await super._call(_))}}class ui extends ne{}class Dl extends ui{}class ro extends ne{}class di extends ro{}class Ll extends ro{async _call(_){return new Ht(await super._call(_))}}class zl extends ne{}class Bl extends zl{}class ci extends ne{}class Rl extends ci{}class Nl extends ci{async _call(_){return new Ht(await super._call(_))}}class pi extends ne{}class jl extends pi{}class hi extends ne{}class Ul extends hi{}class rc extends hi{async _call(_){return new Ht(await super._call(_))}}class Vl extends ne{}class Wl extends Vl{async _call(_){return new Bd(await super._call(_))}}class ir extends ne{}class Gl extends ir{}class Kl extends ir{async _call(_){return new Ht(await super._call(_))}}class mi extends ne{}class Hl extends mi{}class ql extends mi{async _call(_){return new Ht(await super._call(_))}}class _i extends ne{}class Xl extends _i{}class Ql extends _i{}class fi extends ne{}class Yl extends fi{}class nc extends fi{}class gi extends ne{}class Jl extends gi{}class Zl extends gi{async _call(_){return new Ht(await super._call(_))}}class no extends ne{}class eu extends no{}class tu extends no{async _call(_){return new Dr(await super._call(_))}}class su extends no{async _call(_){return new Qr(await super._call(_))}}class Dr extends qe{constructor({logits:_,pred_boxes:Y}){super(),this.logits=_,this.pred_boxes=Y}}class Qr extends qe{constructor({logits:_,pred_boxes:Y,pred_masks:xe}){super(),this.logits=_,this.pred_boxes=Y,this.pred_masks=xe}}class Lr extends ne{}class wi extends Lr{}class Yr extends Lr{async _call(_){return new Ws(await super._call(_))}}class Ws extends qe{constructor({logits:_,pred_boxes:Y}){super(),this.logits=_,this.pred_boxes=Y}}class yi extends ne{}class Mi extends yi{}class ru extends yi{async _call(_){return new oc(await super._call(_))}}class oc extends Dr{}class mn extends ne{}class bi extends mn{}class vi extends mn{async _call(_){return new Ht(await super._call(_))}}class Ti extends ne{}class nu extends Ti{}class xi extends Ti{async _call(_){return new Ht(await super._call(_))}}class oo extends ne{}class ou extends oo{}class Pi extends oo{async _call(_){return new Ht(await super._call(_))}}class Ei extends ne{}class io extends Ei{}class Ci extends Ei{async _call(_){return new Ht(await super._call(_))}}class ki extends ne{}class iu extends ki{}class ic extends ki{}class Si extends ne{}class $i extends Si{}class Dn extends Si{}class au extends ne{}class Ai extends au{}class ao extends ne{}class lu extends ao{}class uu extends ao{}class ac extends ao{}class du extends ne{}class cu extends du{}class pu extends ne{}class hu extends pu{}class lo extends pu{}class Ii extends ne{}class uo extends Ii{}class Oi extends Ii{}class Fi extends ne{}class mu extends Fi{}class Di extends ne{}class Li extends Di{}class lc extends Di{async _call(_){return new Ht(await super._call(_))}}class zi extends ne{}class uc extends zi{}class _u extends zi{async _call(_){return new Ht(await super._call(_))}}class Bi extends ne{}class fu extends Bi{}class Ri extends Bi{async _call(_){return new Ht(await super._call(_))}}class Ni extends ne{}class gu extends Ni{}class ji extends Ni{async _call(_){return new wu(await super._call(_))}}class wu extends qe{constructor({logits:_,pred_boxes:Y}){super(),this.logits=_,this.pred_boxes=Y}}class yu extends ne{}class dc extends yu{async get_image_embeddings({pixel_values:_}){return await Ge(this,{pixel_values:_})}async forward(_){if((!_.image_embeddings||!_.image_positional_embeddings)&&(_={..._,...await this.get_image_embeddings(_)}),!_.input_labels&&_.input_points){const xe=_.input_points.dims.slice(0,-1),ke=xe.reduce((Fe,st)=>Fe*st,1);_.input_labels=new v.Tensor("int64",new BigInt64Array(ke).fill(1n),xe)}const Y={image_embeddings:_.image_embeddings,image_positional_embeddings:_.image_positional_embeddings};return _.input_points&&(Y.input_points=_.input_points),_.input_labels&&(Y.input_labels=_.input_labels),_.input_boxes&&(Y.input_boxes=_.input_boxes),await ce(this.sessions.prompt_encoder_mask_decoder,Y)}async _call(_){return new Mu(await super._call(_))}}class Mu extends qe{constructor({iou_scores:_,pred_masks:Y}){super(),this.iou_scores=_,this.pred_masks=Y}}class Ui extends ne{}class bu extends Ui{}class cc extends Ui{}class Vi extends ne{}class vu extends Vi{}class Tu extends Vi{}class zr extends ne{}class xu extends zr{}class pc extends zr{async _call(_){return new en(await super._call(_))}}class co extends zr{async _call(_){return new Ht(await super._call(_))}}class Ln extends zr{async _call(_){return new Ns(await super._call(_))}}class po extends ne{}class Pu extends po{}class Eu extends po{async _call(_){return new Ns(await super._call(_))}}class Cu extends ne{}class ku extends Cu{}class zn extends ne{}class Su extends zn{}class $u extends zn{async _call(_){return new en(await super._call(_))}}class Au extends zn{async _call(_){return new Ht(await super._call(_))}}class ho extends ne{}class Iu extends ho{}class Wi extends ho{async _call(_){return new en(await super._call(_))}}class Ou extends ho{async _call(_){return new Ht(await super._call(_))}}class Fu extends ho{async _call(_){return new Ns(await super._call(_))}}class mo extends ne{}class hc extends mo{}class Du extends mo{async _call(_){return new en(await super._call(_))}}class Lu extends mo{async _call(_){return new Ht(await super._call(_))}}class Ep extends ne{}class zu extends zr{}class Bu extends zr{async _call(_){return new en(await super._call(_))}}class Ru extends zr{async _call(_){return new Ht(await super._call(_))}}class _n extends ne{}class mc extends _n{}class Nu extends _n{async _call(_){return new en(await super._call(_))}}class ju extends _n{async _call(_){return new Ht(await super._call(_))}}class Uu extends _n{async _call(_){return new zd(await super._call(_))}}class _c extends _n{async _call(_){return new Ns(await super._call(_))}}class _o extends ne{}class fc extends _o{}class Vu extends _o{}class Wu extends _o{async generate_speech(_,Y,{threshold:xe=.5,minlenratio:ke=0,maxlenratio:Fe=20,vocoder:st=null}={}){const rt={input_ids:_},{encoder_outputs:ct,encoder_attention_mask:kt}=await Ge(this,rt),Yt=ct.dims[1]/this.config.reduction_factor,Ut=Math.floor(Yt*Fe),Bt=Math.floor(Yt*ke),At=this.config.num_mel_bins;let bs=[],Vt=null,Wt=null,_s=0;for(;;){++_s;const Is=be(!!Wt);let Os;Wt?Os=Wt.output_sequence_out:Os=new v.Tensor("float32",new Float32Array(At),[1,1,At]);let ks={use_cache_branch:Is,output_sequence:Os,encoder_attention_mask:kt,speaker_embeddings:Y,encoder_hidden_states:ct};this.addPastKeyValues(ks,Vt),Wt=await ce(this.sessions.decoder_model_merged,ks),Vt=this.getPastKeyValues(Wt,Vt);const{prob:Bs,spectrum:Xs}=Wt;if(bs.push(Xs),_s>=Bt&&(Array.from(Bs.data).filter(ar=>ar>=xe).length>0||_s>=Ut))break}const ws=(0,v.cat)(bs),{waveform:es}=await ce(st.sessions.model,{spectrogram:ws});return{spectrogram:ws,waveform:es}}}class gc extends ne{main_input_name="spectrogram"}class Gu extends ne{}class Ku extends Gu{}class Gi extends ne{}class Hu extends Gi{}class wc extends Gi{}class Ki extends ne{}class qu extends Ki{}class Xu extends Ki{}class Hi extends ne{}class yc extends Hi{}class yr extends Hi{}class mr extends ne{}class Jr extends mr{}class Zr extends mr{static async from_pretrained(_,Y={}){return super.from_pretrained(_,{model_file_name:"text_model",...Y})}}class Qu extends mr{static async from_pretrained(_,Y={}){return super.from_pretrained(_,{model_file_name:"audio_model",...Y})}}class Yu extends ne{}class qi extends Yu{async _call(_){return new np(await super._call(_))}}class fo extends ne{}class Mc extends fo{}class Ju extends fo{}class Zu extends fo{}class Xi extends ne{}class ed extends Xi{}class td extends Xi{}class sd extends ne{}class Hs extends sd{}class rd extends sd{async _call(_){return new Ht(await super._call(_))}}class Qi extends ne{}class nd extends Qi{}class bc extends Qi{}class fn extends ne{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(_){const[Y,xe]=_.dims,ke=this.config.decoder.num_codebooks,Fe=xe-ke;let st=0;for(let kt=0;kt<_.size;++kt){if(_.data[kt]===this.config.decoder.pad_token_id)continue;const Yt=kt%xe,Ut=Math.floor(kt/xe)%ke,Bt=Yt-Ut;Bt>0&&Bt<=Fe&&(_.data[st++]=_.data[kt])}const rt=Math.floor(Y/ke),ct=st/(rt*ke);return new v.Tensor(_.type,_.data.slice(0,st),[rt,ke,ct])}prepare_inputs_for_generation(_,Y,xe){let ke=structuredClone(_);for(let st=0;st=rt&&(ke[st][rt]=BigInt(this.config.decoder.pad_token_id));return xe.guidance_scale!==null&&xe.guidance_scale>1&&(ke=ke.concat(ke)),super.prepare_inputs_for_generation(ke,Y,xe)}async generate(_){const Y=await super.generate(_),xe=this._apply_and_filter_by_delay_pattern_mask(Y).unsqueeze_(0),{audio_values:ke}=await ce(this.sessions.encodec_decode,{audio_codes:xe});return ke}}class Yi extends ne{}class od extends Yi{}class id extends Yi{async _call(_){return new Ht(await super._call(_))}}class Ji extends ne{}class ad extends Ji{}class ld extends Ji{async _call(_){return new Ht(await super._call(_))}}class go extends ne{}class ud extends go{}class dd extends go{async _call(_){return new Ht(await super._call(_))}}class Zi extends ne{}class cd extends Zi{}class pd extends Zi{async _call(_){return new Ht(await super._call(_))}}class ea extends ne{}class hd extends ea{}class vc extends ne{}class ta extends vc{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(..._){super(..._),this._generation_mode="text"}async forward(_){const Y=this._generation_mode??"text";let xe;if(Y==="text"||!_.past_key_values){const ct=this.sessions.prepare_inputs_embeds,kt=(0,U.pick)(_,ct.inputNames);xe=await ce(ct,kt)}else{const ct=this.sessions.gen_img_embeds,kt=(0,U.pick)({image_ids:_.input_ids},ct.inputNames);xe=await ce(ct,kt)}const ke={..._,...xe},Fe=await Ne(this,ke),st=this.sessions[Y==="text"?"lm_head":"gen_head"];if(!st)throw new Error(`Unable to find "${st}" generation head`);const rt=await ce(st,(0,U.pick)(Fe,st.inputNames));return{...xe,...Fe,...rt}}async generate(_){return this._generation_mode="text",super.generate(_)}async generate_images(_){this._generation_mode="image";const Y=(_.inputs??_[this.main_input_name]).dims[1],ke=(await super.generate(_)).slice(null,[Y,null]),Fe=this.sessions.image_decode,{decoded_image:st}=await ce(Fe,{generated_tokens:ke}),rt=st.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),ct=[];for(const kt of rt){const Yt=z.RawImage.fromTensor(kt);ct.push(Yt)}return ct}}class md extends qe{constructor({char_logits:_,bpe_logits:Y,wp_logits:xe}){super(),this.char_logits=_,this.bpe_logits=Y,this.wp_logits=xe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class _d extends ne{}class fd extends _d{async _call(_){return new md(await super._call(_))}}class gd extends ne{}class wd extends gd{}class yd extends gd{}class sa extends ne{}class Tc extends sa{}class Md extends sa{}class ms{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(_,{progress_callback:Y=null,config:xe=null,cache_dir:ke=null,local_files_only:Fe=!1,revision:st="main",model_file_name:rt=null,subfolder:ct="onnx",device:kt=null,dtype:Yt=null,use_external_data_format:Ut=null,session_options:Bt={}}={}){const At={progress_callback:Y,config:xe,cache_dir:ke,local_files_only:Fe,revision:st,model_file_name:rt,subfolder:ct,device:kt,dtype:Yt,use_external_data_format:Ut,session_options:Bt};if(At.config=await g.AutoConfig.from_pretrained(_,At),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const bs of this.MODEL_CLASS_MAPPINGS){const Vt=bs.get(At.config.model_type);if(Vt)return await Vt[1].from_pretrained(_,At)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${At.config.model_type}", attempting to construct from base class.`),await ne.from_pretrained(_,At);throw Error(`Unsupported model type: ${At.config.model_type}`)}}const Cp=new Map([["bert",["BertModel",Me]],["nomic_bert",["NomicBertModel",nt]],["roformer",["RoFormerModel",ut]],["electra",["ElectraModel",Qt]],["esm",["EsmModel",qn]],["convbert",["ConvBertModel",$e]],["camembert",["CamembertModel",Ks]],["deberta",["DebertaModel",Nr]],["deberta-v2",["DebertaV2Model",ur]],["mpnet",["MPNetModel",ln]],["albert",["AlbertModel",Sn]],["distilbert",["DistilBertModel",St]],["roberta",["RobertaModel",zs]],["xlm",["XLMModel",wr]],["xlm-roberta",["XLMRobertaModel",gt]],["clap",["ClapModel",Jr]],["clip",["CLIPModel",ja]],["clipseg",["CLIPSegModel",Ha]],["chinese_clip",["ChineseCLIPModel",cr]],["siglip",["SiglipModel",Wa]],["jina_clip",["JinaCLIPModel",Zn]],["mobilebert",["MobileBertModel",Pn]],["squeezebert",["SqueezeBertModel",cn]],["wav2vec2",["Wav2Vec2Model",xu]],["wav2vec2-bert",["Wav2Vec2BertModel",hc]],["unispeech",["UniSpeechModel",Su]],["unispeech-sat",["UniSpeechSatModel",Iu]],["hubert",["HubertModel",zu]],["wavlm",["WavLMModel",mc]],["audio-spectrogram-transformer",["ASTModel",Sa]],["vits",["VitsModel",qi]],["pyannote",["PyAnnoteModel",Pu]],["wespeaker-resnet",["WeSpeakerResNetModel",ku]],["detr",["DetrModel",eu]],["rt_detr",["RTDetrModel",wi]],["table-transformer",["TableTransformerModel",Mi]],["vit",["ViTModel",Al]],["ijepa",["IJepaModel",Ol]],["pvt",["PvtModel",di]],["vit_msn",["ViTMSNModel",Rl]],["vit_mae",["ViTMAEModel",Bl]],["groupvit",["GroupViTModel",jl]],["fastvit",["FastViTModel",Ul]],["mobilevit",["MobileViTModel",Gl]],["mobilevitv2",["MobileViTV2Model",Hl]],["owlvit",["OwlViTModel",Xl]],["owlv2",["Owlv2Model",Yl]],["beit",["BeitModel",Jl]],["deit",["DeiTModel",bi]],["hiera",["HieraModel",nu]],["convnext",["ConvNextModel",Li]],["convnextv2",["ConvNextV2Model",uc]],["dinov2",["Dinov2Model",fu]],["resnet",["ResNetModel",ou]],["swin",["SwinModel",io]],["swin2sr",["Swin2SRModel",iu]],["donut-swin",["DonutSwinModel",mu]],["yolos",["YolosModel",gu]],["dpt",["DPTModel",$i]],["glpn",["GLPNModel",uo]],["hifigan",["SpeechT5HifiGan",gc]],["efficientnet",["EfficientNetModel",Hs]],["decision_transformer",["DecisionTransformerModel",hd]],["patchtst",["PatchTSTForPrediction",wd]],["patchtsmixer",["PatchTSMixerForPrediction",Tc]],["mobilenet_v1",["MobileNetV1Model",od]],["mobilenet_v2",["MobileNetV2Model",ad]],["mobilenet_v3",["MobileNetV3Model",ud]],["mobilenet_v4",["MobileNetV4Model",cd]],["maskformer",["MaskFormerModel",hu]],["mgp-str",["MgpstrForSceneTextRecognition",fd]]]),xc=new Map([["t5",["T5Model",hn]],["longt5",["LongT5Model",In]],["mt5",["MT5Model",Q]],["bart",["BartModel",Ie]],["mbart",["MBartModel",vt]],["marian",["MarianModel",bu]],["whisper",["WhisperModel",$a]],["m2m_100",["M2M100Model",vu]],["blenderbot",["BlenderbotModel",Se]],["blenderbot-small",["BlenderbotSmallModel",Rs]]]),Pc=new Map([["bloom",["BloomModel",Pl]],["jais",["JAISModel",Ya]],["gpt2",["GPT2Model",Xa]],["gptj",["GPTJModel",sl]],["gpt_bigcode",["GPTBigCodeModel",nl]],["gpt_neo",["GPTNeoModel",hr]],["gpt_neox",["GPTNeoXModel",el]],["codegen",["CodeGenModel",Uo]],["llama",["LlamaModel",Wo]],["exaone",["ExaoneModel",to]],["olmo",["OlmoModel",ul]],["olmo2",["Olmo2Model",dl]],["mobilellm",["MobileLLMModel",ll]],["granite",["GraniteModel",tc]],["cohere",["CohereModel",hl]],["gemma",["GemmaModel",as]],["gemma2",["Gemma2Model",_l]],["openelm",["OpenELMModel",gl]],["qwen2",["Qwen2Model",yl]],["phi",["PhiModel",Tl]],["phi3",["Phi3Model",so]],["mpt",["MptModel",Cl]],["opt",["OPTModel",Sl]],["mistral",["MistralModel",Hu]],["starcoder2",["Starcoder2Model",qu]],["falcon",["FalconModel",yc]],["stablelm",["StableLmModel",ed]]]),ra=new Map([["speecht5",["SpeechT5ForSpeechToText",Vu]],["whisper",["WhisperForConditionalGeneration",Aa]],["moonshine",["MoonshineForConditionalGeneration",Ia]]]),bd=new Map([["speecht5",["SpeechT5ForTextToSpeech",Wu]]]),vd=new Map([["vits",["VitsModel",qi]],["musicgen",["MusicgenForConditionalGeneration",fn]]]),Ec=new Map([["bert",["BertForSequenceClassification",Re]],["roformer",["RoFormerForSequenceClassification",I]],["electra",["ElectraForSequenceClassification",xs]],["esm",["EsmForSequenceClassification",Wr]],["convbert",["ConvBertForSequenceClassification",et]],["camembert",["CamembertForSequenceClassification",Rr]],["deberta",["DebertaForSequenceClassification",kr]],["deberta-v2",["DebertaV2ForSequenceClassification",jr]],["mpnet",["MPNetForSequenceClassification",un]],["albert",["AlbertForSequenceClassification",pn]],["distilbert",["DistilBertForSequenceClassification",cs]],["roberta",["RobertaForSequenceClassification",Zt]],["xlm",["XLMForSequenceClassification",Vs]],["xlm-roberta",["XLMRobertaForSequenceClassification",qr]],["bart",["BartForSequenceClassification",_t]],["mbart",["MBartForSequenceClassification",It]],["mobilebert",["MobileBertForSequenceClassification",Ir]],["squeezebert",["SqueezeBertForSequenceClassification",Cn]]]),Td=new Map([["bert",["BertForTokenClassification",We]],["roformer",["RoFormerForTokenClassification",ie]],["electra",["ElectraForTokenClassification",hs]],["esm",["EsmForTokenClassification",xn]],["convbert",["ConvBertForTokenClassification",ot]],["camembert",["CamembertForTokenClassification",Cr]],["deberta",["DebertaForTokenClassification",vr]],["deberta-v2",["DebertaV2ForTokenClassification",rr]],["mpnet",["MPNetForTokenClassification",Kr]],["distilbert",["DistilBertForTokenClassification",Ur]],["roberta",["RobertaForTokenClassification",us]],["xlm",["XLMForTokenClassification",Mt]],["xlm-roberta",["XLMRobertaForTokenClassification",Qn]]]),na=new Map([["t5",["T5ForConditionalGeneration",An]],["longt5",["LongT5ForConditionalGeneration",Te]],["mt5",["MT5ForConditionalGeneration",pe]],["bart",["BartForConditionalGeneration",Xe]],["mbart",["MBartForConditionalGeneration",Qe]],["marian",["MarianMTModel",cc]],["m2m_100",["M2M100ForConditionalGeneration",Tu]],["blenderbot",["BlenderbotForConditionalGeneration",Ps]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",dr]]]),oa=new Map([["bloom",["BloomForCausalLM",El]],["gpt2",["GPT2LMHeadModel",Qa]],["jais",["JAISLMHeadModel",Ja]],["gptj",["GPTJForCausalLM",rl]],["gpt_bigcode",["GPTBigCodeForCausalLM",ol]],["gpt_neo",["GPTNeoForCausalLM",Za]],["gpt_neox",["GPTNeoXForCausalLM",tl]],["codegen",["CodeGenForCausalLM",il]],["llama",["LlamaForCausalLM",ec]],["exaone",["ExaoneForCausalLM",al]],["olmo",["OlmoForCausalLM",qo]],["olmo2",["Olmo2ForCausalLM",cl]],["mobilellm",["MobileLLMForCausalLM",On]],["granite",["GraniteForCausalLM",pl]],["cohere",["CohereForCausalLM",sc]],["gemma",["GemmaForCausalLM",ml]],["gemma2",["Gemma2ForCausalLM",fl]],["openelm",["OpenELMForCausalLM",wl]],["qwen2",["Qwen2ForCausalLM",Ml]],["phi",["PhiForCausalLM",Fn]],["phi3",["Phi3ForCausalLM",xl]],["mpt",["MptForCausalLM",kl]],["opt",["OPTForCausalLM",$l]],["mbart",["MBartForCausalLM",Xt]],["mistral",["MistralForCausalLM",wc]],["starcoder2",["Starcoder2ForCausalLM",Xu]],["falcon",["FalconForCausalLM",yr]],["trocr",["TrOCRForCausalLM",Ku]],["stablelm",["StableLmForCausalLM",td]],["phi3_v",["Phi3VForCausalLM",or]]]),Cc=new Map([["multi_modality",["MultiModalityCausalLM",ta]]]),xd=new Map([["bert",["BertForMaskedLM",je]],["roformer",["RoFormerForMaskedLM",ht]],["electra",["ElectraForMaskedLM",ts]],["esm",["EsmForMaskedLM",Tn]],["convbert",["ConvBertForMaskedLM",He]],["camembert",["CamembertForMaskedLM",sr]],["deberta",["DebertaForMaskedLM",br]],["deberta-v2",["DebertaV2ForMaskedLM",Tr]],["mpnet",["MPNetForMaskedLM",Gr]],["albert",["AlbertForMaskedLM",ns]],["distilbert",["DistilBertForMaskedLM",Vr]],["roberta",["RobertaForMaskedLM",gr]],["xlm",["XLMWithLMHeadModel",As]],["xlm-roberta",["XLMRobertaForMaskedLM",tr]],["mobilebert",["MobileBertForMaskedLM",Xn]],["squeezebert",["SqueezeBertForMaskedLM",En]]]),Pd=new Map([["bert",["BertForQuestionAnswering",ze]],["roformer",["RoFormerForQuestionAnswering",X]],["electra",["ElectraForQuestionAnswering",$s]],["convbert",["ConvBertForQuestionAnswering",yt]],["camembert",["CamembertForQuestionAnswering",an]],["deberta",["DebertaForQuestionAnswering",Sr]],["deberta-v2",["DebertaV2ForQuestionAnswering",it]],["mpnet",["MPNetForQuestionAnswering",dn]],["albert",["AlbertForQuestionAnswering",$n]],["distilbert",["DistilBertForQuestionAnswering",rs]],["roberta",["RobertaForQuestionAnswering",xt]],["xlm",["XLMForQuestionAnswering",Es]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ka]],["mobilebert",["MobileBertForQuestionAnswering",fr]],["squeezebert",["SqueezeBertForQuestionAnswering",kn]]]),ia=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ao]],["idefics3",["Idefics3ForConditionalGeneration",Io]]]),kc=new Map([["llava",["LlavaForConditionalGeneration",Yn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Oa]],["moondream1",["Moondream1ForConditionalGeneration",Fa]],["florence2",["Florence2ForConditionalGeneration",La]],["qwen2-vl",["Qwen2VLForConditionalGeneration",vl]],["idefics3",["Idefics3ForConditionalGeneration",Io]],["paligemma",["PaliGemmaForConditionalGeneration",Ba]]]),Sc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ao]]]),$c=new Map([["vit",["ViTForImageClassification",Il]],["ijepa",["IJepaForImageClassification",Fl]],["pvt",["PvtForImageClassification",Ll]],["vit_msn",["ViTMSNForImageClassification",Nl]],["fastvit",["FastViTForImageClassification",rc]],["mobilevit",["MobileViTForImageClassification",Kl]],["mobilevitv2",["MobileViTV2ForImageClassification",ql]],["beit",["BeitForImageClassification",Zl]],["deit",["DeiTForImageClassification",vi]],["hiera",["HieraForImageClassification",xi]],["convnext",["ConvNextForImageClassification",lc]],["convnextv2",["ConvNextV2ForImageClassification",_u]],["dinov2",["Dinov2ForImageClassification",Ri]],["resnet",["ResNetForImageClassification",Pi]],["swin",["SwinForImageClassification",Ci]],["segformer",["SegformerForImageClassification",Ju]],["efficientnet",["EfficientNetForImageClassification",rd]],["mobilenet_v1",["MobileNetV1ForImageClassification",id]],["mobilenet_v2",["MobileNetV2ForImageClassification",ld]],["mobilenet_v3",["MobileNetV3ForImageClassification",dd]],["mobilenet_v4",["MobileNetV4ForImageClassification",pd]]]),Bn=new Map([["detr",["DetrForObjectDetection",tu]],["rt_detr",["RTDetrForObjectDetection",Yr]],["table-transformer",["TableTransformerForObjectDetection",ru]],["yolos",["YolosForObjectDetection",ji]]]),aa=new Map([["owlvit",["OwlViTForObjectDetection",Ql]],["owlv2",["Owlv2ForObjectDetection",nc]]]),la=new Map([["detr",["DetrForSegmentation",su]],["clipseg",["CLIPSegForImageSegmentation",qa]]]),ua=new Map([["segformer",["SegformerForSemanticSegmentation",Zu]],["sapiens",["SapiensForSemanticSegmentation",lu]]]),da=new Map([["detr",["DetrForSegmentation",su]],["maskformer",["MaskFormerForInstanceSegmentation",lo]]]),Ed=new Map([["sam",["SamModel",dc]]]),Cd=new Map([["wav2vec2",["Wav2Vec2ForCTC",pc]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Du]],["unispeech",["UniSpeechForCTC",$u]],["unispeech-sat",["UniSpeechSatForCTC",Wi]],["wavlm",["WavLMForCTC",Nu]],["hubert",["HubertForCTC",Bu]]]),ca=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",co]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Lu]],["unispeech",["UniSpeechForSequenceClassification",Au]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ou]],["wavlm",["WavLMForSequenceClassification",ju]],["hubert",["HubertForSequenceClassification",Ru]],["audio-spectrogram-transformer",["ASTForAudioClassification",ko]]]),pa=new Map([["wavlm",["WavLMForXVector",Uu]]]),kd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Fu]],["wavlm",["WavLMForAudioFrameClassification",_c]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ln]],["pyannote",["PyAnnoteForAudioFrameClassification",Eu]]]),Sd=new Map([["vitmatte",["VitMatteForImageMatting",Wl]]]),$d=new Map([["patchtst",["PatchTSTForPrediction",yd]],["patchtsmixer",["PatchTSMixerForPrediction",Md]]]),Ad=new Map([["swin2sr",["Swin2SRForImageSuperResolution",ic]]]),Id=new Map([["dpt",["DPTForDepthEstimation",Dn]],["depth_anything",["DepthAnythingForDepthEstimation",Ai]],["glpn",["GLPNForDepthEstimation",Oi]],["sapiens",["SapiensForDepthEstimation",uu]],["depth_pro",["DepthProForDepthEstimation",cu]]]),ha=new Map([["sapiens",["SapiensForNormalEstimation",ac]]]),Od=new Map([["vitpose",["VitPoseForPoseEstimation",Dl]]]),Fd=new Map([["clip",["CLIPVisionModelWithProjection",Va]],["siglip",["SiglipVisionModel",Ka]],["jina_clip",["JinaCLIPVisionModel",pr]]]),Dd=[[Cp,D.EncoderOnly],[xc,D.EncoderDecoder],[Pc,D.DecoderOnly],[Ec,D.EncoderOnly],[Td,D.EncoderOnly],[na,D.Seq2Seq],[ra,D.Seq2Seq],[oa,D.DecoderOnly],[Cc,D.MultiModality],[xd,D.EncoderOnly],[Pd,D.EncoderOnly],[ia,D.Vision2Seq],[kc,D.ImageTextToText],[$c,D.EncoderOnly],[la,D.EncoderOnly],[da,D.EncoderOnly],[ua,D.EncoderOnly],[Sd,D.EncoderOnly],[$d,D.EncoderOnly],[Ad,D.EncoderOnly],[Id,D.EncoderOnly],[ha,D.EncoderOnly],[Od,D.EncoderOnly],[Bn,D.EncoderOnly],[aa,D.EncoderOnly],[Ed,D.MaskGeneration],[Cd,D.EncoderOnly],[ca,D.EncoderOnly],[bd,D.Seq2Seq],[vd,D.EncoderOnly],[pa,D.EncoderOnly],[kd,D.EncoderOnly],[Fd,D.EncoderOnly]];for(const[f,_]of Dd)for(const[Y,xe]of f.values())$.set(Y,_),C.set(xe,Y),w.set(Y,xe);const Ac=[["MusicgenForConditionalGeneration",fn,D.Musicgen],["Phi3VForCausalLM",or,D.Phi3V],["CLIPTextModelWithProjection",Ua,D.EncoderOnly],["SiglipTextModel",Ga,D.EncoderOnly],["JinaCLIPTextModel",Fo,D.EncoderOnly],["ClapTextModelWithProjection",Zr,D.EncoderOnly],["ClapAudioModelWithProjection",Qu,D.EncoderOnly]];for(const[f,_,Y]of Ac)$.set(f,Y),C.set(_,f),w.set(f,_);class kp extends ms{static MODEL_CLASS_MAPPINGS=Dd.map(_=>_[0]);static BASE_IF_FAIL=!0}class Ic extends ms{static MODEL_CLASS_MAPPINGS=[Ec]}class Oc extends ms{static MODEL_CLASS_MAPPINGS=[Td]}class Fc extends ms{static MODEL_CLASS_MAPPINGS=[na]}class Dc extends ms{static MODEL_CLASS_MAPPINGS=[ra]}class Sp extends ms{static MODEL_CLASS_MAPPINGS=[bd]}class Lc extends ms{static MODEL_CLASS_MAPPINGS=[vd]}class zc extends ms{static MODEL_CLASS_MAPPINGS=[oa]}class Bc extends ms{static MODEL_CLASS_MAPPINGS=[xd]}class $p extends ms{static MODEL_CLASS_MAPPINGS=[Pd]}class Rc extends ms{static MODEL_CLASS_MAPPINGS=[ia]}class Nc extends ms{static MODEL_CLASS_MAPPINGS=[$c]}class jc extends ms{static MODEL_CLASS_MAPPINGS=[la]}class Uc extends ms{static MODEL_CLASS_MAPPINGS=[ua]}class Ap extends ms{static MODEL_CLASS_MAPPINGS=[da]}class Vc extends ms{static MODEL_CLASS_MAPPINGS=[Bn]}class Wc extends ms{static MODEL_CLASS_MAPPINGS=[aa]}class Gc extends ms{static MODEL_CLASS_MAPPINGS=[Ed]}class Kc extends ms{static MODEL_CLASS_MAPPINGS=[Cd]}class Hc extends ms{static MODEL_CLASS_MAPPINGS=[ca]}class qc extends ms{static MODEL_CLASS_MAPPINGS=[pa]}class Xc extends ms{static MODEL_CLASS_MAPPINGS=[kd]}class Qc extends ms{static MODEL_CLASS_MAPPINGS=[Sc]}class Yc extends ms{static MODEL_CLASS_MAPPINGS=[Sd]}class Jc extends ms{static MODEL_CLASS_MAPPINGS=[Ad]}class Zc extends ms{static MODEL_CLASS_MAPPINGS=[Id]}class Ld extends ms{static MODEL_CLASS_MAPPINGS=[ha]}class ep extends ms{static MODEL_CLASS_MAPPINGS=[Od]}class tp extends ms{static MODEL_CLASS_MAPPINGS=[Fd]}class sp extends qe{constructor({logits:_,past_key_values:Y,encoder_outputs:xe,decoder_attentions:ke=null,cross_attentions:Fe=null}){super(),this.logits=_,this.past_key_values=Y,this.encoder_outputs=xe,this.decoder_attentions=ke,this.cross_attentions=Fe}}class Ht extends qe{constructor({logits:_}){super(),this.logits=_}}class zd extends qe{constructor({logits:_,embeddings:Y}){super(),this.logits=_,this.embeddings=Y}}class Ns extends qe{constructor({logits:_}){super(),this.logits=_}}class Us extends qe{constructor({logits:_}){super(),this.logits=_}}class qs extends qe{constructor({start_logits:_,end_logits:Y}){super(),this.start_logits=_,this.end_logits=Y}}class en extends qe{constructor({logits:_}){super(),this.logits=_}}class rp extends qe{constructor({logits:_,past_key_values:Y}){super(),this.logits=_,this.past_key_values=Y}}class Bd extends qe{constructor({alphas:_}){super(),this.alphas=_}}class np extends qe{constructor({waveform:_,spectrogram:Y}){super(),this.waveform=_,this.spectrogram=Y}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Ce,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>j});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var O=r("./src/utils/audio.js");class j extends g.FeatureExtractor{constructor(U){super(U);const y=this.config.sampling_rate,P=(0,O.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(y/2),y,null,"kaldi",!0);for(let b=0;b{r.r(A),r.d(A,{AutoFeatureExtractor:()=>te});var g=r("./src/utils/constants.js"),O=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var j=r("./src/models/feature_extractors.js");class te{static async from_pretrained(y,P={}){const b=await(0,O.getModelJSON)(y,g.FEATURE_EXTRACTOR_NAME,!0,P),T=b.feature_extractor_type,v=j[T];if(!v)throw new Error(`Unknown feature_extractor_type: '${T}'. Please report this at ${g.GITHUB_ISSUE_URL}.`);return new v(b)}}},"./src/models/auto/image_processing_auto.js":(Ce,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>U});var g=r("./src/utils/constants.js"),O=r("./src/utils/hub.js"),j=r("./src/base/image_processors_utils.js"),te=r("./src/models/image_processors.js");class U{static async from_pretrained(P,b={}){const T=await(0,O.getModelJSON)(P,g.IMAGE_PROCESSOR_NAME,!0,b),v=T.image_processor_type??T.feature_extractor_type;let z=te[v];return z||(v!==void 0&&console.warn(`Image processor type '${v}' not found, assuming base ImageProcessor. Please report this at ${g.GITHUB_ISSUE_URL}.`),z=j.ImageProcessor),new z(T)}}},"./src/models/auto/processing_auto.js":(Ce,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>P});var g=r("./src/utils/constants.js"),O=r("./src/utils/hub.js"),j=r("./src/base/processing_utils.js"),te=r("./src/models/processors.js"),U=r("./src/models/image_processors.js"),y=r("./src/models/feature_extractors.js");class P{static async from_pretrained(T,v={}){const z=await(0,O.getModelJSON)(T,g.IMAGE_PROCESSOR_NAME,!0,v),{image_processor_type:K,feature_extractor_type:re,processor_class:ae}=z;if(ae&&te[ae])return te[ae].from_pretrained(T,v);if(!K&&!re)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const R={};if(K){const H=U[K];if(!H)throw new Error(`Unknown image_processor_type: '${K}'.`);R.image_processor=new H(z)}if(re){const H=U[re];if(H)R.image_processor=new H(z);else{const D=y[re];if(!D)throw new Error(`Unknown feature_extractor_type: '${re}'.`);R.feature_extractor=new D(z)}}const G={};return new j.Processor(G,R)}}},"./src/models/beit/image_processing_beit.js":(Ce,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Ce,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Ce,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Ce,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>j});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var O=r("./src/utils/audio.js");class j extends g.FeatureExtractor{constructor(U){super(U),this.mel_filters=(0,O.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,O.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,O.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(U,y,P,b){let T;const v=U.length-y;if(v>0)if(P==="rand_trunc"){const z=Math.floor(Math.random()*(v+1));U=U.subarray(z,z+y),T=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${P}" not implemented`);else{if(v<0){let z=new Float64Array(y);if(z.set(U),b==="repeat")for(let K=U.length;K{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>j,CLIPImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/convnext/image_processing_convnext.js":(Ce,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>j,ConvNextImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){const y=this.size?.shortest_edge;if(y===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(y<384){const P=Math.floor(y/this.crop_pct),[b,T]=this.get_resize_output_image_size(U,{shortest_edge:P});U=await U.resize(b,T,{resample:this.resample}),U=await U.center_crop(y,y)}else U=await U.resize(y,y,{resample:this.resample});return U}}class j extends O{}},"./src/models/deit/image_processing_deit.js":(Ce,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>j,DeiTImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/detr/image_processing_detr.js":(Ce,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>te,DetrImageProcessor:()=>j});var g=r("./src/base/image_processors_utils.js"),O=r("./src/utils/tensor.js");class j extends g.ImageProcessor{async _call(y){const P=await super._call(y),b=[P.pixel_values.dims[0],64,64],T=(0,O.full)(b,1n);return{...P,pixel_mask:T}}post_process_object_detection(...y){return(0,g.post_process_object_detection)(...y)}post_process_panoptic_segmentation(...y){return(0,g.post_process_panoptic_segmentation)(...y)}post_process_instance_segmentation(...y){return(0,g.post_process_instance_segmentation)(...y)}}class te extends j{}},"./src/models/donut/image_processing_donut.js":(Ce,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>j,DonutImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{pad_image(U,y,P,b={}){const[T,v,z]=y;let K=this.image_mean;Array.isArray(this.image_mean)||(K=new Array(z).fill(K));let re=this.image_std;Array.isArray(re)||(re=new Array(z).fill(K));const ae=K.map((R,G)=>-R/re[G]);return super.pad_image(U,y,P,{center:!0,constant_values:ae,...b})}}class j extends O{}},"./src/models/dpt/image_processing_dpt.js":(Ce,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>j,DPTImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Ce,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{constructor(te){super(te),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(U=>U*U))}}},"./src/models/feature_extractors.js":(Ce,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>g.ASTFeatureExtractor,ClapFeatureExtractor:()=>O.ClapFeatureExtractor,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>j.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>te.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>U.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>P.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>b.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>T.WhisperFeatureExtractor});var g=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),O=r("./src/models/clap/feature_extraction_clap.js"),j=r("./src/models/moonshine/feature_extraction_moonshine.js"),te=r("./src/models/pyannote/feature_extraction_pyannote.js"),U=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),y=r("./src/models/speecht5/feature_extraction_speecht5.js"),P=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),b=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),T=r("./src/models/whisper/feature_extraction_whisper.js"),v=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Ce,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>te});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class te extends g.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=O.AutoImageProcessor;constructor(y,P){super(y,P);const{tasks_answer_post_processing_type:b,task_prompts_without_inputs:T,task_prompts_with_input:v}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(b??{})),this.task_prompts_without_inputs=new Map(Object.entries(T??{})),this.task_prompts_with_input=new Map(Object.entries(v??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(y){typeof y=="string"&&(y=[y]);const P=[];for(const b of y)if(this.task_prompts_without_inputs.has(b))P.push(this.task_prompts_without_inputs.get(b));else{for(const[T,v]of this.task_prompts_with_input)if(b.includes(T)){P.push(v.replaceAll("{input}",b).replaceAll(T,""));break}P.length!==y.length&&P.push(b)}return P}post_process_generation(y,P,b){const T=this.tasks_answer_post_processing_type.get(P)??"pure_text";y=y.replaceAll("","").replaceAll("","");let v;switch(T){case"pure_text":v=y;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const z=T==="ocr"?"quad_boxes":"bboxes",K=y.matchAll(this.regexes[z]),re=[],ae=[];for(const[R,G,...H]of K)re.push(G?G.trim():re.at(-1)??""),ae.push(H.map((D,$)=>(Number(D)+.5)/this.size_per_bin*b[$%2]));v={labels:re,[z]:ae};break;default:throw new Error(`Task "${P}" (of type "${T}") not yet implemented.`)}return{[P]:v}}async _call(y,P=null,b={}){if(!y&&!P)throw new Error("Either text or images must be provided");const T=await this.image_processor(y,b),v=P?this.tokenizer(P,b):{};return{...T,...v}}}},"./src/models/glpn/image_processing_glpn.js":(Ce,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(Ce,A,r)=>{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>j});var g=r("./src/base/image_processors_utils.js"),O=r("./src/utils/tensor.js");class j extends g.ImageProcessor{constructor(U){super(U),this.do_image_splitting=U.do_image_splitting??!0,this.max_image_size=U.max_image_size}get_resize_for_vision_encoder(U,y){let[P,b]=U.dims.slice(-2);const T=b/P;return b>=P?(b=Math.ceil(b/y)*y,P=Math.floor(b/T),P=Math.ceil(P/y)*y):(P=Math.ceil(P/y)*y,b=Math.floor(P*T),b=Math.ceil(b/y)*y),{height:P,width:b}}async _call(U,{do_image_splitting:y=null,return_row_col_info:P=!1}={}){let b;if(!Array.isArray(U))b=[[U]];else{if(U.length===0||!U[0])throw new Error("No images provided.");Array.isArray(U[0])?b=U:b=[U]}let T=[],v=[],z=[];const K=[],re=[];for(const C of b){let x=await Promise.all(C.map(le=>this.preprocess(le)));K.push(...x.map(le=>le.original_size)),re.push(...x.map(le=>le.reshaped_input_size)),x.forEach(le=>le.pixel_values.unsqueeze_(0));const{longest_edge:J}=this.max_image_size;let q;if(y??this.do_image_splitting){let le=new Array(x.length),ce=new Array(x.length);q=await Promise.all(x.map(async(fe,Pe)=>{const be=this.get_resize_for_vision_encoder(fe.pixel_values,J),De=await(0,O.interpolate_4d)(fe.pixel_values,{size:[be.height,be.width]}),{frames:Ge,num_splits_h:Ne,num_splits_w:lt}=await this.split_image(De,this.max_image_size);return le[Pe]=Ne,ce[Pe]=lt,(0,O.cat)(Ge,0)})),v.push(le),z.push(ce)}else{const le=[J,J];q=await Promise.all(x.map(ce=>(0,O.interpolate_4d)(ce.pixel_values,{size:le}))),v.push(new Array(x.length).fill(0)),z.push(new Array(x.length).fill(0))}T.push((0,O.cat)(q,0))}const ae=T.length,[R,G,H,D]=T[0].dims;let $,w;if(ae===1)$=T[0].unsqueeze_(0),w=(0,O.full)([ae,R,H,D],!0);else{const C=Math.max(...T.map(q=>q.dims.at(0)));w=(0,O.full)([ae,C,H,D],!0);const x=w.data,J=C*H*D;for(let q=0;qP||z>b){K=Math.ceil(v/P),re=Math.ceil(z/b);const ae=Math.ceil(v/K),R=Math.ceil(z/re);for(let D=0;D{r.r(A),r.d(A,{Idefics3Processor:()=>b});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");var te=r("./src/utils/core.js");function U(T,v,z,K,re,ae){let R="";for(let G=0;G`+re.repeat(T);R+=` +`}return R+=` +${K}${ae}`+re.repeat(T)+`${K}`,R}function y(T,v,z,K){return`${v}${K}`+z.repeat(T)+`${v}`}function P(T,v,z,K,re,ae){return T===0&&v===0?y(z,K,re,ae):U(z,T,v,K,re,ae)}class b extends g.Processor{static image_processor_class=O.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(v,z=null,K={}){K.return_row_col_info??=!0;let re;z&&(re=await this.image_processor(z,K)),Array.isArray(v)||(v=[v]);const ae=re.rows??[new Array(v.length).fill(0)],R=re.cols??[new Array(v.length).fill(0)],G=this.config.image_seq_len,H=[],D=[];for(let w=0;wP(fe,J[Pe],G,this.fake_image_token,this.image_token,this.global_img_token)),le=C.split(this.image_token);if(le.length===0)throw new Error("The image token should be present in the text.");let ce=le[0];for(let fe=0;fe{r.r(A),r.d(A,{BeitFeatureExtractor:()=>g.BeitFeatureExtractor,BitImageProcessor:()=>O.BitImageProcessor,CLIPFeatureExtractor:()=>te.CLIPFeatureExtractor,CLIPImageProcessor:()=>te.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>j.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>U.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>U.ConvNextImageProcessor,DPTFeatureExtractor:()=>T.DPTFeatureExtractor,DPTImageProcessor:()=>T.DPTImageProcessor,DeiTFeatureExtractor:()=>y.DeiTFeatureExtractor,DeiTImageProcessor:()=>y.DeiTImageProcessor,DetrFeatureExtractor:()=>P.DetrFeatureExtractor,DetrImageProcessor:()=>P.DetrImageProcessor,DonutFeatureExtractor:()=>b.DonutFeatureExtractor,DonutImageProcessor:()=>b.DonutImageProcessor,EfficientNetImageProcessor:()=>v.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>z.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>K.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>ae.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>R.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>G.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>H.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>H.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>D.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>D.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>$.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>$.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>w.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>w.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>x.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>x.MobileViTImageProcessor,NougatImageProcessor:()=>J.NougatImageProcessor,OwlViTFeatureExtractor:()=>le.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>le.OwlViTImageProcessor,Owlv2ImageProcessor:()=>q.Owlv2ImageProcessor,Phi3VImageProcessor:()=>ce.Phi3VImageProcessor,PvtImageProcessor:()=>fe.PvtImageProcessor,Qwen2VLImageProcessor:()=>Pe.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>be.RTDetrImageProcessor,SamImageProcessor:()=>De.SamImageProcessor,SegformerFeatureExtractor:()=>Ge.SegformerFeatureExtractor,SegformerImageProcessor:()=>Ge.SegformerImageProcessor,SiglipImageProcessor:()=>Ne.SiglipImageProcessor,Swin2SRImageProcessor:()=>lt.Swin2SRImageProcessor,VLMImageProcessor:()=>re.VLMImageProcessor,ViTFeatureExtractor:()=>ue.ViTFeatureExtractor,ViTImageProcessor:()=>ue.ViTImageProcessor,VitMatteImageProcessor:()=>Z.VitMatteImageProcessor,VitPoseImageProcessor:()=>he.VitPoseImageProcessor,YolosFeatureExtractor:()=>ve.YolosFeatureExtractor,YolosImageProcessor:()=>ve.YolosImageProcessor});var g=r("./src/models/beit/image_processing_beit.js"),O=r("./src/models/bit/image_processing_bit.js"),j=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),te=r("./src/models/clip/image_processing_clip.js"),U=r("./src/models/convnext/image_processing_convnext.js"),y=r("./src/models/deit/image_processing_deit.js"),P=r("./src/models/detr/image_processing_detr.js"),b=r("./src/models/donut/image_processing_donut.js"),T=r("./src/models/dpt/image_processing_dpt.js"),v=r("./src/models/efficientnet/image_processing_efficientnet.js"),z=r("./src/models/glpn/image_processing_glpn.js"),K=r("./src/models/idefics3/image_processing_idefics3.js"),re=r("./src/models/janus/image_processing_janus.js"),ae=r("./src/models/jina_clip/image_processing_jina_clip.js"),R=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),G=r("./src/models/mask2former/image_processing_mask2former.js"),H=r("./src/models/maskformer/image_processing_maskformer.js"),D=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),$=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),w=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),x=r("./src/models/mobilevit/image_processing_mobilevit.js"),J=r("./src/models/nougat/image_processing_nougat.js"),q=r("./src/models/owlv2/image_processing_owlv2.js"),le=r("./src/models/owlvit/image_processing_owlvit.js"),ce=r("./src/models/phi3_v/image_processing_phi3_v.js"),fe=r("./src/models/pvt/image_processing_pvt.js"),Pe=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),be=r("./src/models/rt_detr/image_processing_rt_detr.js"),De=r("./src/models/sam/image_processing_sam.js"),Ge=r("./src/models/segformer/image_processing_segformer.js"),Ne=r("./src/models/siglip/image_processing_siglip.js"),lt=r("./src/models/swin2sr/image_processing_swin2sr.js"),ue=r("./src/models/vit/image_processing_vit.js"),Z=r("./src/models/vitmatte/image_processing_vitmatte.js"),he=r("./src/models/vitpose/image_processing_vitpose.js"),ve=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Ce,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{constructor(te){super({do_pad:!0,pad_size:{width:te.image_size,height:te.image_size},...te}),this.constant_values=this.config.background_color.map(U=>U*this.rescale_factor)}pad_image(te,U,y,P){return super.pad_image(te,U,y,{constant_values:this.constant_values,center:!0,...P})}}},"./src/models/janus/processing_janus.js":(Ce,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>P});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),te=r("./src/utils/core.js"),U=r("./src/utils/tensor.js"),y=r("./src/utils/image.js");class P extends g.Processor{static image_processor_class=O.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;static uses_processor_config=!0;constructor(T,v){super(T,v),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(T,{images:v=null,chat_template:z="default"}={}){v?Array.isArray(v)||(v=[v]):v=await Promise.all(T.filter(q=>q.images).flatMap(q=>q.images).map(q=>y.RawImage.read(q)));const K=this.tokenizer,re=K.apply_chat_template(T,{tokenize:!1,add_generation_prompt:!0,chat_template:z}),ae=q=>K.encode(q,{add_special_tokens:!1}),R=re.split(this.image_tag),G=R.length-1;if(v.length!==G)throw new Error(`Number of images provided (${v.length}) does not match number of "${this.image_tag}" image tags (${G})`);const[H,D,$]=K.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=ae(R[0]),C=new Array(w.length).fill(!1);for(let q=1;q0){const q=await this.image_processor(v);return q.pixel_values.unsqueeze_(0),{...J,...q}}return J}}},"./src/models/jina_clip/image_processing_jina_clip.js":(Ce,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{constructor(te){const{resize_mode:U,fill_color:y,interpolation:P,size:b,...T}=te,v=U==="squash"?{width:b,height:b}:U==="shortest"?{shortest_edge:b}:{longest_edge:b},z=P==="bicubic"?3:2;super({...T,size:v,resample:z,do_center_crop:!0,crop_size:b,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Ce,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>te});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class te extends g.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=O.AutoImageProcessor;async _call(y=null,P=null,b={}){if(!y&&!P)throw new Error("Either text or images must be provided");const T=y?this.tokenizer(y,b):{},v=P?await this.image_processor(P,b):{};return{...T,...v}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Ce,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Ce,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>O});var g=r("./src/models/maskformer/image_processing_maskformer.js");class O extends g.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Ce,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>j,MaskFormerImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{post_process_panoptic_segmentation(...U){return(0,g.post_process_panoptic_segmentation)(...U)}post_process_instance_segmentation(...U){return(0,g.post_process_instance_segmentation)(...U)}}class j extends O{}},"./src/models/mgp_str/processing_mgp_str.js":(Ce,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>y});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),te=r("./src/utils/maths.js");const U={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class y extends g.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=O.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(b,T){if(!U.hasOwnProperty(T))throw new Error(`Format ${T} is not supported.`);const[v,z]=U[T],K=this[v].bind(this),[re,ae]=b.dims,R=[],G=[],H=b.tolist();for(let $=0;$0?x.reduce((q,le)=>q*le,1):0;G.push(C),R.push(J)}return[K(G),R]}char_decode(b){return this.char_tokenizer.batch_decode(b).map(T=>T.replaceAll(" ",""))}bpe_decode(b){return this.bpe_tokenizer.batch_decode(b)}wp_decode(b){return this.wp_tokenizer.batch_decode(b).map(T=>T.replaceAll(" ",""))}batch_decode([b,T,v]){const[z,K]=this._decode_helper(b,"char"),[re,ae]=this._decode_helper(T,"bpe"),[R,G]=this._decode_helper(v,"wp"),H=[],D=[];for(let $=0;${r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>j,MobileNetV1ImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Ce,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>j,MobileNetV2ImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Ce,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>j,MobileNetV3ImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Ce,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>j,MobileNetV4ImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Ce,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>j,MobileViTImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/moonshine/feature_extraction_moonshine.js":(Ce,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>j});var g=r("./src/base/feature_extraction_utils.js"),O=r("./src/utils/tensor.js");class j extends g.FeatureExtractor{async _call(U){(0,g.validate_audio_inputs)(U,"MoonshineFeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));const y=[1,U.length];return{input_values:new O.Tensor("float32",U,y)}}}},"./src/models/moonshine/processing_moonshine.js":(Ce,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>te});var g=r("./src/models/auto/feature_extraction_auto.js"),O=r("./src/tokenizers.js"),j=r("./src/base/processing_utils.js");class te extends j.Processor{static tokenizer_class=O.AutoTokenizer;static feature_extractor_class=g.AutoFeatureExtractor;async _call(y){return await this.feature_extractor(y)}}},"./src/models/nougat/image_processing_nougat.js":(Ce,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>O});var g=r("./src/models/donut/image_processing_donut.js");class O extends g.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Ce,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>O});var g=r("./src/models/owlvit/image_processing_owlvit.js");class O extends g.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Ce,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>j,OwlViTImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{post_process_object_detection(...U){return(0,g.post_process_object_detection)(...U)}}class j extends O{}},"./src/models/owlvit/processing_owlvit.js":(Ce,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>te});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class te extends g.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=O.AutoImageProcessor}},"./src/models/paligemma/processing_paligemma.js":(Ce,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>y});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");const te="";function U(P,b,T,v,z){return`${v.repeat(T*z)}${b}${P} +`}class y extends g.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=O.AutoImageProcessor;static uses_processor_config=!1;async _call(b,T=null,v={}){T||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),T=""),Array.isArray(b)||(b=[b]),Array.isArray(T)||(T=[T]);const z=this.tokenizer.bos_token,K=this.image_processor.config.image_seq_length;let re;T.some(G=>G.includes(te))?re=T.map(G=>{const H=G.replaceAll(te,te.repeat(K)),D=H.lastIndexOf(te),$=D===-1?0:D+te.length;return H.slice(0,$)+z+H.slice($)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),re=T.map(G=>U(G,z,K,te,b.length)));const ae=this.tokenizer(re,v);return{...await this.image_processor(b,v),...ae}}}},"./src/models/phi3_v/image_processing_phi3_v.js":(Ce,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>b});var g=r("./src/base/image_processors_utils.js"),O=r("./src/utils/tensor.js");const j=336,te=[2,3],{ceil:U,floor:y,sqrt:P}=Math;class b extends g.ImageProcessor{constructor(v){super({...v,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=v.num_crops}calc_num_image_tokens_from_image_size(v,z){const{num_img_tokens:K}=this.config;return y((y(z/j)*y(v/j)+1)*K+1+(y(z/j)+1)*P(K))}get_resize_output_image_size(v,z){const K=this._num_crops,[re,ae]=v.size;let R=re/ae,G=1;for(;G*Math.ceil(G/R)<=K;)G+=1;G-=1;const H=Math.floor(G*336),D=Math.floor(H/R);return[H,D]}pad_image(v,z,K,re={}){const[ae,R]=z,G=j*U(ae/j),H=j*U(R/j),D=[1,1,1].map(($,w)=>($-this.image_mean[w])/this.image_std[w]);return super.pad_image(v,z,{width:H,height:G},{center:!0,constant_values:D,...re})}async _call(v,{num_crops:z=null}={}){if(this._num_crops=z??=this.config.num_crops,z<4||P(z)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(v)||(v=[v]);const K=v.length,re=await Promise.all(v.map(C=>this.preprocess(C))),ae=re.map(C=>C.original_size),R=re.map(C=>C.reshaped_input_size),G=[];for(const{pixel_values:C}of re){C.unsqueeze_(0);const[x,J]=C.dims.slice(-2),q=await(0,O.interpolate_4d)(C,{size:[j,j],mode:"bicubic"});if(z>0){const le=[],ce=P(z),fe=y(J/ce),Pe=y(x/ce);for(let De=0;DeC.map(x=>j*U(x/j))),$=new O.Tensor("int64",D.flat(),[K,2]),w=D.map(([C,x])=>this.calc_num_image_tokens_from_image_size(x,C));return{pixel_values:H,original_sizes:ae,reshaped_input_sizes:R,image_sizes:$,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(Ce,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>y});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");const te="<|image|>",U=/<\|image_\d+\|>/g;class y extends g.Processor{static image_processor_class=O.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;async _call(b,T=null,{padding:v=!0,truncation:z=!0,num_crops:K=null}={}){Array.isArray(b)||(b=[b]);let re,ae;if(T){ae=await this.image_processor(T,{num_crops:K});const{num_img_tokens:R}=ae,G=b.map((D,$)=>D.split(U).join(te.repeat(R[$])));re=this.tokenizer(G,{padding:v,truncation:z});const H=this.tokenizer.model.convert_tokens_to_ids([te])[0];re.input_ids.map_(D=>D==H?-D:D)}else re=this.tokenizer(b);return{...re,...ae}}}},"./src/models/processors.js":(Ce,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>g.Florence2Processor,Idefics3Processor:()=>te.Idefics3Processor,JinaCLIPProcessor:()=>y.JinaCLIPProcessor,MgpstrProcessor:()=>O.MgpstrProcessor,MoonshineProcessor:()=>j.MoonshineProcessor,OwlViTProcessor:()=>P.OwlViTProcessor,PaliGemmaProcessor:()=>T.PaliGemmaProcessor,Phi3VProcessor:()=>b.Phi3VProcessor,PyAnnoteProcessor:()=>v.PyAnnoteProcessor,Qwen2VLProcessor:()=>z.Qwen2VLProcessor,SamProcessor:()=>K.SamProcessor,SpeechT5Processor:()=>re.SpeechT5Processor,VLChatProcessor:()=>U.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>ae.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>R.WhisperProcessor});var g=r("./src/models/florence2/processing_florence2.js"),O=r("./src/models/mgp_str/processing_mgp_str.js"),j=r("./src/models/moonshine/processing_moonshine.js"),te=r("./src/models/idefics3/processing_idefics3.js"),U=r("./src/models/janus/processing_janus.js"),y=r("./src/models/jina_clip/processing_jina_clip.js"),P=r("./src/models/owlvit/processing_owlvit.js"),b=r("./src/models/phi3_v/processing_phi3_v.js"),T=r("./src/models/paligemma/processing_paligemma.js"),v=r("./src/models/pyannote/processing_pyannote.js"),z=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),K=r("./src/models/sam/processing_sam.js"),re=r("./src/models/speecht5/processing_speecht5.js"),ae=r("./src/models/wav2vec2/processing_wav2vec2.js"),R=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Ce,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Ce,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>te});var g=r("./src/base/feature_extraction_utils.js"),O=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");class te extends g.FeatureExtractor{async _call(y){(0,g.validate_audio_inputs)(y,"PyAnnoteFeatureExtractor"),y instanceof Float64Array&&(y=new Float32Array(y));const P=[1,1,y.length];return{input_values:new O.Tensor("float32",y,P)}}samples_to_frames(y){return(y-this.config.offset)/this.config.step}post_process_speaker_diarization(y,P){const b=P/this.samples_to_frames(P)/this.config.sampling_rate,T=[];for(const v of y.tolist()){const z=[];let K=-1;for(let re=0;re({id:re,start:ae*b,end:R*b,confidence:G/(R-ae)})))}return T}}},"./src/models/pyannote/processing_pyannote.js":(Ce,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>j});var g=r("./src/base/processing_utils.js"),O=r("./src/models/pyannote/feature_extraction_pyannote.js");class j extends g.Processor{static feature_extractor_class=O.PyAnnoteFeatureExtractor;async _call(U){return await this.feature_extractor(U)}post_process_speaker_diarization(...U){return this.feature_extractor.post_process_speaker_diarization(...U)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Ce,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>j});var g=r("./src/base/image_processors_utils.js"),O=r("./src/utils/tensor.js");class j extends g.ImageProcessor{async _call(U,...y){const{pixel_values:P,original_sizes:b,reshaped_input_sizes:T}=await super._call(U,...y);let v=P;const{temporal_patch_size:z,merge_size:K,patch_size:re}=this.config;v.dims[0]===1&&(v=(0,O.cat)(Array.from({length:z},()=>v),0));const ae=v.dims[0]/z,R=v.dims[1],G=Math.floor(v.dims[2]/re),H=Math.floor(v.dims[3]/re),D=v.view(ae,z,R,Math.floor(G/K),K,re,Math.floor(H/K),K,re).permute(0,3,6,4,7,2,1,5,8).view(ae*G*H,R*z*re*re),$=new O.Tensor("int64",[ae,G,H],[1,3]);return{pixel_values:D,image_grid_thw:$,original_sizes:b,reshaped_input_sizes:T}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Ce,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>te});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");class te extends g.Processor{static image_processor_class=O.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;async _call(y,P=null,...b){Array.isArray(y)||(y=[y]);let T,v;if(P&&(T=await this.image_processor(P),v=T.image_grid_thw),v){let K=this.image_processor.config.merge_size**2,re=0;const ae=v.tolist();y=y.map(R=>{for(;R.includes("<|image_pad|>");){const G=Number(ae[re++].reduce((H,D)=>H*D,1n));R=R.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(G/K)))}return R.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(y),...T}}}},"./src/models/rt_detr/image_processing_rt_detr.js":(Ce,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{post_process_object_detection(...te){return(0,g.post_process_object_detection)(...te)}}},"./src/models/sam/image_processing_sam.js":(Ce,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>te});var g=r("./src/base/image_processors_utils.js"),O=r("./src/utils/core.js"),j=r("./src/utils/tensor.js");class te extends g.ImageProcessor{reshape_input_points(y,P,b,T=!1){y=structuredClone(y);let v=(0,O.calculateDimensions)(y);if(v.length===3)T||(v=[1,...v]),y=[y];else if(v.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let z=0;zT!==P.dims[v]))throw Error(`The first ${b.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j.Tensor("int64",y.flat(1/0).map(BigInt),b)}async _call(y,{input_points:P=null,input_labels:b=null,input_boxes:T=null}={}){const v=await super._call(y);if(P&&(v.input_points=this.reshape_input_points(P,v.original_sizes,v.reshaped_input_sizes)),b){if(!v.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");v.input_labels=this.add_input_labels(b,v.input_points)}return T&&(v.input_boxes=this.reshape_input_points(T,v.original_sizes,v.reshaped_input_sizes,!0)),v}async post_process_masks(y,P,b,{mask_threshold:T=0,binarize:v=!0,pad_size:z=null}={}){const K=[];z=z??this.pad_size;const re=[z.height,z.width];for(let ae=0;aeT&&($[w]=1);H=new j.Tensor("bool",$,H.dims)}K.push(H)}return K}generate_crop_boxes(y,P,{crop_n_layers:b=0,overlap_ratio:T=.3413333333333333,points_per_crop:v=32,crop_n_points_downscale_factor:z=1}={}){}}},"./src/models/sam/processing_sam.js":(Ce,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>j});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/image_processing_auto.js");class j extends g.Processor{static image_processor_class=O.AutoImageProcessor;async _call(...U){return await this.image_processor(...U)}post_process_masks(...U){return this.image_processor.post_process_masks(...U)}reshape_input_points(...U){return this.image_processor.reshape_input_points(...U)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Ce,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>te});var g=r("./src/base/feature_extraction_utils.js"),O=r("./src/utils/tensor.js"),j=r("./src/utils/audio.js");class te extends g.FeatureExtractor{constructor(y){super(y);const P=this.config.sampling_rate,b=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(P/2),P,null,"kaldi",!0);for(let T=0;Tb*32768),(0,j.spectrogram)(y,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:P,transpose:!0})}async _call(y,{padding:P=!0,pad_to_multiple_of:b=2,do_normalize_per_mel_bins:T=!0,return_attention_mask:v=!0}={}){(0,g.validate_audio_inputs)(y,"SeamlessM4TFeatureExtractor");let z=await this._extract_fbank_features(y,this.config.max_length);if(T){const[$,w]=z.dims,C=z.data;for(let x=0;x0){const J=new Float32Array(w*($+x));J.set(C),J.fill(this.config.padding_value,C.length);const q=$+x;z=new O.Tensor(z.type,J,[q,w]),v&&(K=new O.Tensor("int64",new BigInt64Array(q),[1,q]),K.data.fill(1n,0,$))}}const[re,ae]=z.dims,R=this.config.stride;if(re%R!==0)throw new Error(`The number of frames (${re}) must be a multiple of the stride (${R}).`);const H=z.view(1,Math.floor(re/R),ae*R),D={input_features:H};if(v){const $=H.dims[1],w=new BigInt64Array($);if(K){const C=K.data;for(let x=1,J=0;x{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>j,SegformerImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{post_process_semantic_segmentation(...U){return(0,g.post_process_semantic_segmentation)(...U)}}class j extends O{}},"./src/models/siglip/image_processing_siglip.js":(Ce,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Ce,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>O});var g=r("./src/base/feature_extraction_utils.js");class O extends g.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Ce,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>te});var g=r("./src/base/processing_utils.js"),O=r("./src/tokenizers.js"),j=r("./src/models/auto/feature_extraction_auto.js");class te extends g.Processor{static tokenizer_class=O.AutoTokenizer;static feature_extractor_class=j.AutoFeatureExtractor;async _call(y){return await this.feature_extractor(y)}}},"./src/models/swin2sr/image_processing_swin2sr.js":(Ce,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{pad_image(te,U,y,P={}){const[b,T,v]=U;return super.pad_image(te,U,{width:T+(y-T%y)%y,height:b+(y-b%y)%y},{mode:"symmetric",center:!1,constant_values:-1,...P})}}},"./src/models/vit/image_processing_vit.js":(Ce,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>j,ViTImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{}class j extends O{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Ce,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>j});var g=r("./src/base/image_processors_utils.js"),O=r("./src/utils/tensor.js");class j extends g.ImageProcessor{async _call(U,y){Array.isArray(U)||(U=[U]),Array.isArray(y)||(y=[y]);const P=await Promise.all(U.map(v=>this.preprocess(v))),b=await Promise.all(y.map(v=>this.preprocess(v,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,O.stack)(P.map((v,z)=>(0,O.cat)([v.pixel_values,b[z].pixel_values],0)),0),original_sizes:P.map(v=>v.original_size),reshaped_input_sizes:P.map(v=>v.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Ce,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{post_process_pose_estimation(te,U,{threshold:y=null}={}){const P=te.tolist(),[b,T,v,z]=te.dims,K=[];for(let re=0;re{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>j});var g=r("./src/base/feature_extraction_utils.js"),O=r("./src/utils/tensor.js");class j extends g.FeatureExtractor{_zero_mean_unit_var_norm(U){const P=U.reduce((T,v)=>T+v,0)/U.length,b=U.reduce((T,v)=>T+(v-P)**2,0)/U.length;return U.map(T=>(T-P)/Math.sqrt(b+1e-7))}async _call(U){(0,g.validate_audio_inputs)(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let y=U;this.config.do_normalize&&(y=this._zero_mean_unit_var_norm(y));const P=[1,y.length];return{input_values:new O.Tensor("float32",y,P),attention_mask:new O.Tensor("int64",new BigInt64Array(y.length).fill(1n),P)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Ce,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>j});var g=r("./src/base/processing_utils.js"),O=r("./src/models/auto/feature_extraction_auto.js");class j extends g.Processor{static feature_extractor_class=O.AutoFeatureExtractor;async _call(U){return await this.feature_extractor(U)}}},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Ce,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>j});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var O=r("./src/utils/audio.js");class j extends g.FeatureExtractor{constructor(U){super(U);const y=this.config.sampling_rate,P=(0,O.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(y/2),y,null,"kaldi",!0);for(let b=0;by*32768),(0,O.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){(0,g.validate_audio_inputs)(U,"WeSpeakerFeatureExtractor");const y=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const P=y.mean(1).data,b=y.data,[T,v,z]=y.dims;for(let K=0;K{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>O,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>j,whisper_language_to_code:()=>te});const g=[["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"]],O=new Map(g),j=new Map([...g.map(([U,y])=>[y,U]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function te(U){U=U.toLowerCase();let y=j.get(U);if(y===void 0)if(O.has(U))y=U;else{const b=U.length===2?O.keys():O.values();throw new Error(`Language "${U}" is not supported. Must be one of: ${JSON.stringify(b)}`)}return y}},"./src/models/whisper/feature_extraction_whisper.js":(Ce,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>te});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var O=r("./src/utils/audio.js"),j=r("./src/utils/maths.js");class te extends g.FeatureExtractor{constructor(y){super(y),this.config.mel_filters??=(0,O.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,O.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(y){const P=await(0,O.spectrogram)(y,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}),b=P.data,T=(0,j.max)(b)[0];for(let v=0;vthis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),P=y.slice(0,this.config.n_samples)):(P=new Float32Array(this.config.n_samples),P.set(y)),{input_features:(await this._extract_fbank_features(P)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(Ce,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>O});var g=r("./src/generation/configuration_utils.js");class O extends g.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/models/whisper/processing_whisper.js":(Ce,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>te});var g=r("./src/models/auto/feature_extraction_auto.js"),O=r("./src/tokenizers.js"),j=r("./src/base/processing_utils.js");class te extends j.Processor{static tokenizer_class=O.AutoTokenizer;static feature_extractor_class=g.AutoFeatureExtractor;async _call(y){return await this.feature_extractor(y)}}},"./src/models/yolos/image_processing_yolos.js":(Ce,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>j,YolosImageProcessor:()=>O});var g=r("./src/base/image_processors_utils.js");class O extends g.ImageProcessor{post_process_object_detection(...U){return(0,g.post_process_object_detection)(...U)}}class j extends O{}},"./src/ops/registry.js":(Ce,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>te});var g=r("./src/backends/onnx.js"),O=r("./src/utils/tensor.js");const j=async(U,y,P)=>{const b=await(0,g.createInferenceSession)(new Uint8Array(U),y);return async T=>{const v=Object.fromEntries(Object.entries(T).map(([K,re])=>[K,re.ort_tensor])),z=await b.run(v);return Array.isArray(P)?P.map(K=>new O.Tensor(z[K])):new O.Tensor(z[P])}};class te{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=j([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=j([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=j([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=j([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=j([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=j([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=j([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}},"./src/pipelines.js":(Ce,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>ce,AutomaticSpeechRecognitionPipeline:()=>Pe,DepthEstimationPipeline:()=>Le,DocumentQuestionAnsweringPipeline:()=>Z,FeatureExtractionPipeline:()=>q,FillMaskPipeline:()=>H,ImageClassificationPipeline:()=>De,ImageFeatureExtractionPipeline:()=>le,ImageSegmentationPipeline:()=>Ge,ImageToImagePipeline:()=>ve,ImageToTextPipeline:()=>be,ObjectDetectionPipeline:()=>lt,Pipeline:()=>re,QuestionAnsweringPipeline:()=>G,SummarizationPipeline:()=>$,Text2TextGenerationPipeline:()=>D,TextClassificationPipeline:()=>ae,TextGenerationPipeline:()=>x,TextToAudioPipeline:()=>he,TokenClassificationPipeline:()=>R,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>fe,ZeroShotClassificationPipeline:()=>J,ZeroShotImageClassificationPipeline:()=>Ne,ZeroShotObjectDetectionPipeline:()=>ue,pipeline:()=>ne});var g=r("./src/tokenizers.js"),O=r("./src/models.js"),j=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var te=r("./src/utils/generic.js"),U=r("./src/utils/core.js"),y=r("./src/utils/maths.js"),P=r("./src/utils/audio.js"),b=r("./src/utils/tensor.js"),T=r("./src/utils/image.js");async function v(Ae){return Array.isArray(Ae)||(Ae=[Ae]),await Promise.all(Ae.map(oe=>T.RawImage.read(oe)))}async function z(Ae,oe){return Array.isArray(Ae)||(Ae=[Ae]),await Promise.all(Ae.map(Me=>typeof Me=="string"||Me instanceof URL?(0,P.read_audio)(Me,oe):Me instanceof Float64Array?new Float32Array(Me):Me))}function K(Ae,oe){oe&&(Ae=Ae.map(ze=>ze|0));const[Me,je,Re,We]=Ae;return{xmin:Me,ymin:je,xmax:Re,ymax:We}}class re extends te.Callable{constructor({task:oe,model:Me,tokenizer:je=null,processor:Re=null}){super(),this.task=oe,this.model=Me,this.tokenizer=je,this.processor=Re}async dispose(){await this.model.dispose()}}class ae extends re{constructor(oe){super(oe)}async _call(oe,{top_k:Me=1}={}){const je=this.tokenizer(oe,{padding:!0,truncation:!0}),Re=await this.model(je),We=this.model.config.problem_type==="multi_label_classification"?nt=>nt.sigmoid():nt=>new b.Tensor("float32",(0,y.softmax)(nt.data),nt.dims),ze=this.model.config.id2label,Ye=[];for(const nt of Re.logits){const wt=We(nt),ut=await(0,b.topk)(wt,Me),ht=ut[0].tolist(),ie=ut[1].tolist().map((X,_e)=>({label:ze?ze[X]:`LABEL_${X}`,score:ht[_e]}));Me===1?Ye.push(...ie):Ye.push(ie)}return Array.isArray(oe)||Me===1?Ye:Ye[0]}}class R extends re{constructor(oe){super(oe)}async _call(oe,{ignore_labels:Me=["O"]}={}){const je=Array.isArray(oe),Re=this.tokenizer(je?oe:[oe],{padding:!0,truncation:!0}),ze=(await this.model(Re)).logits,Ye=this.model.config.id2label,nt=[];for(let wt=0;wtot==this.tokenizer.sep_token_id);nt[ht].map((ot,yt)=>ot==1&&(yt===0||yt>ie&&wt.findIndex(mt=>mt==I[yt])===-1));const X=We[ht].tolist(),_e=ze[ht].tolist();for(let ot=1;otyt==I[ot])!==-1)&&(X[ot]=-1/0,_e[ot]=-1/0);const $e=(0,y.softmax)(X).map((ot,yt)=>[ot,yt]),He=(0,y.softmax)(_e).map((ot,yt)=>[ot,yt]);$e[0][0]=0,He[0][0]=0;const et=(0,U.product)($e,He).filter(ot=>ot[0][1]<=ot[1][1]).map(ot=>[ot[0][1],ot[1][1],ot[0][0]*ot[1][0]]).sort((ot,yt)=>yt[2]-ot[2]);for(let ot=0;otX==this.tokenizer.mask_token_id);if(wt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ut=Re[Ye][wt],ht=await(0,b.topk)(new b.Tensor("float32",(0,y.softmax)(ut.data),ut.dims),Me),I=ht[0].tolist(),ie=ht[1].tolist();We.push(ie.map((X,_e)=>{const $e=nt.slice();return $e[wt]=X,{score:I[_e],token:Number(X),token_str:this.tokenizer.model.vocab[X],sequence:this.tokenizer.decode($e,{skip_special_tokens:!0})}}))}return Array.isArray(oe)?We:We[0]}}class D extends re{_key="generated_text";constructor(oe){super(oe)}async _call(oe,Me={}){Array.isArray(oe)||(oe=[oe]),this.model.config.prefix&&(oe=oe.map(nt=>this.model.config.prefix+nt));const je=this.model.config.task_specific_params;je&&je[this.task]&&je[this.task].prefix&&(oe=oe.map(nt=>je[this.task].prefix+nt));const Re=this.tokenizer,We={padding:!0,truncation:!0};let ze;this instanceof w&&"_build_translation_inputs"in Re?ze=Re._build_translation_inputs(oe,We,Me):ze=Re(oe,We);const Ye=await this.model.generate({...ze,...Me});return Re.batch_decode(Ye,{skip_special_tokens:!0}).map(nt=>({[this._key]:nt}))}}class $ extends D{_key="summary_text";constructor(oe){super(oe)}}class w extends D{_key="translation_text";constructor(oe){super(oe)}}function C(Ae){return Array.isArray(Ae)&&Ae.every(oe=>"role"in oe&&"content"in oe)}class x extends re{constructor(oe){super(oe)}async _call(oe,Me={}){let je=!1,Re=!1,We;if(typeof oe=="string")We=oe=[oe];else if(Array.isArray(oe)&&oe.every(ie=>typeof ie=="string"))je=!0,We=oe;else{if(C(oe))oe=[oe];else if(Array.isArray(oe)&&oe.every(C))je=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Re=!0,We=oe.map(ie=>this.tokenizer.apply_chat_template(ie,{tokenize:!1,add_generation_prompt:!0}))}const ze=Me.add_special_tokens??!1,Ye=Re?!1:Me.return_full_text??!0;this.tokenizer.padding_side="left";const nt=this.tokenizer(We,{add_special_tokens:ze,padding:!0,truncation:!0}),wt=await this.model.generate({...nt,...Me}),ut=this.tokenizer.batch_decode(wt,{skip_special_tokens:!0});let ht;!Ye&&nt.input_ids.dims.at(-1)>0&&(ht=this.tokenizer.batch_decode(nt.input_ids,{skip_special_tokens:!0}).map(ie=>ie.length));const I=Array.from({length:oe.length},ie=>[]);for(let ie=0;ie[Me.toLowerCase(),je])),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(oe,Me,{hypothesis_template:je="This example is {}.",multi_label:Re=!1}={}){const We=Array.isArray(oe);We||(oe=[oe]),Array.isArray(Me)||(Me=[Me]);const ze=Me.map(wt=>je.replace("{}",wt)),Ye=Re||Me.length===1,nt=[];for(const wt of oe){const ut=[];for(const ie of ze){const X=this.tokenizer(wt,{text_pair:ie,padding:!0,truncation:!0}),_e=await this.model(X);Ye?ut.push([_e.logits.data[this.contradiction_id],_e.logits.data[this.entailment_id]]):ut.push(_e.logits.data[this.entailment_id])}const I=(Ye?ut.map(ie=>(0,y.softmax)(ie)[1]):(0,y.softmax)(ut)).map((ie,X)=>[ie,X]).sort((ie,X)=>X[0]-ie[0]);nt.push({sequence:wt,labels:I.map(ie=>Me[ie[1]]),scores:I.map(ie=>ie[0])})}return We?nt:nt[0]}}class q extends re{constructor(oe){super(oe)}async _call(oe,{pooling:Me="none",normalize:je=!1,quantize:Re=!1,precision:We="binary"}={}){const ze=this.tokenizer(oe,{padding:!0,truncation:!0}),Ye=await this.model(ze);let nt=Ye.last_hidden_state??Ye.logits??Ye.token_embeddings;if(Me!=="none")if(Me==="mean")nt=(0,b.mean_pooling)(nt,ze.attention_mask);else if(Me==="cls")nt=nt.slice(null,0);else throw Error(`Pooling method '${Me}' not supported.`);return je&&(nt=nt.normalize(2,-1)),Re&&(nt=(0,b.quantize_embeddings)(nt,We)),nt}}class le extends re{constructor(oe){super(oe)}async _call(oe,{pool:Me=null}={}){const je=await v(oe),{pixel_values:Re}=await this.processor(je),We=await this.model({pixel_values:Re});let ze;if(Me){if(!("pooler_output"in We))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");ze=We.pooler_output}else ze=We.last_hidden_state??We.logits??We.image_embeds;return ze}}class ce extends re{constructor(oe){super(oe)}async _call(oe,{top_k:Me=5}={}){const je=this.processor.feature_extractor.config.sampling_rate,Re=await z(oe,je),We=this.model.config.id2label,ze=[];for(const Ye of Re){const nt=await this.processor(Ye),ut=(await this.model(nt)).logits[0],ht=await(0,b.topk)(new b.Tensor("float32",(0,y.softmax)(ut.data),ut.dims),Me),I=ht[0].tolist(),X=ht[1].tolist().map((_e,$e)=>({label:We?We[_e]:`LABEL_${_e}`,score:I[$e]}));ze.push(X)}return Array.isArray(oe)?ze:ze[0]}}class fe extends re{constructor(oe){super(oe)}async _call(oe,Me,{hypothesis_template:je="This is a sound of {}."}={}){const Re=!Array.isArray(oe);Re&&(oe=[oe]);const We=Me.map(ut=>je.replace("{}",ut)),ze=this.tokenizer(We,{padding:!0,truncation:!0}),Ye=this.processor.feature_extractor.config.sampling_rate,nt=await z(oe,Ye),wt=[];for(const ut of nt){const ht=await this.processor(ut),I=await this.model({...ze,...ht}),ie=(0,y.softmax)(I.logits_per_audio.data);wt.push([...ie].map((X,_e)=>({score:X,label:Me[_e]})))}return Re?wt[0]:wt}}class Pe extends re{constructor(oe){super(oe)}async _call(oe,Me={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(oe,Me);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(oe,Me);case"moonshine":return this._call_moonshine(oe,Me);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(oe,Me){Me.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Me.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const je=!Array.isArray(oe);je&&(oe=[oe]);const Re=this.processor.feature_extractor.config.sampling_rate,We=await z(oe,Re),ze=[];for(const Ye of We){const nt=await this.processor(Ye),ut=(await this.model(nt)).logits[0],ht=[];for(const ie of ut)ht.push((0,y.max)(ie.data)[1]);const I=this.tokenizer.decode(ht);ze.push({text:I})}return je?ze[0]:ze}async _call_whisper(oe,Me){const je=Me.return_timestamps??!1,Re=Me.chunk_length_s??0,We=Me.force_full_sequences??!1;let ze=Me.stride_length_s??null;const Ye={...Me};je==="word"&&(Ye.return_token_timestamps=!0,Ye.return_timestamps=!1);const nt=!Array.isArray(oe);nt&&(oe=[oe]);const wt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ut=this.processor.feature_extractor.config.hop_length,ht=this.processor.feature_extractor.config.sampling_rate,I=await z(oe,ht),ie=[];for(const X of I){let _e=[];if(Re>0){if(ze===null)ze=Re/6;else if(Re<=ze)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const et=ht*Re,ot=ht*ze,yt=et-2*ot;let mt=0;for(;;){const Qt=mt+et,ts=X.subarray(mt,Qt),xs=await this.processor(ts),hs=mt===0,$s=Qt>=X.length;if(_e.push({stride:[ts.length,hs?0:ot,$s?0:ot],input_features:xs.input_features,is_last:$s}),$s)break;mt+=yt}}else _e=[{stride:[X.length,0,0],input_features:(await this.processor(X)).input_features,is_last:!0}];for(const et of _e){Ye.num_frames=Math.floor(et.stride[0]/ut);const ot=await this.model.generate({inputs:et.input_features,...Ye});je==="word"?(et.tokens=ot.sequences.tolist()[0],et.token_timestamps=ot.token_timestamps.tolist()[0].map(yt=>(0,y.round)(yt,2))):et.tokens=ot[0].tolist(),et.stride=et.stride.map(yt=>yt/ht)}const[$e,He]=this.tokenizer._decode_asr(_e,{time_precision:wt,return_timestamps:je,force_full_sequences:We});ie.push({text:$e,...He})}return nt?ie[0]:ie}async _call_moonshine(oe,Me){const je=!Array.isArray(oe);je&&(oe=[oe]);const Re=this.processor.feature_extractor.config.sampling_rate,We=await z(oe,Re),ze=[];for(const Ye of We){const nt=await this.processor(Ye),wt=Math.floor(Ye.length/Re)*6,ut=await this.model.generate({max_new_tokens:wt,...Me,...nt}),ht=this.processor.batch_decode(ut,{skip_special_tokens:!0})[0];ze.push({text:ht})}return je?ze[0]:ze}}class be extends re{constructor(oe){super(oe)}async _call(oe,Me={}){const je=Array.isArray(oe),Re=await v(oe),{pixel_values:We}=await this.processor(Re),ze=[];for(const Ye of We){Ye.dims=[1,...Ye.dims];const nt=await this.model.generate({inputs:Ye,...Me}),wt=this.tokenizer.batch_decode(nt,{skip_special_tokens:!0}).map(ut=>({generated_text:ut.trim()}));ze.push(wt)}return je?ze:ze[0]}}class De extends re{constructor(oe){super(oe)}async _call(oe,{top_k:Me=5}={}){const je=await v(oe),{pixel_values:Re}=await this.processor(je),We=await this.model({pixel_values:Re}),ze=this.model.config.id2label,Ye=[];for(const nt of We.logits){const wt=await(0,b.topk)(new b.Tensor("float32",(0,y.softmax)(nt.data),nt.dims),Me),ut=wt[0].tolist(),I=wt[1].tolist().map((ie,X)=>({label:ze?ze[ie]:`LABEL_${ie}`,score:ut[X]}));Ye.push(I)}return Array.isArray(oe)?Ye:Ye[0]}}class Ge extends re{constructor(oe){super(oe),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(oe,{threshold:Me=.5,mask_threshold:je=.5,overlap_mask_area_threshold:Re=.8,label_ids_to_fuse:We=null,target_sizes:ze=null,subtask:Ye=null}={}){if(Array.isArray(oe)&&oe.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const wt=await v(oe),ut=wt.map(He=>[He.height,He.width]),{pixel_values:ht,pixel_mask:I}=await this.processor(wt),ie=await this.model({pixel_values:ht,pixel_mask:I});let X=null;if(Ye!==null)X=this.subtasks_mapping[Ye];else for(let[He,et]of Object.entries(this.subtasks_mapping))if(et in this.processor.image_processor){X=this.processor.image_processor[et].bind(this.processor.image_processor),Ye=He;break}const _e=this.model.config.id2label,$e=[];if(Ye==="panoptic"||Ye==="instance"){const He=X(ie,Me,je,Re,We,ze??ut)[0],et=He.segmentation;for(const ot of He.segments_info){const yt=new Uint8ClampedArray(et.data.length);for(let Qt=0;Qtje.replace("{}",I)),Ye=this.tokenizer(ze,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:nt}=await this.processor(We),wt=await this.model({...Ye,pixel_values:nt}),ut=this.model.config.model_type==="siglip"?I=>I.sigmoid().data:I=>(0,y.softmax)(I.data),ht=[];for(const I of wt.logits_per_image){const X=[...ut(I)].map((_e,$e)=>({score:_e,label:Me[$e]}));X.sort((_e,$e)=>$e.score-_e.score),ht.push(X)}return Re?ht:ht[0]}}class lt extends re{constructor(oe){super(oe)}async _call(oe,{threshold:Me=.9,percentage:je=!1}={}){const Re=Array.isArray(oe);if(Re&&oe.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const We=await v(oe),ze=je?null:We.map(ie=>[ie.height,ie.width]),{pixel_values:Ye,pixel_mask:nt}=await this.processor(We),wt=await this.model({pixel_values:Ye,pixel_mask:nt}),ut=this.processor.image_processor.post_process_object_detection(wt,Me,ze),ht=this.model.config.id2label,I=ut.map(ie=>ie.boxes.map((X,_e)=>({score:ie.scores[_e],label:ht[ie.classes[_e]],box:K(X,!je)})));return Re?I:I[0]}}class ue extends re{constructor(oe){super(oe)}async _call(oe,Me,{threshold:je=.1,top_k:Re=null,percentage:We=!1}={}){const ze=Array.isArray(oe),Ye=await v(oe),nt=this.tokenizer(Me,{padding:!0,truncation:!0}),wt=await this.processor(Ye),ut=[];for(let ht=0;ht({score:$e.scores[ot],label:Me[$e.classes[ot]],box:K(et,!We)})).sort((et,ot)=>ot.score-et.score);Re!==null&&(He=He.slice(0,Re)),ut.push(He)}return ze?ut:ut[0]}}class Z extends re{constructor(oe){super(oe)}async _call(oe,Me,je={}){const Re=(await v(oe))[0],{pixel_values:We}=await this.processor(Re),ze=`${Me}`,Ye=this.tokenizer(ze,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,nt=await this.model.generate({inputs:We,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ye,...je}),ut=this.tokenizer.batch_decode(nt)[0].match(/(.*?)<\/s_answer>/);let ht=null;return ut&&ut.length>=2&&(ht=ut[1].trim()),[{answer:ht}]}}class he extends re{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(oe){super(oe),this.vocoder=oe.vocoder??null}async _call(oe,{speaker_embeddings:Me=null}={}){return this.processor?this._call_text_to_spectrogram(oe,{speaker_embeddings:Me}):this._call_text_to_waveform(oe)}async _call_text_to_waveform(oe){const Me=this.tokenizer(oe,{padding:!0,truncation:!0}),{waveform:je}=await this.model(Me),Re=this.model.config.sampling_rate;return{audio:je.data,sampling_rate:Re}}async _call_text_to_spectrogram(oe,{speaker_embeddings:Me}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await O.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Me=="string"||Me instanceof URL)&&(Me=new Float32Array(await(await fetch(Me)).arrayBuffer())),Me instanceof Float32Array)Me=new b.Tensor("float32",Me,[1,Me.length]);else if(!(Me instanceof b.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:je}=this.tokenizer(oe,{padding:!0,truncation:!0}),{waveform:Re}=await this.model.generate_speech(je,Me,{vocoder:this.vocoder}),We=this.processor.feature_extractor.config.sampling_rate;return{audio:Re.data,sampling_rate:We}}}class ve extends re{constructor(oe){super(oe)}async _call(oe){const Me=await v(oe),je=await this.processor(Me),Re=await this.model(je),We=[];for(const ze of Re.reconstruction){const Ye=ze.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");We.push(T.RawImage.fromTensor(Ye))}return We.length>1?We:We[0]}}class Le extends re{constructor(oe){super(oe)}async _call(oe){const Me=await v(oe),je=await this.processor(Me),{predicted_depth:Re}=await this.model(je),We=[];for(let ze=0;ze1?We:We[0]}}const Ze=Object.freeze({"text-classification":{tokenizer:g.AutoTokenizer,pipeline:ae,model:O.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:g.AutoTokenizer,pipeline:R,model:O.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:g.AutoTokenizer,pipeline:G,model:O.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:g.AutoTokenizer,pipeline:H,model:O.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:g.AutoTokenizer,pipeline:$,model:O.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:g.AutoTokenizer,pipeline:w,model:O.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:g.AutoTokenizer,pipeline:D,model:O.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:g.AutoTokenizer,pipeline:x,model:O.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:g.AutoTokenizer,pipeline:J,model:O.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ce,model:O.AutoModelForAudioClassification,processor:j.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:g.AutoTokenizer,pipeline:fe,model:O.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:g.AutoTokenizer,pipeline:Pe,model:[O.AutoModelForSpeechSeq2Seq,O.AutoModelForCTC],processor:j.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:g.AutoTokenizer,pipeline:he,model:[O.AutoModelForTextToWaveform,O.AutoModelForTextToSpectrogram],processor:[j.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:g.AutoTokenizer,pipeline:be,model:O.AutoModelForVision2Seq,processor:j.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:De,model:O.AutoModelForImageClassification,processor:j.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ge,model:[O.AutoModelForImageSegmentation,O.AutoModelForSemanticSegmentation,O.AutoModelForUniversalSegmentation],processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:g.AutoTokenizer,pipeline:Ne,model:O.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:lt,model:O.AutoModelForObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:g.AutoTokenizer,pipeline:ue,model:O.AutoModelForZeroShotObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:g.AutoTokenizer,pipeline:Z,model:O.AutoModelForDocumentQuestionAnswering,processor:j.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ve,model:O.AutoModelForImageToImage,processor:j.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Le,model:O.AutoModelForDepthEstimation,processor:j.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:g.AutoTokenizer,pipeline:q,model:O.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:j.AutoProcessor,pipeline:le,model:[O.AutoModelForImageFeatureExtraction,O.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ke=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ne(Ae,oe=null,{progress_callback:Me=null,config:je=null,cache_dir:Re=null,local_files_only:We=!1,revision:ze="main",device:Ye=null,dtype:nt=null,model_file_name:wt=null,session_options:ut={}}={}){Ae=Ke[Ae]??Ae;const ht=Ze[Ae.split("_",1)[0]];if(!ht)throw Error(`Unsupported pipeline: ${Ae}. Must be one of [${Object.keys(Ze)}]`);oe||(oe=ht.default.model,console.log(`No model specified. Using default model: "${oe}".`));const I={progress_callback:Me,config:je,cache_dir:Re,local_files_only:We,revision:ze,device:Ye,dtype:nt,model_file_name:wt,session_options:ut},ie=new Map([["tokenizer",ht.tokenizer],["model",ht.model],["processor",ht.processor]]),X=await qe(ie,oe,I);X.task=Ae,(0,U.dispatchCallback)(Me,{status:"ready",task:Ae,model:oe});const _e=ht.pipeline;return new _e(X)}async function qe(Ae,oe,Me){const je=Object.create(null),Re=[];for(const[We,ze]of Ae.entries()){if(!ze)continue;let Ye;Array.isArray(ze)?Ye=new Promise(async(nt,wt)=>{let ut;for(const ht of ze){if(ht===null){nt(null);return}try{nt(await ht.from_pretrained(oe,Me));return}catch(I){if(I.message?.includes("Unsupported model type"))ut=I;else if(I.message?.includes("Could not locate file"))ut=I;else{wt(I);return}}}wt(ut)}):Ye=ze.from_pretrained(oe,Me),je[We]=Ye,Re.push(Ye)}await Promise.all(Re);for(const[We,ze]of Object.entries(je))je[We]=await ze;return je}},"./src/tokenizers.js":(Ce,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>br,AutoTokenizer:()=>In,BartTokenizer:()=>rs,BertTokenizer:()=>Nr,BlenderbotSmallTokenizer:()=>$n,BlenderbotTokenizer:()=>pn,BloomTokenizer:()=>Tn,CLIPTokenizer:()=>Cn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>En,CodeLlamaTokenizer:()=>Ar,CohereTokenizer:()=>An,ConvBertTokenizer:()=>Tr,DebertaTokenizer:()=>Sr,DebertaV2Tokenizer:()=>Js,DistilBertTokenizer:()=>rr,ElectraTokenizer:()=>St,EsmTokenizer:()=>Zs,FalconTokenizer:()=>Ir,GPT2Tokenizer:()=>Ur,GPTNeoXTokenizer:()=>fr,GemmaTokenizer:()=>Gr,Grok1Tokenizer:()=>un,HerbertTokenizer:()=>ur,LlamaTokenizer:()=>xn,M2M100Tokenizer:()=>Ft,MBart50Tokenizer:()=>$r,MBartTokenizer:()=>Vr,MPNetTokenizer:()=>Xn,MarianTokenizer:()=>Or,MgpstrTokenizer:()=>Hr,MobileBertTokenizer:()=>kr,NllbTokenizer:()=>dn,NougatTokenizer:()=>er,PreTrainedTokenizer:()=>Ot,Qwen2Tokenizer:()=>ln,RoFormerTokenizer:()=>jr,RobertaTokenizer:()=>qn,SiglipTokenizer:()=>kn,SpeechT5Tokenizer:()=>ns,SqueezeBertTokenizer:()=>vr,T5Tokenizer:()=>cs,TokenizerModel:()=>le,VitsTokenizer:()=>hn,Wav2Vec2CTCTokenizer:()=>Sn,WhisperTokenizer:()=>cn,XLMRobertaTokenizer:()=>Pn,XLMTokenizer:()=>dt,is_chinese_char:()=>H});var g=r("./src/utils/generic.js"),O=r("./src/utils/core.js"),j=r("./src/utils/hub.js"),te=r("./src/utils/maths.js"),U=r("./src/utils/tensor.js"),y=r("./src/utils/data-structures.js"),P=r("./node_modules/@huggingface/jinja/dist/index.js"),b=r("./src/models/whisper/common_whisper.js");r("./src/utils/constants.js");async function T(Te,M){const Q=await Promise.all([(0,j.getModelJSON)(Te,"tokenizer.json",!0,M),(0,j.getModelJSON)(Te,"tokenizer_config.json",!0,M)]);return M.legacy!==null&&(Q[1].legacy=M.legacy),Q}function v(Te,M){const Q=[];let pe=0;for(const ge of Te.matchAll(M)){const Ie=ge[0];pe0&&Q.push(Ie),pe=ge.index+Ie.length}return pe=19968&&Te<=40959||Te>=13312&&Te<=19903||Te>=131072&&Te<=173791||Te>=173824&&Te<=177983||Te>=177984&&Te<=178207||Te>=178208&&Te<=183983||Te>=63744&&Te<=64255||Te>=194560&&Te<=195103}function D(Te,M,Q){const pe=[];let ge=0;for(;gethis.tokens_to_ids.get(Q)??this.unk_token_id)}convert_ids_to_tokens(M){return M.map(Q=>this.vocab[Q]??this.unk_token)}}class ce extends le{constructor(M){super(M),this.tokens_to_ids=K(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[Q,pe]of this.tokens_to_ids)this.vocab[pe]=Q}encode(M){const Q=[];for(const pe of M){const ge=[...pe];if(ge.length>this.max_input_chars_per_word){Q.push(this.unk_token);continue}let Ie=!1,Xe=0;const _t=[];for(;Xe0&&(Qe=this.config.continuing_subword_prefix+Qe),this.tokens_to_ids.has(Qe)){vt=Qe;break}--ft}if(vt===null){Ie=!0;break}_t.push(vt),Xe=ft}Ie?Q.push(this.unk_token):Q.push(..._t)}return Q}}class fe extends le{constructor(M,Q){super(M);const pe=M.vocab.length;this.vocab=new Array(pe),this.scores=new Array(pe);for(let ge=0;ge[ge,Ie])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,te.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new y.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(M){const Q=M.chars,pe=1;let ge=0;for(;ge{const Te=[...Array.from({length:94},(ge,Ie)=>Ie+33),...Array.from({length:12},(ge,Ie)=>Ie+161),...Array.from({length:82},(ge,Ie)=>Ie+174)],M=Te.slice();let Q=0;for(let ge=0;ge<256;++ge)Te.includes(ge)||(Te.push(ge),M.push(256+Q),Q+=1);const pe=M.map(ge=>String.fromCharCode(ge));return Object.fromEntries(Te.map((ge,Ie)=>[ge,pe[Ie]]))})(),be=(0,O.reverseDictionary)(Pe);class De extends le{constructor(M){super(M),this.tokens_to_ids=K(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[pe,ge]of this.tokens_to_ids)this.vocab[ge]=pe;const Q=Array.isArray(M.merges[0]);this.merges=Q?M.merges:M.merges.map(pe=>pe.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((pe,ge)=>[JSON.stringify(pe),ge])),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 Q=this.cache.get(M);if(Q!==void 0)return Q;const pe=Array.from(M);this.end_of_word_suffix&&(pe[pe.length-1]+=this.end_of_word_suffix);let ge=[];if(pe.length>1){const Ie=new y.PriorityQueue((ft,vt)=>ft.score`<0x${_t.toString(16).toUpperCase().padStart(2,"0")}>`);Xe.every(_t=>this.tokens_to_ids.has(_t))?Q.push(...Xe):Q.push(this.unk_token)}else Q.push(this.unk_token)}return Q}}class Ge extends le{constructor(M,Q){super(M),this.tokens_to_ids=K(Q.target_lang?M.vocab[Q.target_lang]:M.vocab),this.bos_token=Q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=Q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=Q.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[pe,ge]of this.tokens_to_ids)this.vocab[ge]=pe}encode(M){return M}}class Ne extends g.Callable{constructor(M){super(),this.config=M}static fromConfig(M){if(M===null)return null;switch(M.type){case"BertNormalizer":return new qe(M);case"Precompiled":return new hs(M);case"Sequence":return new ne(M);case"Replace":return new lt(M);case"NFC":return new ue(M);case"NFKC":return new Z(M);case"NFKD":return new he(M);case"Strip":return new ve(M);case"StripAccents":return new Le(M);case"Lowercase":return new Ze(M);case"Prepend":return new Ke(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 lt extends Ne{normalize(M){const Q=z(this.config.pattern);return Q===null?M:M.replaceAll(Q,this.config.content)}}class ue extends Ne{normalize(M){return M=M.normalize("NFC"),M}}class Z extends Ne{normalize(M){return M=M.normalize("NFKC"),M}}class he extends Ne{normalize(M){return M=M.normalize("NFKD"),M}}class ve extends Ne{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 Le extends Ne{normalize(M){return M=R(M),M}}class Ze extends Ne{normalize(M){return M=M.toLowerCase(),M}}class Ke extends Ne{normalize(M){return M=this.config.prepend+M,M}}class ne extends Ne{constructor(M){super(M),this.normalizers=M.normalizers.map(Q=>Ne.fromConfig(Q))}normalize(M){return this.normalizers.reduce((Q,pe)=>pe.normalize(Q),M)}}class qe extends Ne{_tokenize_chinese_chars(M){const Q=[];for(let pe=0;pethis.pre_tokenize_text(pe,Q)):this.pre_tokenize_text(M,Q)).flat()}_call(M,Q){return this.pre_tokenize(M,Q)}}class oe extends Ae{constructor(M){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(M,Q){return M.trim().match(this.pattern)||[]}}class Me extends Ae{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=Pe,this.text_encoder=new TextEncoder}pre_tokenize_text(M,Q){return this.add_prefix_space&&!M.startsWith(" ")&&(M=" "+M),(this.use_regex?M.match(this.pattern)||[]:[M]).map(ge=>Array.from(this.text_encoder.encode(ge),Ie=>this.byte_encoder[Ie]).join(""))}}class je extends Ae{constructor(M){super(),this.config=M,this.pattern=z(this.config.pattern,this.config.invert)}pre_tokenize_text(M,Q){return this.pattern===null?[]:this.config.invert?M.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?M.split(this.pattern).filter(pe=>pe):v(M,this.pattern)}}class Re extends Ae{constructor(M){super(),this.config=M,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(M,Q){return M.match(this.pattern)||[]}}class We extends Ae{constructor(M){super(),this.config=M;const Q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Q,"gu")}pre_tokenize_text(M,Q){return M.match(this.pattern)||[]}}class ze extends g.Callable{constructor(M){super(),this.config=M}static fromConfig(M){if(M===null)return null;switch(M.type){case"TemplateProcessing":return new wt(M);case"ByteLevel":return new ut(M);case"RobertaProcessing":return new nt(M);case"BertProcessing":return new Ye(M);case"Sequence":return new ht(M);default:throw new Error(`Unknown PostProcessor type: ${M.type}`)}}post_process(M,...Q){throw Error("post_process should be implemented in subclass.")}_call(M,...Q){return this.post_process(M,...Q)}}class Ye extends ze{constructor(M){super(M),this.cls=M.cls[0],this.sep=M.sep[0]}post_process(M,Q=null,{add_special_tokens:pe=!0}={}){pe&&(M=(0,O.mergeArrays)([this.cls],M,[this.sep]));let ge=new Array(M.length).fill(0);if(Q!==null){const Ie=pe&&this instanceof nt?[this.sep]:[],Xe=pe?[this.sep]:[];M=(0,O.mergeArrays)(M,Ie,Q,Xe),ge=(0,O.mergeArrays)(ge,new Array(Q.length+Ie.length+Xe.length).fill(1))}return{tokens:M,token_type_ids:ge}}}class nt extends Ye{}class wt extends ze{constructor(M){super(M),this.single=M.single,this.pair=M.pair}post_process(M,Q=null,{add_special_tokens:pe=!0}={}){const ge=Q===null?this.single:this.pair;let Ie=[],Xe=[];for(const _t of ge)"SpecialToken"in _t?pe&&(Ie.push(_t.SpecialToken.id),Xe.push(_t.SpecialToken.type_id)):"Sequence"in _t&&(_t.Sequence.id==="A"?(Ie=(0,O.mergeArrays)(Ie,M),Xe=(0,O.mergeArrays)(Xe,new Array(M.length).fill(_t.Sequence.type_id))):_t.Sequence.id==="B"&&(Ie=(0,O.mergeArrays)(Ie,Q),Xe=(0,O.mergeArrays)(Xe,new Array(Q.length).fill(_t.Sequence.type_id))));return{tokens:Ie,token_type_ids:Xe}}}class ut extends ze{post_process(M,Q=null){return Q&&(M=(0,O.mergeArrays)(M,Q)),{tokens:M}}}class ht extends ze{constructor(M){super(M),this.processors=M.processors.map(Q=>ze.fromConfig(Q))}post_process(M,Q=null,pe={}){let ge;for(const Ie of this.processors)if(Ie instanceof ut)M=Ie.post_process(M).tokens,Q&&(Q=Ie.post_process(Q).tokens);else{const Xe=Ie.post_process(M,Q,pe);M=Xe.tokens,ge=Xe.token_type_ids}return{tokens:M,token_type_ids:ge}}}class I extends g.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 xs(M);case"ByteLevel":return new et(M);case"Replace":return new ie(M);case"ByteFallback":return new X(M);case"Fuse":return new _e(M);case"Strip":return new $e(M);case"Sequence":return new yt(M);case"CTC":return new ot(M);case"BPEDecoder":return new mt(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 ie extends I{decode_chain(M){const Q=z(this.config.pattern);return Q===null?M:M.map(pe=>pe.replaceAll(Q,this.config.content))}}class X extends I{constructor(M){super(M),this.text_decoder=new TextDecoder}decode_chain(M){const Q=[];let pe=[];for(const ge of M){let Ie=null;if(ge.length===6&&ge.startsWith("<0x")&&ge.endsWith(">")){const Xe=parseInt(ge.slice(3,5),16);isNaN(Xe)||(Ie=Xe)}if(Ie!==null)pe.push(Ie);else{if(pe.length>0){const Xe=this.text_decoder.decode(Uint8Array.from(pe));Q.push(Xe),pe=[]}Q.push(ge)}}if(pe.length>0){const ge=this.text_decoder.decode(Uint8Array.from(pe));Q.push(ge),pe=[]}return Q}}class _e extends I{decode_chain(M){return[M.join("")]}}class $e extends I{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(Q=>{let pe=0;for(let Ie=0;Ie(pe!==0&&(Q.startsWith(this.config.prefix)?Q=Q.replace(this.config.prefix,""):Q=" "+Q),this.cleanup&&(Q=ae(Q)),Q))}}class et extends I{constructor(M){super(M),this.byte_decoder=be,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(M){const Q=M.join(""),pe=new Uint8Array([...Q].map(Ie=>this.byte_decoder[Ie]));return this.text_decoder.decode(pe)}decode_chain(M){const Q=[];let pe=[];for(const ge of M)this.added_tokens.find(Ie=>Ie.content===ge)!==void 0?(pe.length>0&&(Q.push(this.convert_tokens_to_string(pe)),pe=[]),Q.push(ge)):pe.push(ge);return pe.length>0&&Q.push(this.convert_tokens_to_string(pe)),Q}}class ot extends I{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 Q=[M[0]];for(let Ie=1;IeIe!==this.pad_token).join("");return this.cleanup&&(ge=ae(ge).replaceAll(this.word_delimiter_token," ").trim()),ge}decode_chain(M){return[this.convert_tokens_to_string(M)]}}class yt extends I{constructor(M){super(M),this.decoders=M.decoders.map(Q=>I.fromConfig(Q))}decode_chain(M){return this.decoders.reduce((Q,pe)=>pe.decode_chain(Q),M)}}class mt extends I{constructor(M){super(M),this.suffix=this.config.suffix}decode_chain(M){return M.map((Q,pe)=>Q.replaceAll(this.suffix,pe===M.length-1?"":" "))}}class Qt extends I{decode_chain(M){let Q="";for(let pe=1;pepe.normalize("NFKC")).join("~"):M=M.normalize("NFKC"),M}}class $s extends Ae{constructor(M){super(),this.tokenizers=M.pretokenizers.map(Q=>Ae.fromConfig(Q))}pre_tokenize_text(M,Q){return this.tokenizers.reduce((pe,ge)=>ge.pre_tokenize(pe,Q),[M])}}class Ms extends Ae{constructor(M){super()}pre_tokenize_text(M,Q){return M.match(/\w+|[^\w\s]+/g)||[]}}class Ks extends Ae{constructor(M){super()}pre_tokenize_text(M,Q){return $(M)}}class sr extends Ae{constructor(M){super(),this.config=M,this.pattern=z(this.config.pattern),this.content=this.config.content}pre_tokenize_text(M,Q){return this.pattern===null?[M]:[M.replaceAll(this.pattern,this.config.content)]}}const Rr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Cr(Te,M,Q,pe){for(const ge of Object.keys(Te)){const Ie=M-Te[ge].length,Xe=Q(ge),_t=new Array(Ie).fill(Xe);Te[ge]=pe==="right"?(0,O.mergeArrays)(Te[ge],_t):(0,O.mergeArrays)(_t,Te[ge])}}function an(Te,M){for(const Q of Object.keys(Te))Te[Q].length=M}class Ot extends g.Callable{return_token_type_ids=!1;padding_side="right";constructor(M,Q){super(),this._tokenizer_config=Q,this.normalizer=Ne.fromConfig(M.normalizer),this.pre_tokenizer=Ae.fromConfig(M.pre_tokenizer),this.model=le.fromConfig(M.model,Q),this.post_processor=ze.fromConfig(M.post_processor),this.decoder=I.fromConfig(M.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const pe of M.added_tokens){const ge=new q(pe);this.added_tokens.push(ge),this.model.tokens_to_ids.set(ge.content,ge.id),this.model.vocab[ge.id]=ge.content,ge.special&&(this.special_tokens.push(ge.content),this.all_special_ids.push(ge.id))}if(this.additional_special_tokens=Q.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((pe,ge)=>ge.content.length-pe.content.length).map(pe=>`${pe.lstrip?"\\s*":""}(${(0,O.escapeRegExp)(pe.content)})${pe.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const pe=Object.create(null);for(const{name:ge,template:Ie}of this.chat_template){if(typeof ge!="string"||typeof Ie!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');pe[ge]=Ie}this.chat_template=pe}this._compiled_template_cache=new Map}getToken(...M){for(const Q of M){const pe=this._tokenizer_config[Q];if(pe)if(typeof pe=="object"){if(pe.__type==="AddedToken")return pe.content;throw Error(`Unknown token: ${pe}`)}else return pe}return null}static async from_pretrained(M,{progress_callback:Q=null,config:pe=null,cache_dir:ge=null,local_files_only:Ie=!1,revision:Xe="main",legacy:_t=null}={}){const ft=await T(M,{progress_callback:Q,config:pe,cache_dir:ge,local_files_only:Ie,revision:Xe,legacy:_t});return new this(...ft)}_call(M,{text_pair:Q=null,add_special_tokens:pe=!0,padding:ge=!1,truncation:Ie=null,max_length:Xe=null,return_tensor:_t=!0,return_token_type_ids:ft=null}={}){const vt=Array.isArray(M);let Qe;if(vt){if(M.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(M.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Qe=M.map((Xt,gs)=>this._encode_plus(Xt,{text_pair:Q[gs],add_special_tokens:pe,return_token_type_ids:ft}))}else Qe=M.map(Xt=>this._encode_plus(Xt,{add_special_tokens:pe,return_token_type_ids:ft}))}else{if(M==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Qe=[this._encode_plus(M,{text_pair:Q,add_special_tokens:pe,return_token_type_ids:ft})]}if(Xe===null?ge==="max_length"?Xe=this.model_max_length:Xe=(0,te.max)(Qe.map(Xt=>Xt.input_ids.length))[0]:Ie||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."),Xe=Math.min(Xe,this.model_max_length??1/0),ge||Ie)for(let Xt=0;XtXe?Ie&&an(Qe[Xt],Xe):ge&&Cr(Qe[Xt],Xe,gs=>gs==="input_ids"?this.pad_token_id:0,this.padding_side));const It={};if(_t){if(!(ge&&Ie)&&Qe.some(gs=>{for(const Se of Object.keys(gs))if(gs[Se].length!==Qe[0][Se]?.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 Xt=[Qe.length,Qe[0].input_ids.length];for(const gs of Object.keys(Qe[0]))It[gs]=new U.Tensor("int64",BigInt64Array.from(Qe.flatMap(Se=>Se[gs]).map(BigInt)),Xt)}else{for(const Xt of Object.keys(Qe[0]))It[Xt]=Qe.map(gs=>gs[Xt]);if(!vt)for(const Xt of Object.keys(It))It[Xt]=It[Xt][0]}return It}_encode_text(M){return M===null?null:(this.added_tokens_regex?M.split(this.added_tokens_regex).filter(ge=>ge):[M]).map((ge,Ie)=>{if(this.added_tokens.find(_t=>_t.content===ge)!==void 0)return ge;{if(this.remove_space===!0&&(ge=ge.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ge=G(ge)),this.normalizer!==null&&(ge=this.normalizer(ge)),ge.length===0)return[];const _t=this.pre_tokenizer!==null?this.pre_tokenizer(ge,{section_index:Ie}):[ge];return this.model(_t)}}).flat()}_encode_plus(M,{text_pair:Q=null,add_special_tokens:pe=!0,return_token_type_ids:ge=null}={}){const{tokens:Ie,token_type_ids:Xe}=this._tokenize_helper(M,{pair:Q,add_special_tokens:pe}),_t=this.model.convert_tokens_to_ids(Ie),ft={input_ids:_t,attention_mask:new Array(_t.length).fill(1)};return(ge??this.return_token_type_ids)&&Xe&&(ft.token_type_ids=Xe),ft}_tokenize_helper(M,{pair:Q=null,add_special_tokens:pe=!1}={}){const ge=this._encode_text(M),Ie=this._encode_text(Q);return this.post_processor?this.post_processor(ge,Ie,{add_special_tokens:pe}):{tokens:(0,O.mergeArrays)(ge??[],Ie??[])}}tokenize(M,{pair:Q=null,add_special_tokens:pe=!1}={}){return this._tokenize_helper(M,{pair:Q,add_special_tokens:pe}).tokens}encode(M,{text_pair:Q=null,add_special_tokens:pe=!0,return_token_type_ids:ge=null}={}){return this._encode_plus(M,{text_pair:Q,add_special_tokens:pe,return_token_type_ids:ge}).input_ids}batch_decode(M,Q={}){return M instanceof U.Tensor&&(M=M.tolist()),M.map(pe=>this.decode(pe,Q))}decode(M,Q={}){if(M instanceof U.Tensor&&(M=re(M)),!Array.isArray(M)||M.length===0||!(0,O.isIntegralNumber)(M[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(M,Q)}decode_single(M,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:pe=null}){let ge=this.model.convert_ids_to_tokens(M);Q&&(ge=ge.filter(Xe=>!this.special_tokens.includes(Xe)));let Ie=this.decoder?this.decoder(ge):ge.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ie=Ie.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(Ie=Ie.trim())),(pe??this.clean_up_tokenization_spaces)&&(Ie=ae(Ie)),Ie}get_chat_template({chat_template:M=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const pe=this.chat_template;if(M!==null&&Object.hasOwn(pe,M))M=pe[M];else if(M===null)if(Q!==null&&"tool_use"in pe)M=pe.tool_use;else if("default"in pe)M=pe.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(pe).sort()}.`)}else if(M===null)if(this.chat_template)M=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return M}apply_chat_template(M,{tools:Q=null,documents:pe=null,chat_template:ge=null,add_generation_prompt:Ie=!1,tokenize:Xe=!0,padding:_t=!1,truncation:ft=!1,max_length:vt=null,return_tensor:Qe=!0,return_dict:It=!1,tokenizer_kwargs:Xt={},...gs}={}){if(ge=this.get_chat_template({chat_template:ge,tools:Q}),typeof ge!="string")throw Error(`chat_template must be a string, but got ${typeof ge}`);let Se=this._compiled_template_cache.get(ge);Se===void 0&&(Se=new P.Template(ge),this._compiled_template_cache.set(ge,Se));const Ps=Object.create(null);for(const Rs of Rr){const dr=this.getToken(Rs);dr&&(Ps[Rs]=dr)}const js=Se.render({messages:M,add_generation_prompt:Ie,tools:Q,documents:pe,...Ps,...gs});if(Xe){const Rs=this._call(js,{add_special_tokens:!1,padding:_t,truncation:ft,max_length:vt,return_tensor:Qe,...Xt});return It?Rs:Rs.input_ids}return js}}class Nr extends Ot{return_token_type_ids=!0}class br extends Ot{return_token_type_ids=!0}class kr extends Ot{return_token_type_ids=!0}class vr extends Ot{return_token_type_ids=!0}class Sr extends Ot{return_token_type_ids=!0}class Js extends Ot{return_token_type_ids=!0}class ur extends Ot{return_token_type_ids=!0}class Tr extends Ot{return_token_type_ids=!0}class jr extends Ot{return_token_type_ids=!0}class rr extends Ot{}class it extends Ot{}class dt extends Ot{return_token_type_ids=!0;constructor(M,Q){super(M,Q),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class St extends Ot{return_token_type_ids=!0}class cs extends Ot{}class Ur extends Ot{}class rs extends Ot{}class Vr extends Ot{constructor(M,Q){super(M,Q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(pe=>this.languageRegex.test(pe)),this.lang_to_token=pe=>pe}_build_translation_inputs(M,Q,pe){return Kr(this,M,Q,pe)}}class $r extends Vr{}class qn extends Ot{}class Tn extends Ot{}const Wr="▁";class xn extends Ot{padding_side="left";constructor(M,Q){super(M,Q),this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new ts({replacement:Wr,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 Q=super._encode_text(Wr+M.replaceAll(Wr," "));return Q.length>1&&Q[0]===Wr&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class Ar extends Ot{}class Pn extends Ot{}class Xn extends Ot{}class Ir extends Ot{}class fr extends Ot{}class Zs extends Ot{}class ln extends Ot{}class Gr extends Ot{}class un extends Ot{}function Kr(Te,M,Q,pe){if(!("language_codes"in Te)||!Array.isArray(Te.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Te)||!(Te.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Te)||typeof Te.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ge=pe.src_lang,Ie=pe.tgt_lang;if(!Te.language_codes.includes(Ie))throw new Error(`Target language code "${Ie}" is not valid. Must be one of: {${Te.language_codes.join(", ")}}`);if(ge!==void 0){if(!Te.language_codes.includes(ge))throw new Error(`Source language code "${ge}" is not valid. Must be one of: {${Te.language_codes.join(", ")}}`);for(const Xe of Te.post_processor.config.single)if("SpecialToken"in Xe&&Te.languageRegex.test(Xe.SpecialToken.id)){Xe.SpecialToken.id=Te.lang_to_token(ge);break}}return pe.forced_bos_token_id=Te.model.convert_tokens_to_ids([Te.lang_to_token(Ie)])[0],Te._call(M,Q)}class dn extends Ot{constructor(M,Q){super(M,Q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(pe=>this.languageRegex.test(pe)),this.lang_to_token=pe=>pe}_build_translation_inputs(M,Q,pe){return Kr(this,M,Q,pe)}}class Ft extends Ot{constructor(M,Q){super(M,Q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(pe=>this.languageRegex.test(pe)).map(pe=>pe.slice(2,-2)),this.lang_to_token=pe=>`__${pe}__`}_build_translation_inputs(M,Q,pe){return Kr(this,M,Q,pe)}}class cn extends Ot{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(M,{return_timestamps:Q=!1,return_language:pe=!1,time_precision:ge=null,force_full_sequences:Ie=!0}={}){if(ge===null)throw Error("Must specify time_precision");let Xe=null;const _t=Q==="word";function ft(){return{language:Xe,timestamp:[null,null],text:""}}const vt=[];let Qe=ft(),It=0;const Xt=this.timestamp_begin,Se=Xt+1500;let Ps=[],js=[],Rs=!1,dr=null;const zt=new Set(this.all_special_ids);for(const Zt of M){const us=Zt.tokens,xt=_t?Zt.token_timestamps:null;let os=null,wr=Xt;if("stride"in Zt){const[Mt,Es,Oe]=Zt.stride;if(It-=Es,dr=Mt-Oe,Es&&(wr=Es/ge+Xt),Oe)for(let gt=us.length-1;gt>=0;--gt){const tr=Number(us[gt]);if(tr>=Xt){if(os!==null&&(tr-Xt)*ge=Xt&&Es<=Se){const Oe=(Es-Xt)*ge+It,gt=(0,te.round)(Oe,2);if(os!==null&&Es>=os)Rs=!0;else if(Rs||Ps.length>0&&Es0?(Ps.push(As),_t&&js.push(Vs)):Ps.every(Mt=>Mt.length===0)&&(Qe=ft(),Ps=[],As=[],js=[],Vs=[])}if(Ps.length>0){if(Ie&&Q)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Zt,us]=this.findLongestCommonSequence(Ps,js),xt=this.decode(Zt);Qe.text=xt,_t&&(Qe.words=this.collateWordTimestamps(Zt,us,Xe)),vt.push(Qe)}let zs=Object.create(null);const gr=vt.map(Zt=>Zt.text).join("");if(Q||pe){for(let Zt=0;Zt0;let _t=Xe?[]:null,ft=Xe?Q[0]:null;for(let vt=1;vtEs===wr[Oe]&&ft[gr+Oe]<=Q[vt][xt+Oe]).length:As=us.filter((Es,Oe)=>Es===wr[Oe]).length;const Vs=zs/1e4,Mt=As/zs+Vs;As>1&&Mt>It&&(It=Mt,Xt=[gr,Zt,xt,os])}const[Se,Ps,js,Rs]=Xt,dr=Math.floor((Ps+Se)/2),zt=Math.floor((Rs+js)/2);Ie.push(...pe.slice(0,dr)),pe=Qe.slice(zt),ge=pe.length,Xe&&(_t.push(...ft.slice(0,dr)),ft=Q[vt].slice(zt))}return Ie.push(...pe),Xe?(_t.push(...ft),[Ie,_t]):[Ie,[]]}collateWordTimestamps(M,Q,pe){const[ge,Ie,Xe]=this.combineTokensIntoWords(M,pe),_t=[];for(let ft=0;ft=ge){const _t=((Xe-ge)*pe).toFixed(2);Ie.push(`<|${_t}|>`),Ie.push([])}else Ie[Ie.length-1].push(Xe);return Ie=Ie.map(Xe=>typeof Xe=="string"?Xe:super.decode(Xe,Q)),Ie.join("")}splitTokensOnUnicode(M){const Q=this.decode(M,{decode_with_timestamps:!0}),pe="�",ge=[],Ie=[],Xe=[];let _t=[],ft=[],vt=0;for(let Qe=0;Qe=this.model.tokens_to_ids.get("<|endoftext|>"),Se=Qe.startsWith(" "),Ps=Qe.trim(),js=ft.test(Ps);if(gs||Se||js||Ie.length===0)Ie.push(Qe),Xe.push(It),_t.push(Xt);else{const Rs=Ie.length-1;Ie[Rs]+=Qe,Xe[Rs].push(...It),_t[Rs].push(...Xt)}}return[Ie,Xe,_t]}mergePunctuations(M,Q,pe,ge,Ie){const Xe=structuredClone(M),_t=structuredClone(Q),ft=structuredClone(pe);let vt=Xe.length-2,Qe=Xe.length-1;for(;vt>=0;)Xe[vt].startsWith(" ")&&ge.includes(Xe[vt].trim())?(Xe[Qe]=Xe[vt]+Xe[Qe],_t[Qe]=(0,O.mergeArrays)(_t[vt],_t[Qe]),ft[Qe]=(0,O.mergeArrays)(ft[vt],ft[Qe]),Xe[vt]="",_t[vt]=[],ft[vt]=[]):Qe=vt,--vt;for(vt=0,Qe=1;QeIt),_t.filter(It=>It.length>0),ft.filter(It=>It.length>0)]}}class En extends Ot{}class Cn extends Ot{}class kn extends Ot{}class Or extends Ot{constructor(M,Q){super(M,Q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(pe=>this.languageRegex.test(pe)),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[Q,...pe]=M.trim().split(this.languageRegex);if(pe.length===0)return super._encode_text(Q);if(pe.length===2){const[ge,Ie]=pe;return this.supported_language_codes.includes(ge)||console.warn(`Unsupported language code "${ge}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,O.mergeArrays)([ge],super._encode_text(Ie))}}}class Sn extends Ot{}class pn extends Ot{}class $n extends Ot{}class ns extends Ot{}class er extends Ot{}class hn extends Ot{constructor(M,Q){super(M,Q),this.decoder=new Qt({})}}class An extends Ot{}class Hr extends Ot{}class In{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:cs,DistilBertTokenizer:rr,CamembertTokenizer:it,DebertaTokenizer:Sr,DebertaV2Tokenizer:Js,BertTokenizer:Nr,HerbertTokenizer:ur,ConvBertTokenizer:Tr,RoFormerTokenizer:jr,XLMTokenizer:dt,ElectraTokenizer:St,MobileBertTokenizer:kr,SqueezeBertTokenizer:vr,AlbertTokenizer:br,GPT2Tokenizer:Ur,BartTokenizer:rs,MBartTokenizer:Vr,MBart50Tokenizer:$r,RobertaTokenizer:qn,WhisperTokenizer:cn,CodeGenTokenizer:En,CLIPTokenizer:Cn,SiglipTokenizer:kn,MarianTokenizer:Or,BloomTokenizer:Tn,NllbTokenizer:dn,M2M100Tokenizer:Ft,LlamaTokenizer:xn,CodeLlamaTokenizer:Ar,XLMRobertaTokenizer:Pn,MPNetTokenizer:Xn,FalconTokenizer:Ir,GPTNeoXTokenizer:fr,EsmTokenizer:Zs,Wav2Vec2CTCTokenizer:Sn,BlenderbotTokenizer:pn,BlenderbotSmallTokenizer:$n,SpeechT5Tokenizer:ns,NougatTokenizer:er,VitsTokenizer:hn,Qwen2Tokenizer:ln,GemmaTokenizer:Gr,Grok1Tokenizer:un,CohereTokenizer:An,MgpstrTokenizer:Hr,PreTrainedTokenizer:Ot};static async from_pretrained(M,{progress_callback:Q=null,config:pe=null,cache_dir:ge=null,local_files_only:Ie=!1,revision:Xe="main",legacy:_t=null}={}){const[ft,vt]=await T(M,{progress_callback:Q,config:pe,cache_dir:ge,local_files_only:Ie,revision:Xe,legacy:_t}),Qe=vt.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let It=this.TOKENIZER_CLASS_MAPPING[Qe];return It||(console.warn(`Unknown tokenizer class "${Qe}", attempting to construct from base class.`),It=Ot),new It(ft,vt)}}},"./src/utils/audio.js":(Ce,A,r)=>{r.r(A),r.d(A,{hamming:()=>b,hanning:()=>P,mel_filter_bank:()=>R,read_audio:()=>U,spectrogram:()=>w,window_function:()=>C});var g=r("./src/utils/hub.js"),O=r("./src/utils/maths.js"),j=r("./src/utils/core.js"),te=r("./src/utils/tensor.js");async function U(x,J){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 q=await(await(0,g.getFile)(x)).arrayBuffer(),le=new AudioContext({sampleRate:J});typeof J>"u"&&console.warn(`No sampling rate provided, using default of ${le.sampleRate}Hz.`);const ce=await le.decodeAudioData(q);let fe;if(ce.numberOfChannels===2){const Pe=Math.sqrt(2),be=ce.getChannelData(0),De=ce.getChannelData(1);fe=new Float32Array(be.length);for(let Ge=0;Ge2595*Math.log10(1+x/700),kaldi:x=>1127*Math.log(1+x/700),slaney:(x,J=1e3,q=15,le=27/Math.log(6.4))=>x>=J?q+Math.log(x/J)*le:3*x/200};function v(x,J="htk"){const q=T[J];if(!q)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof x=="number"?q(x):x.map(le=>q(le))}const z={htk:x=>700*(10**(x/2595)-1),kaldi:x=>700*(Math.exp(x/1127)-1),slaney:(x,J=1e3,q=15,le=Math.log(6.4)/27)=>x>=q?J*Math.exp(le*(x-q)):200*x/3};function K(x,J="htk"){const q=z[J];if(!q)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof x=="number"?q(x):x.map(le=>q(le))}function re(x,J){const q=Float64Array.from({length:J.length-1},(Pe,be)=>J[be+1]-J[be]),le=Array.from({length:x.length},()=>new Array(J.length));for(let Pe=0;Penew Array(x.length));for(let Pe=0;Pex+le*fe)}function R(x,J,q,le,ce,fe=null,Pe="htk",be=!1){if(fe!==null&&fe!=="slaney")throw new Error('norm must be one of null or "slaney"');const De=v(q,Pe),Ge=v(le,Pe),Ne=ae(De,Ge,J+2);let lt=K(Ne,Pe),ue;if(be){const he=ce/(x*2);ue=v(Float64Array.from({length:x},(ve,Le)=>Le*he),Pe),lt=Ne}else ue=ae(0,Math.floor(ce/2),x);const Z=re(ue,lt);if(fe!==null&&fe==="slaney")for(let he=0;hece)throw Error(`frame_length (${q}) may not be larger than fft_length (${ce})`);if(Ae!==q)throw new Error(`Length of the window (${Ae}) must equal frame_length (${q})`);if(le<=0)throw new Error("hop_length must be greater than zero");if(fe===null&&Ne!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(Pe){if(be!=="reflect")throw new Error(`pad_mode="${be}" not implemented yet.`);const I=Math.floor((ce-1)/2)+1;x=G(x,I,I)}let oe=Math.floor(1+Math.floor((x.length-q)/le));Ze!==null&&oeoe?ne&&(Re=Ke):Re=je=Ke);const We=new O.FFT(ce),ze=new Float64Array(ce),Ye=new Float64Array(We.outputBufferSize),nt=new Float32Array(Me*Re);for(let I=0;I=1;--_e)ze[_e]-=Ge*ze[_e-1];ze[0]*=1-Ge}for(let _e=0;_eMath.pow(be,.85));break;default:throw new Error(`Unknown window type ${J}.`)}if(q&&(Pe=Pe.subarray(0,x)),le===null)return Pe;if(x>le)throw new Error(`Length of the window (${x}) may not be larger than frame_length (${le})`);return Pe}},"./src/utils/constants.js":(Ce,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>y,CONFIG_NAME:()=>O,FEATURE_EXTRACTOR_NAME:()=>j,GENERATION_CONFIG_NAME:()=>P,GITHUB_ISSUE_URL:()=>g,IMAGE_PROCESSOR_NAME:()=>te,PROCESSOR_NAME:()=>U});const g="https://github.com/huggingface/transformers.js/issues/new/choose",O="config.json",j="preprocessor_config.json",te=j,U="processor_config.json",y="chat_template.json",P="generation_config.json"},"./src/utils/core.js":(Ce,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>P,calculateReflectOffset:()=>z,count:()=>ae,dispatchCallback:()=>g,escapeRegExp:()=>j,isIntegralNumber:()=>U,isNullishDimension:()=>y,isTypedArray:()=>te,len:()=>re,mergeArrays:()=>T,pick:()=>K,pop:()=>b,product:()=>v,reverseDictionary:()=>O});function g(R,G){R&&R(G)}function O(R){return Object.fromEntries(Object.entries(R).map(([G,H])=>[H,G]))}function j(R){return R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function te(R){return R?.prototype?.__proto__?.constructor?.name==="TypedArray"}function U(R){return Number.isInteger(R)||typeof R=="bigint"}function y(R){return R==null||R===-1}function P(R){const G=[];let H=R;for(;Array.isArray(H);)G.push(H.length),H=H[0];return G}function b(R,G,H=void 0){const D=R[G];if(D!==void 0)return delete R[G],D;if(H===void 0)throw Error(`Key ${G} does not exist in object.`);return H}function T(...R){return Array.prototype.concat.apply([],R)}function v(...R){return R.reduce((G,H)=>G.flatMap(D=>H.map($=>[D,$])))}function z(R,G){return Math.abs((R+G)%(2*G)-G)}function K(R,G){return Object.assign({},...G.map(H=>{if(R[H]!==void 0)return{[H]:R[H]}}))}function re(R){let G=0;for(const H of R)++G;return G}function ae(R,G){let H=0;for(const D of R)D===G&&++H;return H}},"./src/utils/data-structures.js":(Ce,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>O,PriorityQueue:()=>g,TokenLattice:()=>te});class g{constructor(P=(T,v)=>T>v,b=1/0){this._heap=[],this._comparator=P,this._maxSize=b}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...P){return this.extend(P)}extend(P){for(const b of P)if(this.size0&&this._swap(0,b),this._heap.pop(),this._siftDown(),P}replace(P){const b=this.peek();return this._heap[0]=P,this._siftDown(),b}_parent(P){return(P+1>>>1)-1}_left(P){return(P<<1)+1}_right(P){return P+1<<1}_greater(P,b){return this._comparator(this._heap[P],this._heap[b])}_swap(P,b){const T=this._heap[P];this._heap[P]=this._heap[b],this._heap[b]=T}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(P){for(;P>0&&this._greater(P,this._parent(P));)this._swap(P,this._parent(P)),P=this._parent(P)}_siftDown(){let P=0;for(;this._left(P)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const v=new U(this.bosTokenId,0,0,0,0),z=new U(this.eosTokenId,1,this.len,0,0);this.nodes.push(v.clone()),this.nodes.push(z.clone()),this.beginNodes[this.len].push(z),this.endNodes[0].push(v)}insert(P,b,T,v){const z=this.nodes.length,K=new U(v,z,P,b,T);this.beginNodes[P].push(K),this.endNodes[P+b].push(K),this.nodes.push(K)}viterbi(){const P=this.len;let b=0;for(;b<=P;){if(this.beginNodes[b].length==0)return[];for(let re of this.beginNodes[b]){re.prev=null;let ae=0,R=null;for(let G of this.endNodes[b]){const H=G.backtraceScore+re.score;(R===null||H>ae)&&(R=G.clone(),ae=H)}if(R!==null)re.prev=R,re.backtraceScore=ae;else return[]}++b}const T=[],z=this.beginNodes[P][0].prev;if(z===null)return[];let K=z.clone();for(;K.prev!==null;)T.push(K.clone()),K=K.clone().prev.clone();return T.reverse(),T}piece(P){return this.chars.slice(P.pos,P.pos+P.length).join("")}tokens(){return this.viterbi().map(b=>this.piece(b))}tokenIds(){return this.viterbi().map(b=>b.tokenId)}}class U{constructor(P,b,T,v,z){this.tokenId=P,this.nodeId=b,this.pos=T,this.length=v,this.score=z,this.prev=null,this.backtraceScore=0}clone(){const P=new U(this.tokenId,this.nodeId,this.pos,this.length,this.score);return P.prev=this.prev,P.backtraceScore=this.backtraceScore,P}}},"./src/utils/devices.js":(Ce,A,r)=>{r.r(A),r.d(A,{DEVICE_TYPES:()=>g});const g=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":(Ce,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>te,DEFAULT_DEVICE_DTYPE_MAPPING:()=>U,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>y,isWebGpuFp16Supported:()=>j});var g=r("./src/env.js"),O=r("./src/utils/devices.js");const j=function(){let P;return async function(){if(P===void 0)if(!g.apis.IS_WEBGPU_AVAILABLE)P=!1;else try{P=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{P=!1}return P}}(),te=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),U=Object.freeze({[O.DEVICE_TYPES.wasm]:te.q8}),y=Object.freeze({[te.fp32]:"",[te.fp16]:"_fp16",[te.int8]:"_int8",[te.uint8]:"_uint8",[te.q8]:"_quantized",[te.q4]:"_q4",[te.q4f16]:"_q4f16",[te.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Ce,A,r)=>{r.r(A),r.d(A,{Callable:()=>g});const g=class{constructor(){let O=function(...j){return O._call(...j)};return Object.setPrototypeOf(O,new.target.prototype)}_call(...O){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Ce,A,r)=>{r.r(A),r.d(A,{getFile:()=>b,getModelFile:()=>re,getModelJSON:()=>ae});var g=r("?7a2c"),O=r("?a42a"),j=r("./src/env.js"),te=r("./src/utils/core.js");const U={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class y{constructor(D){if(this.filePath=D,this.headers=new Headers,this.exists=g.existsSync(D),this.exists){this.status=200,this.statusText="OK";let $=g.statSync(D);this.headers.set("content-length",$.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(C){w.arrayBuffer().then(x=>{C.enqueue(new Uint8Array(x)),C.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const D=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",U[D]??"application/octet-stream")}clone(){let D=new y(this.filePath);return D.exists=this.exists,D.status=this.status,D.statusText=this.statusText,D.headers=new Headers(this.headers),D}async arrayBuffer(){return(await g.promises.readFile(this.filePath)).buffer}async blob(){const D=await g.promises.readFile(this.filePath);return new Blob([D],{type:this.headers.get("content-type")})}async text(){return await g.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function P(H,D=null,$=null){let w;try{w=new URL(H)}catch{return!1}return!(D&&!D.includes(w.protocol)||$&&!$.includes(w.hostname))}async function b(H){if(j.env.useFS&&!P(H,["http:","https:","blob:"]))return new y(H);if(typeof process<"u"&&process?.release?.name==="node"){const D=!!hh?.TESTING_REMOTELY,$=j.env.version,w=new Headers;if(w.set("User-Agent",`transformers.js/${$}; is_ci/${D};`),P(H,["http:","https:"],["huggingface.co","hf.co"])){const x=hh?.HF_TOKEN??hh?.HF_ACCESS_TOKEN;x&&w.set("Authorization",`Bearer ${x}`)}return fetch(H,{headers:w})}else return fetch(H)}const T={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function v(H,D,$){if(!$)return null;const w=T[H]??`Error (${H}) occurred while trying to load file`;throw Error(`${w}: "${D}".`)}class z{constructor(D){this.path=D}async match(D){let $=O.join(this.path,D),w=new y($);if(w.exists)return w}async put(D,$){const w=Buffer.from(await $.arrayBuffer());let C=O.join(this.path,D);try{await g.promises.mkdir(O.dirname(C),{recursive:!0}),await g.promises.writeFile(C,w)}catch(x){console.warn("An error occurred while writing the file to cache:",x)}}}async function K(H,...D){for(let $ of D)try{let w=await H.match($);if(w)return w}catch{continue}}async function re(H,D,$=!0,w={}){if(!j.env.allowLocalModels){if(w.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!j.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,te.dispatchCallback)(w.progress_callback,{status:"initiate",name:H,file:D});let C;if(!C&&j.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{C=await caches.open("transformers-cache")}catch(lt){console.warn("An error occurred while opening the browser cache:",lt)}}if(!C&&j.env.useFSCache&&(C=new z(w.cache_dir??j.env.cacheDir)),!C&&j.env.useCustomCache){if(!j.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!j.env.customCache.match||!j.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");C=j.env.customCache}const x=w.revision??"main";let J=G(H,D),q=G(j.env.localModelPath,J),le=G(j.env.remoteHost,j.env.remotePathTemplate.replaceAll("{model}",H).replaceAll("{revision}",encodeURIComponent(x)),D),ce=x==="main"?J:G(H,x,D),fe,Pe=C instanceof z?ce:le,be=!1,De;C&&(De=await K(C,q,Pe));const Ge=De!==void 0;if(De===void 0){if(j.env.allowLocalModels)if(P(J,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${J}.`);if(!j.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${J}.`)}else try{De=await b(q),fe=q}catch(ue){console.warn(`Unable to load from local path "${q}": "${ue}"`)}if(De===void 0||De.status===404){if(w.local_files_only||!j.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${q}".`);return null}if(De=await b(le),De.status!==200)return v(De.status,le,$);fe=Pe}be=C&&typeof Response<"u"&&De instanceof Response&&De.status===200}(0,te.dispatchCallback)(w.progress_callback,{status:"download",name:H,file:D});let Ne;return w.progress_callback?Ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ne=new Uint8Array(await De.arrayBuffer()),(0,te.dispatchCallback)(w.progress_callback,{status:"progress",name:H,file:D,progress:100,loaded:Ne.length,total:Ne.length})):Ne=await R(De,lt=>{(0,te.dispatchCallback)(w.progress_callback,{status:"progress",name:H,file:D,...lt})}):Ne=new Uint8Array(await De.arrayBuffer()),be&&fe&&await C.match(fe)===void 0&&await C.put(fe,new Response(Ne,{headers:De.headers})).catch(lt=>{console.warn(`Unable to add response to browser cache: ${lt}.`)}),(0,te.dispatchCallback)(w.progress_callback,{status:"done",name:H,file:D}),Ne}async function ae(H,D,$=!0,w={}){let C=await re(H,D,$,w);if(C===null)return{};let J=new TextDecoder("utf-8").decode(C);return JSON.parse(J)}async function R(H,D){const $=H.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt($??"0"),C=new Uint8Array(w),x=0;const J=H.body.getReader();async function q(){const{done:le,value:ce}=await J.read();if(le)return;let fe=x+ce.length;if(fe>w){w=fe;let be=new Uint8Array(w);be.set(C),C=be}C.set(ce,x),x=fe;const Pe=x/w*100;return D({progress:Pe,loaded:x,total:w}),q()}return await q(),C}function G(...H){return H=H.map((D,$)=>($&&(D=D.replace(new RegExp("^/"),"")),$!==H.length-1&&(D=D.replace(new RegExp("/$"),"")),D)),H.join("/")}},"./src/utils/image.js":(Ce,A,r)=>{r.r(A),r.d(A,{RawImage:()=>K,load_image:()=>re});var g=r("./src/utils/core.js"),O=r("./src/utils/hub.js"),j=r("./src/env.js"),te=r("./src/utils/tensor.js"),U=r("?2b25");let y,P,b;const T=j.apis.IS_BROWSER_ENV||j.apis.IS_WEBWORKER_ENV;if(T)y=(ae,R)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ae,R)},b=self.createImageBitmap,P=self.ImageData;else if(U)b=async ae=>{const G=(await ae.metadata()).channels,{data:H,info:D}=await ae.rotate().raw().toBuffer({resolveWithObject:!0}),$=new K(new Uint8ClampedArray(H),D.width,D.height,D.channels);return G!==void 0&&G!==D.channels&&$.convert(G),$};else throw new Error("Unable to load image processing library.");const v={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},z=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class K{constructor(R,G,H,D){this.data=R,this.width=G,this.height=H,this.channels=D}get size(){return[this.width,this.height]}static async read(R){if(R instanceof K)return R;if(typeof R=="string"||R instanceof URL)return await this.fromURL(R);throw new Error(`Unsupported input type: ${typeof R}`)}static fromCanvas(R){if(!T)throw new Error("fromCanvas() is only supported in browser environments.");const H=R.getContext("2d").getImageData(0,0,R.width,R.height).data;return new K(H,R.width,R.height,4)}static async fromURL(R){const G=await(0,O.getFile)(R);if(G.status!==200)throw new Error(`Unable to read image from "${R}" (${G.status} ${G.statusText})`);const H=await G.blob();return this.fromBlob(H)}static async fromBlob(R){if(T){const G=await b(R),H=y(G.width,G.height).getContext("2d");return H.drawImage(G,0,0),new this(H.getImageData(0,0,G.width,G.height).data,G.width,G.height,4)}else{const G=U(await R.arrayBuffer());return await b(G)}}static fromTensor(R,G="CHW"){if(R.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${R.dims.length} dimensions.`);if(G==="CHW")R=R.transpose(1,2,0);else if(G!=="HWC")throw new Error(`Unsupported channel format: ${G}`);if(!(R.data instanceof Uint8ClampedArray||R.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${R.type}`);switch(R.dims[2]){case 1:case 2:case 3:case 4:return new K(R.data,R.dims[1],R.dims[0],R.dims[2]);default:throw new Error(`Unsupported number of channels: ${R.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const R=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let G=0,H=0;G=0?x=H:q=-H,D>=0?J=D:le=-D,C.drawImage(w,x,J,R,G,q,le,R,G),new K(C.getImageData(0,0,R,G).data,R,G,4).convert($)}else{let $=this.toSharp();if(H>=0&&D>=0)$=$.extract({left:Math.floor(H),top:Math.floor(D),width:R,height:G});else if(H<=0&&D<=0){const w=Math.floor(-D),C=Math.floor(-H);$=$.extend({top:w,left:C,right:R-this.width-C,bottom:G-this.height-w})}else{let w=[0,0],C=0;D<0?(w[0]=Math.floor(-D),w[1]=G-this.height-w[0]):C=Math.floor(D);let x=[0,0],J=0;H<0?(x[0]=Math.floor(-H),x[1]=R-this.width-x[0]):J=Math.floor(H),$=$.extend({top:w[0],bottom:w[1],left:x[0],right:x[1]}).extract({left:J,top:C,width:R,height:G})}return await b($)}}async toBlob(R="image/png",G=1){if(!T)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:R,quality:G})}toTensor(R="CHW"){let G=new te.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(R!=="HWC")if(R==="CHW")G=G.permute(2,0,1);else throw new Error(`Unsupported channel format: ${R}`);return G}toCanvas(){if(!T)throw new Error("toCanvas() is only supported in browser environments.");const R=this.clone().rgba(),G=y(R.width,R.height),H=new P(R.data,R.width,R.height);return G.getContext("2d").putImageData(H,0,0),G}split(){const{data:R,width:G,height:H,channels:D}=this,$=R.constructor,w=R.length/D,C=Array.from({length:D},()=>new $(w));for(let x=0;xnew K(x,G,H,1))}_update(R,G,H,D=null){return this.data=R,this.width=G,this.height=H,D!==null&&(this.channels=D),this}clone(){return new K(this.data.slice(),this.width,this.height,this.channels)}convert(R){if(this.channels===R)return this;switch(R){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(R){if(T){if(j.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const G=R.split(".").pop().toLowerCase(),H=z.get(G)??"image/png",D=await this.toBlob(H),$=URL.createObjectURL(D),w=document.createElement("a");w.href=$,w.download=R,w.click(),w.remove()}else{if(j.env.useFS)return await this.toSharp().toFile(R);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(T)throw new Error("toSharp() is only supported in server-side environments.");return U(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const re=K.read.bind(K)},"./src/utils/maths.js":(Ce,A,r)=>{r.r(A),r.d(A,{FFT:()=>re,bankers_round:()=>G,cos_sim:()=>y,dot:()=>U,dynamic_time_warping:()=>H,interpolate_data:()=>g,log_softmax:()=>te,magnitude:()=>P,max:()=>T,medianFilter:()=>ae,min:()=>b,permute_data:()=>O,round:()=>R,softmax:()=>j});function g(D,[$,w,C],[x,J],q="bilinear",le=!1){const ce=J/C,fe=x/w,Pe=new D.constructor(x*J*$),be=w*C,De=x*J;for(let Ge=0;Ge=0;--le)x[le]=ce,C[le]=$[w[le]],ce*=C[le];const J=w.map((le,ce)=>x[w.indexOf(ce)]),q=new D.constructor(D.length);for(let le=0;le=0;--fe)ce+=Pe%$[fe]*J[fe],Pe=Math.floor(Pe/$[fe]);q[ce]=D[le]}return[q,C]}function j(D){const $=T(D)[0],w=D.map(J=>Math.exp(J-$)),C=w.reduce((J,q)=>J+q,0);return w.map(J=>J/C)}function te(D){const $=T(D)[0];let w=0;for(let J=0;JJ-$-C)}function U(D,$){let w=0;for(let C=0;C$+w*w,0))}function b(D){if(D.length===0)throw Error("Array must not be empty");let $=D[0],w=0;for(let C=1;C$&&($=D[C],w=C);return[Number($),w]}function v(D){return D>0&&(D&D-1)===0}class z{constructor($){if(this.size=$|0,this.size<=1||!v(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=$<<1,this.table=new Float64Array(this.size*2);for(let C=0;CC;C<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>x&3)<>>1);for(let x=0;x<$.length;x+=2)C[x>>>1]=$[x];return C}toComplexArray($,w){const C=w||this.createComplexArray();for(let x=0;x>>1],C[x+1]=0;return C}transform($,w){if($===w)throw new Error("Input and output buffers must be different");this._transform4($,w,1)}realTransform($,w){if($===w)throw new Error("Input and output buffers must be different");this._realTransform4($,w,1)}inverseTransform($,w){if($===w)throw new Error("Input and output buffers must be different");this._transform4($,w,-1);for(let C=0;C<$.length;++C)$[C]/=this.size}_transform4($,w,C){const x=this._csize;let q=1<>=2;q>=2;q>>=2){le=x/q<<1;const De=le>>>2;for(ce=0;ce>>1,q>>>1)}else for(ce=0,fe=0;ce>>1,q>>>1,C)}const be=this.table;for(q>>=2;q>=2;q>>=2){le=x/q<<1;const Ge=le>>>1,Ne=Ge>>>1,lt=Ne>>>1;for(ce=0;ce>>1;for(let Ge=2;Ge>1;++Pe){const be=(Pe+1-$)**2/2,De=Math.sqrt(ce**2+fe**2)**be,Ge=be*Math.atan2(fe,ce),Ne=2*Pe;J[Ne]=De*Math.cos(Ge),J[Ne+1]=De*Math.sin(Ge),q[Ne]=J[Ne],q[Ne+1]=-J[Ne+1]}this._slicedChirpBuffer=J.subarray(w,C),this._f=new z(x>>1),this._f.transform(this._chirpBuffer,q)}_transform($,w,C){const x=this._buffer1,J=this._buffer2,q=this._outBuffer1,le=this._outBuffer2,ce=this._chirpBuffer,fe=this._slicedChirpBuffer,Pe=this._a;if(C)for(let be=0;be>1,Ne=w[Ge];x[be]=Ne*fe[be],x[De]=Ne*fe[De]}else for(let be=0;be=D.length&&(ce=2*(D.length-1)-ce),C[q++]=D[ce]}C.sort(),w[J]=C[x]}return w}function R(D,$){const w=Math.pow(10,$);return Math.round(D*w)/w}function G(D){const $=Math.round(D);return Math.abs(D)%1===.5?$%2===0?$:$-1:$}function H(D){const $=D.length,w=D[0].length,C=[$+1,w+1],x=Array.from({length:C[0]},()=>Array(C[1]).fill(1/0));x[0][0]=0;const J=Array.from({length:C[0]},()=>Array(C[1]).fill(-1));for(let Pe=1;Pe0||le>0;)switch(ce.push(q-1),fe.push(le-1),J[q][le]){case 0:--q,--le;break;case 1:--q;break;case 2:--le;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${q}, ${le}]. Please file a bug report.`)}return ce.reverse(),fe.reverse(),[ce,fe]}},"./src/utils/tensor.js":(Ce,A,r)=>{r.r(A),r.d(A,{Tensor:()=>U,cat:()=>w,full:()=>ce,full_like:()=>fe,interpolate:()=>b,interpolate_4d:()=>T,layer_norm:()=>G,matmul:()=>v,mean:()=>J,mean_pooling:()=>R,ones:()=>Pe,ones_like:()=>be,permute:()=>P,quantize_embeddings:()=>lt,rand:()=>Ne,rfft:()=>z,slice:()=>ae,stack:()=>C,std_mean:()=>x,topk:()=>K,zeros:()=>De,zeros_like:()=>Ge});var g=r("./src/utils/maths.js"),O=r("./src/backends/onnx.js"),j=r("./src/ops/registry.js");const te=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class U{get dims(){return this.ort_tensor.dims}set dims(Z){this.ort_tensor.dims=Z}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...Z){return(0,O.isONNXTensor)(Z[0])?this.ort_tensor=Z[0]:this.ort_tensor=new O.Tensor(Z[0],Z[1],Z[2]),new Proxy(this,{get:(he,ve)=>{if(typeof ve=="string"){let Le=Number(ve);if(Number.isInteger(Le))return he._getitem(Le)}return he[ve]},set:(he,ve,Le)=>he[ve]=Le})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[Z,...he]=this.dims;if(he.length>0){const ve=he.reduce((Le,Ze)=>Le*Ze);for(let Le=0;Le0){const Le=ve.reduce((Ze,Ke)=>Ze*Ke);return this._subarray(Z,Le,ve)}else return new U(this.type,[this.data[Z]],ve)}indexOf(Z){const he=this.data;for(let ve=0;veje)throw new Error(`Invalid slice: ${oe}`);const Re=[Math.max(Me,0),Math.min(je,this.dims[Ae])];ve.push(Re),he.push(Re[1]-Re[0])}else throw new Error(`Invalid slice: ${oe}`)}const Le=ve.map(([Ae,oe])=>oe-Ae),Ze=Le.reduce((Ae,oe)=>Ae*oe),Ke=this.data,ne=new Ke.constructor(Ze),qe=this.stride();for(let Ae=0;Ae=0;--Me){const Re=Le[Me];oe+=(je%Re+ve[Me][0])*qe[Me],je=Math.floor(je/Re)}ne[Ae]=Ke[oe]}return new U(this.type,ne,he)}permute(...Z){return P(this,Z)}transpose(...Z){return this.permute(...Z)}sum(Z=null,he=!1){return this.norm(1,Z,he)}norm(Z="fro",he=null,ve=!1){if(Z==="fro")Z=2;else if(typeof Z=="string")throw Error(`Unsupported norm: ${Z}`);const Le=this.data;if(he===null){let ne=Le.reduce((qe,Ae)=>qe+Ae**Z,0)**(1/Z);return new U(this.type,[ne],[])}he=$(he,this.dims.length);const Ze=this.dims.slice();Ze[he]=1;const Ke=new Le.constructor(Le.length/this.dims[he]);for(let ne=0;ne=0;--Ae){const je=this.dims[Ae];if(Ae!==he){const Re=oe%je;qe+=Re*Me,Me*=Ze[Ae]}oe=Math.floor(oe/je)}Ke[qe]+=Le[ne]**Z}if(Z!==1)for(let ne=0;ne=0;--qe){const Me=this.dims[qe];if(qe!==he){const je=Ae%Me;ne+=je*oe,oe*=this.dims[qe]}Ae=Math.floor(Ae/Me)}Le[Ke]/=Ze[ne]}return this}normalize(Z=2,he=1){return this.clone().normalize_(Z,he)}stride(){return q(this.dims)}squeeze(Z=null){return new U(this.type,this.data,H(this.dims,Z))}squeeze_(Z=null){return this.dims=H(this.dims,Z),this}unsqueeze(Z=null){return new U(this.type,this.data,D(this.dims,Z))}unsqueeze_(Z=null){return this.dims=D(this.dims,Z),this}flatten_(Z=0,he=-1){he=(he+this.dims.length)%this.dims.length;let ve=this.dims.slice(0,Z),Le=this.dims.slice(Z,he+1),Ze=this.dims.slice(he+1);return this.dims=[...ve,Le.reduce((Ke,ne)=>Ke*ne,1),...Ze],this}flatten(Z=0,he=-1){return this.clone().flatten_(Z,he)}view(...Z){let he=-1;for(let Le=0;Lene!==he?Ze*Ke:Ze,1);Z[he]=ve.length/Le}return new U(this.type,ve,Z)}neg_(){const Z=this.data;for(let he=0;heZe*Ke);if(he!==ve)throw Error(`cannot reshape array of size ${he} into shape (${Z})`);let Le=ue;for(let Ze=Z.length-1;Ze>=0;Ze--)Le=Le.reduce((Ke,ne)=>{let qe=Ke[Ke.length-1];return qe.lengthnew U("int64",ue,[ue.length]);async function ae(ue,Z,he,ve,Le){return await(await j.TensorOpRegistry.slice)({x:ue,s:re(Z),e:re(he),a:re(ve),t:re(Le??new Array(ve.length).fill(1))})}function R(ue,Z){const he=ue.data,ve=Z.data,Le=[ue.dims[0],ue.dims[2]],Ze=new he.constructor(Le[0]*Le[1]),[Ke,ne,qe]=ue.dims;let Ae=0;for(let oe=0;oehe!==1):typeof Z=="number"?ue[Z]===1&&ue.splice(Z,1):Array.isArray(Z)&&(ue=ue.filter((he,ve)=>he!==1||!Z.includes(ve))),ue}function D(ue,Z){return Z=$(Z,ue.length+1),ue=ue.slice(),ue.splice(Z,0,1),ue}function $(ue,Z,he=null,ve=!0){if(ve&&(ue<-Z||ue>=Z))throw new Error(`IndexError: index ${ue} is out of bounds for dimension${he===null?"":" "+he} with size ${Z}`);return ue<0&&(ue=(ue%Z+Z)%Z),ue}function w(ue,Z=0){Z=$(Z,ue[0].dims.length);const he=ue[0].dims.slice();he[Z]=ue.reduce((Ke,ne)=>Ke+ne.dims[Z],0);const ve=he.reduce((Ke,ne)=>Ke*ne,1),Le=new ue[0].data.constructor(ve),Ze=ue[0].type;if(Z===0){let Ke=0;for(const ne of ue){const qe=ne.data;Le.set(qe,Ke),Ke+=qe.length}}else{let Ke=0;for(let ne=0;ne=0;--je){const ze=Ae[je];let Ye=Re%ze;je===Z&&(Ye+=Ke),Me+=Ye*We,We*=he[je],Re=Math.floor(Re/ze)}Le[Me]=qe[oe]}Ke+=Ae[Z]}}return new U(Ze,Le,he)}function C(ue,Z=0){return w(ue.map(he=>he.unsqueeze(Z)),Z)}function x(ue,Z=null,he=1,ve=!1){const Le=ue.data,Ze=ue.dims;if(Z===null){const je=Le.reduce((Ye,nt)=>Ye+nt,0)/Le.length,Re=Math.sqrt(Le.reduce((Ye,nt)=>Ye+(nt-je)**2,0)/(Le.length-he)),We=new U(ue.type,[je],[]);return[new U(ue.type,[Re],[]),We]}Z=$(Z,Ze.length);const Ke=J(ue,Z,ve),ne=Ke.data,qe=Ze.slice();qe[Z]=1;const Ae=new Le.constructor(Le.length/Ze[Z]);for(let Me=0;Me=0;--Re){const Ye=Ze[Re];if(Re!==Z){const nt=We%Ye;je+=nt*ze,ze*=qe[Re]}We=Math.floor(We/Ye)}Ae[je]+=(Le[Me]-ne[je])**2}for(let Me=0;Meqe+Ae,0);return new U(ue.type,[ne/ve.length],[])}const Le=ue.dims;Z=$(Z,Le.length);const Ze=Le.slice();Ze[Z]=1;const Ke=new ve.constructor(ve.length/Le[Z]);for(let ne=0;ne=0;--Ae){const je=Le[Ae];if(Ae!==Z){const Re=oe%je;qe+=Re*Me,Me*=Ze[Ae]}oe=Math.floor(oe/je)}Ke[qe]+=ve[ne]}if(Le[Z]!==1)for(let ne=0;ne=0;--he)Z[he]=ve,ve*=ue[he];return Z}function le(ue,Z,he,ve){const Le=ue.reduce((Ze,Ke)=>Ze*Ke,1);return new U(he,new ve(Le).fill(Z),ue)}function ce(ue,Z){let he,ve;if(typeof Z=="number")he="float32",ve=Float32Array;else if(typeof Z=="bigint")he="int64",ve=BigInt64Array;else if(typeof Z=="boolean")he="bool",ve=Uint8Array;else throw new Error(`Unsupported data type: ${typeof Z}`);return le(ue,Z,he,ve)}function fe(ue,Z){return ce(ue.dims,Z)}function Pe(ue){return le(ue,1n,"int64",BigInt64Array)}function be(ue){return Pe(ue.dims)}function De(ue){return le(ue,0n,"int64",BigInt64Array)}function Ge(ue){return De(ue.dims)}function Ne(ue){const Z=ue.reduce((he,ve)=>he*ve,1);return new U("float32",Float32Array.from({length:Z},()=>Math.random()),ue)}function lt(ue,Z){if(ue.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ue.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(Z))throw new Error("The precision must be either 'binary' or 'ubinary'");const he=Z==="binary",ve=he?"int8":"uint8",Le=he?Int8Array:Uint8Array,Ze=ue.data,Ke=new Le(Ze.length/8);for(let ne=0;ne0?1:0,Ae=Math.floor(ne/8),oe=ne%8;Ke[Ae]|=qe<<7-oe,he&&oe===0&&(Ke[Ae]-=128)}return new U(ve,Ke,[ue.dims[0],ue.dims[1]/8])}}},Zm={};function ds(Ce){var A=Zm[Ce];if(A!==void 0)return A.exports;var r=Zm[Ce]={exports:{}};return s_[Ce](r,r.exports,ds),r.exports}ds.m=s_;(()=>{var Ce=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;ds.t=function(r,g){if(g&1&&(r=this(r)),g&8||typeof r=="object"&&r&&(g&4&&r.__esModule||g&16&&typeof r.then=="function"))return r;var O=Object.create(null);ds.r(O);var j={};A=A||[null,Ce({}),Ce([]),Ce(Ce)];for(var te=g&2&&r;typeof te=="object"&&!~A.indexOf(te);te=Ce(te))Object.getOwnPropertyNames(te).forEach(U=>j[U]=()=>r[U]);return j.default=()=>r,ds.d(O,j),O}})();ds.d=(Ce,A)=>{for(var r in A)ds.o(A,r)&&!ds.o(Ce,r)&&Object.defineProperty(Ce,r,{enumerable:!0,get:A[r]})};ds.o=(Ce,A)=>Object.prototype.hasOwnProperty.call(Ce,A);ds.r=Ce=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Ce,"__esModule",{value:!0})};(()=>{var Ce;if(typeof import.meta.url=="string"&&(Ce=import.meta.url),!Ce)throw new Error("Automatic publicPath is not supported in this browser");Ce=Ce.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),ds.p=Ce})();ds.b=new URL("./",import.meta.url);var d={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/ds.r(d),ds.d(d,{ASTFeatureExtractor:()=>b.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>g.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>O.AutoConfig,AutoFeatureExtractor:()=>T.AutoFeatureExtractor,AutoImageProcessor:()=>K.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>R.AutoProcessor,AutoTokenizer:()=>g.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>g.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>G.BaseStreamer,BeitFeatureExtractor:()=>z.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>g.BertTokenizer,BitImageProcessor:()=>z.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>g.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>g.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>g.BloomTokenizer,CLIPFeatureExtractor:()=>z.CLIPFeatureExtractor,CLIPImageProcessor:()=>z.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>g.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>g.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>z.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>b.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>D.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>g.CodeGenTokenizer,CodeLlamaTokenizer:()=>g.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>g.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>g.ConvBertTokenizer,ConvNextFeatureExtractor:()=>z.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>z.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>z.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>z.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>g.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>g.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>z.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>z.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>z.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>z.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>g.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>z.DonutFeatureExtractor,DonutImageProcessor:()=>z.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>z.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>g.ElectraTokenizer,EosTokenCriteria:()=>H.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>g.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>y.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>g.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>P.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ae.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>D.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>D.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>z.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>g.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>g.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>g.GemmaTokenizer,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>g.Grok1Tokenizer,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HerbertTokenizer:()=>g.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>z.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ae.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>b.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>v.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>H.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>z.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ae.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>g.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>D.LogitsProcessor,LogitsProcessorList:()=>D.LogitsProcessorList,LogitsWarper:()=>D.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>g.M2M100Tokenizer,MBart50Tokenizer:()=>g.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>g.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>g.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>g.MarianTokenizer,Mask2FormerImageProcessor:()=>z.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>z.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>z.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>H.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ae.MgpstrProcessor,MgpstrTokenizer:()=>g.MgpstrTokenizer,MinLengthLogitsProcessor:()=>D.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>D.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>g.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>z.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>z.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>z.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>z.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>z.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>z.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>z.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>z.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>z.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>z.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>b.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>ae.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>g.NllbTokenizer,NoBadWordsLogitsProcessor:()=>D.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>D.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>z.NougatImageProcessor,NougatTokenizer:()=>g.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>z.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>z.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ae.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>z.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ae.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>z.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ae.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>g.PreTrainedTokenizer,PretrainedConfig:()=>O.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>re.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>z.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>b.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ae.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>g.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>z.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ae.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>z.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>te.RawImage,RepetitionPenaltyLogitsProcessor:()=>D.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>g.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>g.RobertaTokenizer,SamImageProcessor:()=>z.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ae.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>b.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>z.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>z.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>z.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>g.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>b.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ae.SpeechT5Processor,SpeechT5Tokenizer:()=>g.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>g.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>H.StoppingCriteria,StoppingCriteriaList:()=>H.StoppingCriteriaList,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>D.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>z.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>g.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>D.TemperatureLogitsWarper,Tensor:()=>U.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>G.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>g.TokenizerModel,TopKLogitsWarper:()=>D.TopKLogitsWarper,TopPLogitsWarper:()=>D.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ae.VLChatProcessor,VLMImageProcessor:()=>z.VLMImageProcessor,ViTFeatureExtractor:()=>z.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>z.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>z.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>z.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>g.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>g.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>b.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>ae.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>b.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>b.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>ae.WhisperProcessor,WhisperTextStreamer:()=>G.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>D.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>g.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>g.XLMRobertaTokenizer,XLMTokenizer:()=>g.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>z.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>z.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>y.bankers_round,cat:()=>U.cat,cos_sim:()=>y.cos_sim,dot:()=>y.dot,dynamic_time_warping:()=>y.dynamic_time_warping,env:()=>Ce.env,full:()=>U.full,full_like:()=>U.full_like,getKeyValueShapes:()=>O.getKeyValueShapes,hamming:()=>j.hamming,hanning:()=>j.hanning,interpolate:()=>U.interpolate,interpolate_4d:()=>U.interpolate_4d,interpolate_data:()=>y.interpolate_data,is_chinese_char:()=>g.is_chinese_char,layer_norm:()=>U.layer_norm,load_image:()=>te.load_image,log_softmax:()=>y.log_softmax,magnitude:()=>y.magnitude,matmul:()=>U.matmul,max:()=>y.max,mean:()=>U.mean,mean_pooling:()=>U.mean_pooling,medianFilter:()=>y.medianFilter,mel_filter_bank:()=>j.mel_filter_bank,min:()=>y.min,ones:()=>U.ones,ones_like:()=>U.ones_like,permute:()=>U.permute,permute_data:()=>y.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>U.quantize_embeddings,rand:()=>U.rand,read_audio:()=>j.read_audio,rfft:()=>U.rfft,round:()=>y.round,slice:()=>U.slice,softmax:()=>y.softmax,spectrogram:()=>j.spectrogram,stack:()=>U.stack,std_mean:()=>U.std_mean,topk:()=>U.topk,window_function:()=>j.window_function,zeros:()=>U.zeros,zeros_like:()=>U.zeros_like});var Ce=ds("./src/env.js"),A=ds("./src/pipelines.js"),r=ds("./src/models.js"),g=ds("./src/tokenizers.js"),O=ds("./src/configs.js"),j=ds("./src/utils/audio.js"),te=ds("./src/utils/image.js"),U=ds("./src/utils/tensor.js"),y=ds("./src/utils/maths.js"),P=ds("./src/base/feature_extraction_utils.js"),b=ds("./src/models/feature_extractors.js"),T=ds("./src/models/auto/feature_extraction_auto.js"),v=ds("./src/base/image_processors_utils.js"),z=ds("./src/models/image_processors.js"),K=ds("./src/models/auto/image_processing_auto.js"),re=ds("./src/base/processing_utils.js"),ae=ds("./src/models/processors.js"),R=ds("./src/models/auto/processing_auto.js"),G=ds("./src/generation/streamers.js"),H=ds("./src/generation/stopping_criteria.js"),D=ds("./src/generation/logits_process.js")})();d.ASTFeatureExtractor;d.ASTForAudioClassification;d.ASTModel;d.ASTPreTrainedModel;d.AlbertForMaskedLM;d.AlbertForQuestionAnswering;d.AlbertForSequenceClassification;d.AlbertModel;d.AlbertPreTrainedModel;d.AlbertTokenizer;d.AudioClassificationPipeline;d.AutoConfig;d.AutoFeatureExtractor;d.AutoImageProcessor;var If=d.AutoModel;d.AutoModelForAudioClassification;d.AutoModelForAudioFrameClassification;d.AutoModelForCTC;d.AutoModelForCausalLM;d.AutoModelForDepthEstimation;d.AutoModelForDocumentQuestionAnswering;d.AutoModelForImageClassification;d.AutoModelForImageFeatureExtraction;d.AutoModelForImageMatting;d.AutoModelForImageSegmentation;d.AutoModelForImageToImage;d.AutoModelForMaskGeneration;d.AutoModelForMaskedLM;d.AutoModelForNormalEstimation;d.AutoModelForObjectDetection;d.AutoModelForPoseEstimation;d.AutoModelForQuestionAnswering;d.AutoModelForSemanticSegmentation;d.AutoModelForSeq2SeqLM;d.AutoModelForSequenceClassification;d.AutoModelForSpeechSeq2Seq;d.AutoModelForTextToSpectrogram;d.AutoModelForTextToWaveform;d.AutoModelForTokenClassification;d.AutoModelForUniversalSegmentation;d.AutoModelForVision2Seq;d.AutoModelForXVector;d.AutoModelForZeroShotObjectDetection;d.AutoProcessor;d.AutoTokenizer;d.AutomaticSpeechRecognitionPipeline;d.BartForConditionalGeneration;d.BartForSequenceClassification;d.BartModel;d.BartPretrainedModel;d.BartTokenizer;d.BaseModelOutput;d.BaseStreamer;d.BeitFeatureExtractor;d.BeitForImageClassification;d.BeitModel;d.BeitPreTrainedModel;d.BertForMaskedLM;d.BertForQuestionAnswering;d.BertForSequenceClassification;d.BertForTokenClassification;d.BertModel;d.BertPreTrainedModel;d.BertTokenizer;d.BitImageProcessor;d.BlenderbotForConditionalGeneration;d.BlenderbotModel;d.BlenderbotPreTrainedModel;d.BlenderbotSmallForConditionalGeneration;d.BlenderbotSmallModel;d.BlenderbotSmallPreTrainedModel;d.BlenderbotSmallTokenizer;d.BlenderbotTokenizer;d.BloomForCausalLM;d.BloomModel;d.BloomPreTrainedModel;d.BloomTokenizer;d.CLIPFeatureExtractor;d.CLIPImageProcessor;d.CLIPModel;d.CLIPPreTrainedModel;d.CLIPSegForImageSegmentation;d.CLIPSegModel;d.CLIPSegPreTrainedModel;d.CLIPTextModel;d.CLIPTextModelWithProjection;d.CLIPTokenizer;d.CLIPVisionModel;d.CLIPVisionModelWithProjection;d.CamembertForMaskedLM;d.CamembertForQuestionAnswering;d.CamembertForSequenceClassification;d.CamembertForTokenClassification;d.CamembertModel;d.CamembertPreTrainedModel;d.CamembertTokenizer;d.CausalLMOutput;d.CausalLMOutputWithPast;d.ChineseCLIPFeatureExtractor;d.ChineseCLIPModel;d.ChineseCLIPPreTrainedModel;d.ClapAudioModelWithProjection;d.ClapFeatureExtractor;d.ClapModel;d.ClapPreTrainedModel;d.ClapTextModelWithProjection;d.ClassifierFreeGuidanceLogitsProcessor;d.CodeGenForCausalLM;d.CodeGenModel;d.CodeGenPreTrainedModel;d.CodeGenTokenizer;d.CodeLlamaTokenizer;d.CohereForCausalLM;d.CohereModel;d.CoherePreTrainedModel;d.CohereTokenizer;d.ConvBertForMaskedLM;d.ConvBertForQuestionAnswering;d.ConvBertForSequenceClassification;d.ConvBertForTokenClassification;d.ConvBertModel;d.ConvBertPreTrainedModel;d.ConvBertTokenizer;d.ConvNextFeatureExtractor;d.ConvNextForImageClassification;d.ConvNextImageProcessor;d.ConvNextModel;d.ConvNextPreTrainedModel;d.ConvNextV2ForImageClassification;d.ConvNextV2Model;d.ConvNextV2PreTrainedModel;d.DPTFeatureExtractor;d.DPTForDepthEstimation;d.DPTImageProcessor;d.DPTModel;d.DPTPreTrainedModel;d.DebertaForMaskedLM;d.DebertaForQuestionAnswering;d.DebertaForSequenceClassification;d.DebertaForTokenClassification;d.DebertaModel;d.DebertaPreTrainedModel;d.DebertaTokenizer;d.DebertaV2ForMaskedLM;d.DebertaV2ForQuestionAnswering;d.DebertaV2ForSequenceClassification;d.DebertaV2ForTokenClassification;d.DebertaV2Model;d.DebertaV2PreTrainedModel;d.DebertaV2Tokenizer;d.DecisionTransformerModel;d.DecisionTransformerPreTrainedModel;d.DeiTFeatureExtractor;d.DeiTForImageClassification;d.DeiTImageProcessor;d.DeiTModel;d.DeiTPreTrainedModel;d.DepthAnythingForDepthEstimation;d.DepthAnythingPreTrainedModel;d.DepthEstimationPipeline;d.DepthProForDepthEstimation;d.DepthProPreTrainedModel;d.DetrFeatureExtractor;d.DetrForObjectDetection;d.DetrForSegmentation;d.DetrImageProcessor;d.DetrModel;d.DetrObjectDetectionOutput;d.DetrPreTrainedModel;d.DetrSegmentationOutput;d.Dinov2ForImageClassification;d.Dinov2Model;d.Dinov2PreTrainedModel;d.DistilBertForMaskedLM;d.DistilBertForQuestionAnswering;d.DistilBertForSequenceClassification;d.DistilBertForTokenClassification;d.DistilBertModel;d.DistilBertPreTrainedModel;d.DistilBertTokenizer;d.DocumentQuestionAnsweringPipeline;d.DonutFeatureExtractor;d.DonutImageProcessor;d.DonutSwinModel;d.DonutSwinPreTrainedModel;d.EfficientNetForImageClassification;d.EfficientNetImageProcessor;d.EfficientNetModel;d.EfficientNetPreTrainedModel;d.ElectraForMaskedLM;d.ElectraForQuestionAnswering;d.ElectraForSequenceClassification;d.ElectraForTokenClassification;d.ElectraModel;d.ElectraPreTrainedModel;d.ElectraTokenizer;d.EosTokenCriteria;d.EsmForMaskedLM;d.EsmForSequenceClassification;d.EsmForTokenClassification;d.EsmModel;d.EsmPreTrainedModel;d.EsmTokenizer;d.ExaoneForCausalLM;d.ExaoneModel;d.ExaonePreTrainedModel;d.FFT;d.FalconForCausalLM;d.FalconModel;d.FalconPreTrainedModel;d.FalconTokenizer;d.FastViTForImageClassification;d.FastViTModel;d.FastViTPreTrainedModel;d.FeatureExtractionPipeline;d.FeatureExtractor;d.FillMaskPipeline;d.Florence2ForConditionalGeneration;d.Florence2PreTrainedModel;d.Florence2Processor;d.ForcedBOSTokenLogitsProcessor;d.ForcedEOSTokenLogitsProcessor;d.GLPNFeatureExtractor;d.GLPNForDepthEstimation;d.GLPNModel;d.GLPNPreTrainedModel;d.GPT2LMHeadModel;d.GPT2Model;d.GPT2PreTrainedModel;d.GPT2Tokenizer;d.GPTBigCodeForCausalLM;d.GPTBigCodeModel;d.GPTBigCodePreTrainedModel;d.GPTJForCausalLM;d.GPTJModel;d.GPTJPreTrainedModel;d.GPTNeoForCausalLM;d.GPTNeoModel;d.GPTNeoPreTrainedModel;d.GPTNeoXForCausalLM;d.GPTNeoXModel;d.GPTNeoXPreTrainedModel;d.GPTNeoXTokenizer;d.Gemma2ForCausalLM;d.Gemma2Model;d.Gemma2PreTrainedModel;d.GemmaForCausalLM;d.GemmaModel;d.GemmaPreTrainedModel;d.GemmaTokenizer;d.GraniteForCausalLM;d.GraniteModel;d.GranitePreTrainedModel;d.Grok1Tokenizer;d.GroupViTModel;d.GroupViTPreTrainedModel;d.HerbertTokenizer;d.HieraForImageClassification;d.HieraModel;d.HieraPreTrainedModel;d.HubertForCTC;d.HubertForSequenceClassification;d.HubertModel;d.HubertPreTrainedModel;d.IJepaForImageClassification;d.IJepaModel;d.IJepaPreTrainedModel;d.Idefics3ForConditionalGeneration;d.Idefics3ImageProcessor;d.Idefics3PreTrainedModel;d.Idefics3Processor;d.ImageClassificationPipeline;d.ImageFeatureExtractionPipeline;d.ImageFeatureExtractor;d.ImageMattingOutput;d.ImageProcessor;d.ImageSegmentationPipeline;d.ImageToImagePipeline;d.ImageToTextPipeline;d.InterruptableStoppingCriteria;d.JAISLMHeadModel;d.JAISModel;d.JAISPreTrainedModel;d.JinaCLIPImageProcessor;d.JinaCLIPModel;d.JinaCLIPPreTrainedModel;d.JinaCLIPProcessor;d.JinaCLIPTextModel;d.JinaCLIPVisionModel;d.LlamaForCausalLM;d.LlamaModel;d.LlamaPreTrainedModel;d.LlamaTokenizer;d.LlavaForConditionalGeneration;d.LlavaOnevisionForConditionalGeneration;d.LlavaOnevisionImageProcessor;d.LlavaPreTrainedModel;d.LogitsProcessor;d.LogitsProcessorList;d.LogitsWarper;d.LongT5ForConditionalGeneration;d.LongT5Model;d.LongT5PreTrainedModel;d.M2M100ForConditionalGeneration;d.M2M100Model;d.M2M100PreTrainedModel;d.M2M100Tokenizer;d.MBart50Tokenizer;d.MBartForCausalLM;d.MBartForConditionalGeneration;d.MBartForSequenceClassification;d.MBartModel;d.MBartPreTrainedModel;d.MBartTokenizer;d.MPNetForMaskedLM;d.MPNetForQuestionAnswering;d.MPNetForSequenceClassification;d.MPNetForTokenClassification;d.MPNetModel;d.MPNetPreTrainedModel;d.MPNetTokenizer;d.MT5ForConditionalGeneration;d.MT5Model;d.MT5PreTrainedModel;d.MarianMTModel;d.MarianModel;d.MarianPreTrainedModel;d.MarianTokenizer;d.Mask2FormerImageProcessor;d.MaskFormerFeatureExtractor;d.MaskFormerForInstanceSegmentation;d.MaskFormerImageProcessor;d.MaskFormerModel;d.MaskFormerPreTrainedModel;d.MaskedLMOutput;d.MaxLengthCriteria;d.MgpstrForSceneTextRecognition;d.MgpstrModelOutput;d.MgpstrPreTrainedModel;d.MgpstrProcessor;d.MgpstrTokenizer;d.MinLengthLogitsProcessor;d.MinNewTokensLengthLogitsProcessor;d.MistralForCausalLM;d.MistralModel;d.MistralPreTrainedModel;d.MobileBertForMaskedLM;d.MobileBertForQuestionAnswering;d.MobileBertForSequenceClassification;d.MobileBertModel;d.MobileBertPreTrainedModel;d.MobileBertTokenizer;d.MobileLLMForCausalLM;d.MobileLLMModel;d.MobileLLMPreTrainedModel;d.MobileNetV1FeatureExtractor;d.MobileNetV1ForImageClassification;d.MobileNetV1ImageProcessor;d.MobileNetV1Model;d.MobileNetV1PreTrainedModel;d.MobileNetV2FeatureExtractor;d.MobileNetV2ForImageClassification;d.MobileNetV2ImageProcessor;d.MobileNetV2Model;d.MobileNetV2PreTrainedModel;d.MobileNetV3FeatureExtractor;d.MobileNetV3ForImageClassification;d.MobileNetV3ImageProcessor;d.MobileNetV3Model;d.MobileNetV3PreTrainedModel;d.MobileNetV4FeatureExtractor;d.MobileNetV4ForImageClassification;d.MobileNetV4ImageProcessor;d.MobileNetV4Model;d.MobileNetV4PreTrainedModel;d.MobileViTFeatureExtractor;d.MobileViTForImageClassification;d.MobileViTImageProcessor;d.MobileViTModel;d.MobileViTPreTrainedModel;d.MobileViTV2ForImageClassification;d.MobileViTV2Model;d.MobileViTV2PreTrainedModel;d.ModelOutput;d.Moondream1ForConditionalGeneration;d.MoonshineFeatureExtractor;d.MoonshineForConditionalGeneration;d.MoonshineModel;d.MoonshinePreTrainedModel;d.MoonshineProcessor;d.MptForCausalLM;d.MptModel;d.MptPreTrainedModel;d.MultiModalityCausalLM;d.MultiModalityPreTrainedModel;d.MusicgenForCausalLM;d.MusicgenForConditionalGeneration;d.MusicgenModel;d.MusicgenPreTrainedModel;d.NllbTokenizer;d.NoBadWordsLogitsProcessor;d.NoRepeatNGramLogitsProcessor;d.NomicBertModel;d.NomicBertPreTrainedModel;d.NougatImageProcessor;d.NougatTokenizer;d.OPTForCausalLM;d.OPTModel;d.OPTPreTrainedModel;d.ObjectDetectionPipeline;d.Olmo2ForCausalLM;d.Olmo2Model;d.Olmo2PreTrainedModel;d.OlmoForCausalLM;d.OlmoModel;d.OlmoPreTrainedModel;d.OpenELMForCausalLM;d.OpenELMModel;d.OpenELMPreTrainedModel;d.OwlViTFeatureExtractor;d.OwlViTForObjectDetection;d.OwlViTImageProcessor;d.OwlViTModel;d.OwlViTPreTrainedModel;d.OwlViTProcessor;d.Owlv2ForObjectDetection;d.Owlv2ImageProcessor;d.Owlv2Model;d.Owlv2PreTrainedModel;d.PaliGemmaForConditionalGeneration;d.PaliGemmaPreTrainedModel;d.PaliGemmaProcessor;d.PatchTSMixerForPrediction;d.PatchTSMixerModel;d.PatchTSMixerPreTrainedModel;d.PatchTSTForPrediction;d.PatchTSTModel;d.PatchTSTPreTrainedModel;d.Phi3ForCausalLM;d.Phi3Model;d.Phi3PreTrainedModel;d.Phi3VForCausalLM;d.Phi3VImageProcessor;d.Phi3VPreTrainedModel;d.Phi3VProcessor;d.PhiForCausalLM;d.PhiModel;d.PhiPreTrainedModel;d.Pipeline;d.PreTrainedModel;d.PreTrainedTokenizer;d.PretrainedConfig;d.PretrainedMixin;d.Processor;d.PvtForImageClassification;d.PvtImageProcessor;d.PvtModel;d.PvtPreTrainedModel;d.PyAnnoteFeatureExtractor;d.PyAnnoteForAudioFrameClassification;d.PyAnnoteModel;d.PyAnnotePreTrainedModel;d.PyAnnoteProcessor;d.QuestionAnsweringModelOutput;d.QuestionAnsweringPipeline;d.Qwen2ForCausalLM;d.Qwen2Model;d.Qwen2PreTrainedModel;d.Qwen2Tokenizer;d.Qwen2VLForConditionalGeneration;d.Qwen2VLImageProcessor;d.Qwen2VLPreTrainedModel;d.Qwen2VLProcessor;d.RTDetrForObjectDetection;d.RTDetrImageProcessor;d.RTDetrModel;d.RTDetrObjectDetectionOutput;d.RTDetrPreTrainedModel;d.RawImage;d.RepetitionPenaltyLogitsProcessor;d.ResNetForImageClassification;d.ResNetModel;d.ResNetPreTrainedModel;d.RoFormerForMaskedLM;d.RoFormerForQuestionAnswering;d.RoFormerForSequenceClassification;d.RoFormerForTokenClassification;d.RoFormerModel;d.RoFormerPreTrainedModel;d.RoFormerTokenizer;d.RobertaForMaskedLM;d.RobertaForQuestionAnswering;d.RobertaForSequenceClassification;d.RobertaForTokenClassification;d.RobertaModel;d.RobertaPreTrainedModel;d.RobertaTokenizer;d.SamImageProcessor;d.SamImageSegmentationOutput;d.SamModel;d.SamPreTrainedModel;d.SamProcessor;d.SapiensForDepthEstimation;d.SapiensForNormalEstimation;d.SapiensForSemanticSegmentation;d.SapiensPreTrainedModel;d.SeamlessM4TFeatureExtractor;d.SegformerFeatureExtractor;d.SegformerForImageClassification;d.SegformerForSemanticSegmentation;d.SegformerImageProcessor;d.SegformerModel;d.SegformerPreTrainedModel;d.Seq2SeqLMOutput;d.SequenceClassifierOutput;d.SiglipImageProcessor;d.SiglipModel;d.SiglipPreTrainedModel;d.SiglipTextModel;d.SiglipTokenizer;d.SiglipVisionModel;d.SpeechT5FeatureExtractor;d.SpeechT5ForSpeechToText;d.SpeechT5ForTextToSpeech;d.SpeechT5HifiGan;d.SpeechT5Model;d.SpeechT5PreTrainedModel;d.SpeechT5Processor;d.SpeechT5Tokenizer;d.SqueezeBertForMaskedLM;d.SqueezeBertForQuestionAnswering;d.SqueezeBertForSequenceClassification;d.SqueezeBertModel;d.SqueezeBertPreTrainedModel;d.SqueezeBertTokenizer;d.StableLmForCausalLM;d.StableLmModel;d.StableLmPreTrainedModel;d.Starcoder2ForCausalLM;d.Starcoder2Model;d.Starcoder2PreTrainedModel;d.StoppingCriteria;d.StoppingCriteriaList;d.SummarizationPipeline;d.SuppressTokensAtBeginLogitsProcessor;d.Swin2SRForImageSuperResolution;d.Swin2SRImageProcessor;d.Swin2SRModel;d.Swin2SRPreTrainedModel;d.SwinForImageClassification;d.SwinModel;d.SwinPreTrainedModel;d.T5ForConditionalGeneration;d.T5Model;d.T5PreTrainedModel;d.T5Tokenizer;d.TableTransformerForObjectDetection;d.TableTransformerModel;d.TableTransformerObjectDetectionOutput;d.TableTransformerPreTrainedModel;d.TemperatureLogitsWarper;var fh=d.Tensor;d.Text2TextGenerationPipeline;d.TextClassificationPipeline;d.TextGenerationPipeline;d.TextStreamer;d.TextToAudioPipeline;d.TokenClassificationPipeline;d.TokenClassifierOutput;d.TokenizerModel;d.TopKLogitsWarper;d.TopPLogitsWarper;d.TrOCRForCausalLM;d.TrOCRPreTrainedModel;d.TranslationPipeline;d.UniSpeechForCTC;d.UniSpeechForSequenceClassification;d.UniSpeechModel;d.UniSpeechPreTrainedModel;d.UniSpeechSatForAudioFrameClassification;d.UniSpeechSatForCTC;d.UniSpeechSatForSequenceClassification;d.UniSpeechSatModel;d.UniSpeechSatPreTrainedModel;d.VLChatProcessor;d.VLMImageProcessor;d.ViTFeatureExtractor;d.ViTForImageClassification;d.ViTImageProcessor;d.ViTMAEModel;d.ViTMAEPreTrainedModel;d.ViTMSNForImageClassification;d.ViTMSNModel;d.ViTMSNPreTrainedModel;d.ViTModel;d.ViTPreTrainedModel;d.VisionEncoderDecoderModel;d.VitMatteForImageMatting;d.VitMatteImageProcessor;d.VitMattePreTrainedModel;d.VitPoseForPoseEstimation;d.VitPoseImageProcessor;d.VitPosePreTrainedModel;d.VitsModel;d.VitsModelOutput;d.VitsPreTrainedModel;d.VitsTokenizer;d.Wav2Vec2BertForCTC;d.Wav2Vec2BertForSequenceClassification;d.Wav2Vec2BertModel;d.Wav2Vec2BertPreTrainedModel;d.Wav2Vec2CTCTokenizer;d.Wav2Vec2FeatureExtractor;d.Wav2Vec2ForAudioFrameClassification;d.Wav2Vec2ForCTC;d.Wav2Vec2ForSequenceClassification;d.Wav2Vec2Model;d.Wav2Vec2PreTrainedModel;d.Wav2Vec2ProcessorWithLM;d.WavLMForAudioFrameClassification;d.WavLMForCTC;d.WavLMForSequenceClassification;d.WavLMForXVector;d.WavLMModel;d.WavLMPreTrainedModel;d.WeSpeakerFeatureExtractor;d.WeSpeakerResNetModel;d.WeSpeakerResNetPreTrainedModel;d.WhisperFeatureExtractor;d.WhisperForConditionalGeneration;d.WhisperModel;d.WhisperPreTrainedModel;d.WhisperProcessor;d.WhisperTextStreamer;d.WhisperTimeStampLogitsProcessor;d.WhisperTokenizer;d.XLMForQuestionAnswering;d.XLMForSequenceClassification;d.XLMForTokenClassification;d.XLMModel;d.XLMPreTrainedModel;d.XLMRobertaForMaskedLM;d.XLMRobertaForQuestionAnswering;d.XLMRobertaForSequenceClassification;d.XLMRobertaForTokenClassification;d.XLMRobertaModel;d.XLMRobertaPreTrainedModel;d.XLMRobertaTokenizer;d.XLMTokenizer;d.XLMWithLMHeadModel;d.XVectorOutput;d.YolosFeatureExtractor;d.YolosForObjectDetection;d.YolosImageProcessor;d.YolosModel;d.YolosObjectDetectionOutput;d.YolosPreTrainedModel;d.ZeroShotAudioClassificationPipeline;d.ZeroShotClassificationPipeline;d.ZeroShotImageClassificationPipeline;d.ZeroShotObjectDetectionPipeline;d.bankers_round;d.cat;d.cos_sim;d.dot;d.dynamic_time_warping;d.env;d.full;d.full_like;d.getKeyValueShapes;d.hamming;d.hanning;d.interpolate;d.interpolate_4d;d.interpolate_data;d.is_chinese_char;d.layer_norm;d.load_image;d.log_softmax;d.magnitude;d.matmul;d.max;d.mean;d.mean_pooling;d.medianFilter;d.mel_filter_bank;d.min;d.ones;d.ones_like;d.permute;d.permute_data;var Of=d.pipeline;d.quantize_embeddings;d.rand;d.read_audio;d.rfft;d.round;d.slice;d.softmax;d.spectrogram;d.stack;d.std_mean;d.topk;d.window_function;d.zeros;d.zeros_like;const Ca=16e3,gh=Ca/1e3,Ff=.3,Df=.1,Lf=400,zf=Lf*gh,Bf=80,mh=Bf*gh,Rf=250*gh,Nf=30,jf=512,Uf=Math.ceil(mh/jf);async function Vf(){try{return navigator.gpu?(await navigator.gpu.requestAdapter(),!0):!1}catch{return!1}}const _h=await Vf()?"webgpu":"wasm";self.postMessage({type:"info",message:`Using device: "${_h}"`});self.postMessage({type:"info",message:"Loading models...",duration:"until_next"});const Wf=await If.from_pretrained("onnx-community/silero-vad",{config:{model_type:"custom"},dtype:"fp32"}).catch(Ce=>{throw self.postMessage({error:Ce}),Ce}),Gf={webgpu:{encoder_model:"fp32",decoder_model_merged:"q4"},wasm:{encoder_model:"fp32",decoder_model_merged:"q8"}},o_=await Of("automatic-speech-recognition","onnx-community/moonshine-base-ONNX",{device:_h,dtype:Gf[_h]}).catch(Ce=>{throw self.postMessage({error:Ce}),Ce});await o_(new Float32Array(Ca));self.postMessage({type:"status",status:"ready",message:"Ready!"});let Pp=Promise.resolve();const Ea=new Float32Array(Nf*Ca);let vn=0;const Kf=new fh("int64",[Ca],[]);let e_=new fh("float32",new Float32Array(2*1*128),[2,1,128]),qd=!1;async function Hf(Ce){const A=new fh("float32",Ce,[1,Ce.length]),{stateN:r,output:g}=await(Pp=Pp.then(j=>Wf({input:A,sr:Kf,state:e_})));e_=r;const O=g.data[0];return O>Ff||qd&&O>=Df}const qf=async(Ce,A)=>{const{text:r}=await(Pp=Pp.then(g=>o_(Ce)));self.postMessage({type:"output",buffer:Ce,message:r,...A})};let Xd=0;const i_=(Ce=0)=>{self.postMessage({type:"status",status:"recording_end",message:"Transcribing...",duration:"until_next"}),Ea.fill(0,Ce),vn=Ce,qd=!1,Xd=0},t_=Ce=>{const r=Date.now()-(Xd+mh)/Ca*1e3,g=r-vn/Ca*1e3,O=r-g,j=Ce?.length??0,te=Ea.slice(0,vn+mh),U=Qd.reduce((b,T)=>b+T.length,0),y=new Float32Array(U+te.length);let P=0;for(const b of Qd)y.set(b,P),P+=b.length;y.set(te,P),qf(y,{start:g,end:r,duration:O}),Ce&&Ea.set(Ce,0),i_(j)};let Qd=[];self.onmessage=async Ce=>{const{buffer:A}=Ce.data,r=qd,g=await Hf(A);if(!r&&!g){Qd.length>=Uf&&Qd.shift(),Qd.push(A);return}const O=Ea.length-vn;if(A.length>=O){Ea.set(A.subarray(0,O),vn),vn+=O;const j=A.subarray(O);t_(j);return}else Ea.set(A,vn),vn+=A.length;if(g){qd||self.postMessage({type:"status",status:"recording_start",message:"Listening...",duration:"until_next"}),qd=!0,Xd=0;return}if(Xd+=A.length,!(Xd