diff --git "a/assets/index-BbCFr5ZN.js" "b/assets/index-BbCFr5ZN.js" new file mode 100644--- /dev/null +++ "b/assets/index-BbCFr5ZN.js" @@ -0,0 +1,2787 @@ +(function(){const A=document.createElement("link").relList;if(A&&A.supports&&A.supports("modulepreload"))return;for(const $ of document.querySelectorAll('link[rel="modulepreload"]'))g($);new MutationObserver($=>{for(const N of $)if(N.type==="childList")for(const Z of N.addedNodes)Z.tagName==="LINK"&&Z.rel==="modulepreload"&&g(Z)}).observe(document,{childList:!0,subtree:!0});function r($){const N={};return $.integrity&&(N.integrity=$.integrity),$.referrerPolicy&&(N.referrerPolicy=$.referrerPolicy),$.crossOrigin==="use-credentials"?N.credentials="include":$.crossOrigin==="anonymous"?N.credentials="omit":N.credentials="same-origin",N}function g($){if($.ep)return;$.ep=!0;const N=r($);fetch($.href,N)}})();var bh={},pf={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(ke,A,r)=>{ke.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(ke,A,r)=>{ke.exports=r.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(ke,A,r)=>{r.r(A),r.d(A,{Environment:()=>Ze,Interpreter:()=>at,Template:()=>ct,parse:()=>_e,tokenize:()=>x});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"}),$=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}),N=class{constructor(O,le){this.value=O,this.type=le}};function Z(O){return/\w/.test(O)}function j(O){return/[0-9]/.test(O)}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]],T=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function b(O,le={}){return O.endsWith(` +`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),le.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),le.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function x(O,le={}){const Q=[],we=b(O,le);let Se=0;const We=qe=>{let tt="";for(;qe(we[Se]);){if(we[Se]==="\\"){if(++Se,Se>=we.length)throw new SyntaxError("Unexpected end of input");const st=we[Se++],ft=T.get(st);if(ft===void 0)throw new SyntaxError(`Unexpected escaped character: ${st}`);tt+=ft;continue}if(tt+=we[Se++],Se>=we.length)throw new SyntaxError("Unexpected end of input")}return tt};e:for(;Se0){Q.push(new N(st,g.Text));continue}}We(st=>/\s/.test(st));const tt=we[Se];if(tt==="-"||tt==="+"){const st=Q.at(-1)?.type;if(st===g.Text||st===void 0)throw new SyntaxError(`Unexpected character: ${tt}`);switch(st){case g.Identifier:case g.NumericLiteral:case g.BooleanLiteral:case g.NullLiteral:case g.StringLiteral:case g.CloseParen:case g.CloseSquareBracket:break;default:{++Se;const ft=We(j);Q.push(new N(`${tt}${ft}`,ft.length>0?g.NumericLiteral:g.UnaryOperator));continue}}}for(const[st,ft]of y)if(we.slice(Se,Se+st.length)===st){Q.push(new N(st,ft)),Se+=st.length;continue e}if(tt==="'"||tt==='"'){++Se;const st=We(ft=>ft!==tt);Q.push(new N(st,g.StringLiteral)),++Se;continue}if(j(tt)){const st=We(j);Q.push(new N(st,g.NumericLiteral));continue}if(Z(tt)){const st=We(Z),ft=Object.hasOwn($,st)?$[st]:g.Identifier;ft===g.In&&Q.at(-1)?.type===g.Not?(Q.pop(),Q.push(new N("not in",g.NotIn))):Q.push(new N(st,ft));continue}throw new SyntaxError(`Unexpected character: ${tt}`)}return Q}var v=class{type="Statement"},L=class extends v{constructor(O){super(),this.body=O}type="Program"},K=class extends v{constructor(O,le,Q){super(),this.test=O,this.body=le,this.alternate=Q}type="If"},se=class extends v{constructor(O,le,Q,we){super(),this.loopvar=O,this.iterable=le,this.body=Q,this.defaultBlock=we}type="For"},oe=class extends v{constructor(O,le){super(),this.assignee=O,this.value=le}type="Set"},V=class extends v{constructor(O,le,Q){super(),this.name=O,this.args=le,this.body=Q}type="Macro"},U=class extends v{type="Expression"},H=class extends U{constructor(O,le,Q){super(),this.object=O,this.property=le,this.computed=Q}type="MemberExpression"},I=class extends U{constructor(O,le){super(),this.callee=O,this.args=le}type="CallExpression"},S=class extends U{constructor(O){super(),this.value=O}type="Identifier"},w=class extends U{constructor(O){super(),this.value=O}type="Literal"},P=class extends w{type="NumericLiteral"},F=class extends w{type="StringLiteral"},ae=class extends w{type="BooleanLiteral"},ie=class extends w{type="NullLiteral"},ye=class extends w{type="ArrayLiteral"},ge=class extends w{type="TupleLiteral"},re=class extends w{type="ObjectLiteral"},Me=class extends U{constructor(O,le,Q){super(),this.operator=O,this.left=le,this.right=Q}type="BinaryExpression"},pe=class extends U{constructor(O,le){super(),this.operand=O,this.filter=le}type="FilterExpression"},Ce=class extends U{constructor(O,le){super(),this.iterable=O,this.test=le}type="SelectExpression"},Ae=class extends U{constructor(O,le,Q){super(),this.operand=O,this.negate=le,this.test=Q}type="TestExpression"},Pe=class extends U{constructor(O,le){super(),this.operator=O,this.argument=le}type="UnaryExpression"},Je=class extends U{constructor(O=void 0,le=void 0,Q=void 0){super(),this.start=O,this.stop=le,this.step=Q}type="SliceExpression"},je=class extends U{constructor(O,le){super(),this.key=O,this.value=le}type="KeywordArgumentExpression"};function _e(O){const le=new L([]);let Q=0;function we(it,vt){const Ft=O[Q++];if(!Ft||Ft.type!==it)throw new Error(`Parser Error: ${vt}. ${Ft.type} !== ${it}.`);return Ft}function Se(){switch(O[Q].type){case g.Text:return tt();case g.OpenStatement:return st();case g.OpenExpression:return ft();default:throw new SyntaxError(`Unexpected token type: ${O[Q].type}`)}}function We(...it){return Q+it.length<=O.length&&it.some((vt,Ft)=>vt!==O[Q+Ft].type)}function qe(...it){return Q+it.length<=O.length&&it.every((vt,Ft)=>vt===O[Q+Ft].type)}function tt(){return new F(we(g.Text,"Expected text token").value)}function st(){we(g.OpenStatement,"Expected opening statement token");let it;switch(O[Q].type){case g.Set:++Q,it=Nt(),we(g.CloseStatement,"Expected closing statement token");break;case g.If:++Q,it=ss(),we(g.OpenStatement,"Expected {% token"),we(g.EndIf,"Expected endif token"),we(g.CloseStatement,"Expected %} token");break;case g.Macro:++Q,it=Ts(),we(g.OpenStatement,"Expected {% token"),we(g.EndMacro,"Expected endmacro token"),we(g.CloseStatement,"Expected %} token");break;case g.For:++Q,it=Ps(),we(g.OpenStatement,"Expected {% token"),we(g.EndFor,"Expected endfor token"),we(g.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[Q].type}`)}return it}function ft(){we(g.OpenExpression,"Expected opening expression token");const it=As();return we(g.CloseExpression,"Expected closing expression token"),it}function Nt(){const it=As();if(qe(g.Equals)){++Q;const vt=Nt();return new oe(it,vt)}return it}function ss(){const it=As();we(g.CloseStatement,"Expected closing statement token");const vt=[],Ft=[];for(;!(O[Q]?.type===g.OpenStatement&&(O[Q+1]?.type===g.ElseIf||O[Q+1]?.type===g.Else||O[Q+1]?.type===g.EndIf));)vt.push(Se());if(O[Q]?.type===g.OpenStatement&&O[Q+1]?.type!==g.EndIf)if(++Q,qe(g.ElseIf))we(g.ElseIf,"Expected elseif token"),Ft.push(ss());else for(we(g.Else,"Expected else token"),we(g.CloseStatement,"Expected closing statement token");!(O[Q]?.type===g.OpenStatement&&O[Q+1]?.type===g.EndIf);)Ft.push(Se());return new K(it,vt,Ft)}function Ts(){const it=or();if(it.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const vt=Er();we(g.CloseStatement,"Expected closing statement token");const Ft=[];for(;We(g.OpenStatement,g.EndMacro);)Ft.push(Se());return new V(it,vt,Ft)}function ms(it=!1){const vt=it?or:As,Ft=[vt()],Ys=qe(g.Comma);for(;Ys&&(++Q,Ft.push(vt()),!!qe(g.Comma)););return Ys?new ge(Ft):Ft[0]}function Ps(){const it=ms(!0);if(!(it instanceof S||it instanceof ge))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${it.type} instead`);we(g.In,"Expected `in` keyword following loop variable");const vt=As();we(g.CloseStatement,"Expected closing statement token");const Ft=[];for(;We(g.OpenStatement,g.EndFor)&&We(g.OpenStatement,g.Else);)Ft.push(Se());const Ys=[];if(qe(g.OpenStatement,g.Else))for(++Q,++Q,we(g.CloseStatement,"Expected closing statement token");We(g.OpenStatement,g.EndFor);)Ys.push(Se());return new se(it,vt,Ft,Ys)}function As(){return tr()}function tr(){const it=Tr();if(qe(g.If)){++Q;const vt=Tr();if(qe(g.Else)){++Q;const Ft=Tr();return new K(vt,[it],[Ft])}else return new Ce(it,vt)}return it}function Tr(){let it=Gr();for(;qe(g.Or);){const vt=O[Q];++Q;const Ft=Gr();it=new Me(vt,it,Ft)}return it}function Gr(){let it=Ns();for(;qe(g.And);){const vt=O[Q];++Q;const Ft=Ns();it=new Me(vt,it,Ft)}return it}function Ns(){let it;for(;qe(g.Not);){const vt=O[Q];++Q;const Ft=Ns();it=new Pe(vt,Ft)}return it??Mr()}function Mr(){let it=Lt();for(;qe(g.ComparisonBinaryOperator)||qe(g.In)||qe(g.NotIn);){const vt=O[Q];++Q;const Ft=Lt();it=new Me(vt,it,Ft)}return it}function Lt(){let it=Cr();for(;qe(g.AdditiveBinaryOperator);){const vt=O[Q];++Q;const Ft=Cr();it=new Me(vt,it,Ft)}return it}function Kr(){const it=qr();return qe(g.OpenParen)?Pr(it):it}function Pr(it){let vt=new I(it,Er());return qe(g.OpenParen)&&(vt=Pr(vt)),vt}function Er(){we(g.OpenParen,"Expected opening parenthesis for arguments list");const it=Hr();return we(g.CloseParen,"Expected closing parenthesis for arguments list"),it}function Hr(){const it=[];for(;!qe(g.CloseParen);){let vt=As();if(qe(g.Equals)){if(++Q,!(vt instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const Ft=As();vt=new je(vt,Ft)}it.push(vt),qe(g.Comma)&&++Q}return it}function dr(){const it=[];let vt=!1;for(;!qe(g.CloseSquareBracket);)qe(g.Colon)?(it.push(void 0),++Q,vt=!0):(it.push(As()),qe(g.Colon)&&(++Q,vt=!0));if(it.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(vt){if(it.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Je(...it)}return it[0]}function qr(){let it=or();for(;qe(g.Dot)||qe(g.OpenSquareBracket);){const vt=O[Q];++Q;let Ft;const Ys=vt.type!==g.Dot;if(Ys)Ft=dr(),we(g.CloseSquareBracket,"Expected closing square bracket");else if(Ft=or(),Ft.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");it=new H(it,Ft,Ys)}return it}function Cr(){let it=Dr();for(;qe(g.MultiplicativeBinaryOperator);){const vt=O[Q];++Q;const Ft=Dr();it=new Me(vt,it,Ft)}return it}function Dr(){let it=Lr();for(;qe(g.Is);){++Q;const vt=qe(g.Not);vt&&++Q;let Ft=or();if(Ft instanceof ae?Ft=new S(Ft.value.toString()):Ft instanceof ie&&(Ft=new S("none")),!(Ft instanceof S))throw new SyntaxError("Expected identifier for the test");it=new Ae(it,vt,Ft)}return it}function Lr(){let it=Kr();for(;qe(g.Pipe);){++Q;let vt=or();if(!(vt instanceof S))throw new SyntaxError("Expected identifier for the filter");qe(g.OpenParen)&&(vt=Pr(vt)),it=new pe(it,vt)}return it}function or(){const it=O[Q];switch(it.type){case g.NumericLiteral:return++Q,new P(Number(it.value));case g.StringLiteral:return++Q,new F(it.value);case g.BooleanLiteral:return++Q,new ae(it.value.toLowerCase()==="true");case g.NullLiteral:return++Q,new ie(null);case g.Identifier:return++Q,new S(it.value);case g.OpenParen:{++Q;const vt=ms();if(O[Q].type!==g.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[Q].type} instead`);return++Q,vt}case g.OpenSquareBracket:{++Q;const vt=[];for(;!qe(g.CloseSquareBracket);)vt.push(As()),qe(g.Comma)&&++Q;return++Q,new ye(vt)}case g.OpenCurlyBracket:{++Q;const vt=new Map;for(;!qe(g.CloseCurlyBracket);){const Ft=As();we(g.Colon,"Expected colon between key and value in object literal");const Ys=As();vt.set(Ft,Ys),qe(g.Comma)&&++Q}return++Q,new re(vt)}default:throw new SyntaxError(`Unexpected token: ${it.type}`)}}for(;Q=0?(le=(le??=0)<0?Math.max(O.length+le,0):Math.min(le,O.length),Q=(Q??=O.length)<0?Math.max(O.length+Q,0):Math.min(Q,O.length)):(le=(le??=O.length-1)<0?Math.max(O.length+le,-1):Math.min(le,O.length-1),Q=(Q??=-1)<-1?Math.max(O.length+Q,-1):Math.min(Q,O.length-1));const We=[];for(let qe=le;Se*qele.toUpperCase())}var Oe=class{type="RuntimeValue";value;builtins=new Map;constructor(O=void 0){this.value=O}__bool__(){return new Ve(!!this.value)}},Xe=class extends Oe{type="NumericValue"},ee=class extends Oe{type="StringValue";builtins=new Map([["upper",new Ne(()=>new ee(this.value.toUpperCase()))],["lower",new Ne(()=>new ee(this.value.toLowerCase()))],["strip",new Ne(()=>new ee(this.value.trim()))],["title",new Ne(()=>new ee(Ee(this.value)))],["length",new Xe(this.value.length)],["rstrip",new Ne(()=>new ee(this.value.trimEnd()))],["lstrip",new Ne(()=>new ee(this.value.trimStart()))]])},Ve=class extends Oe{type="BooleanValue"},Re=class extends Oe{type="ObjectValue";__bool__(){return new Ve(this.value.size>0)}builtins=new Map([["get",new Ne(([O,le])=>{if(!(O instanceof ee))throw new Error(`Object key must be a string: got ${O.type}`);return this.value.get(O.value)??le??new Ue})],["items",new Ne(()=>new ve(Array.from(this.value.entries()).map(([O,le])=>new ve([new ee(O),le]))))]])},te=class extends Re{type="KeywordArgumentsValue"},ve=class extends Oe{type="ArrayValue";builtins=new Map([["length",new Xe(this.value.length)]]);__bool__(){return new Ve(this.value.length>0)}},Ke=class extends ve{type="TupleValue"},Ne=class extends Oe{type="FunctionValue"},Ue=class extends Oe{type="NullValue"},ze=class extends Oe{type="UndefinedValue"},Ze=class{constructor(O){this.parent=O}variables=new Map([["namespace",new Ne(O=>{if(O.length===0)return new Re(new Map);if(O.length!==1||!(O[0]instanceof Re))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]);tests=new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof Ne],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const le=O.value;return O.type==="StringValue"&&le===le.toLowerCase()}],["upper",O=>{const le=O.value;return O.type==="StringValue"&&le===le.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,le)=>O.value===le.value],["eq",(O,le)=>O.value===le.value]]);set(O,le){return this.declareVariable(O,mt(le))}declareVariable(O,le){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,le),le}setVariable(O,le){return this.variables.set(O,le),le}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new ze}catch{return new ze}}},at=class{global;constructor(O){this.global=O??new Ze}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,le){const Q=this.evaluate(O.left,le);switch(O.operator.value){case"and":return Q.__bool__().value?this.evaluate(O.right,le):Q;case"or":return Q.__bool__().value?Q:this.evaluate(O.right,le)}const we=this.evaluate(O.right,le);switch(O.operator.value){case"==":return new Ve(Q.value==we.value);case"!=":return new Ve(Q.value!=we.value)}if(Q instanceof ze||we instanceof ze)throw new Error("Cannot perform operation on undefined values");if(Q instanceof Ue||we instanceof Ue)throw new Error("Cannot perform operation on null values");if(Q instanceof Xe&&we instanceof Xe)switch(O.operator.value){case"+":return new Xe(Q.value+we.value);case"-":return new Xe(Q.value-we.value);case"*":return new Xe(Q.value*we.value);case"/":return new Xe(Q.value/we.value);case"%":return new Xe(Q.value%we.value);case"<":return new Ve(Q.value":return new Ve(Q.value>we.value);case">=":return new Ve(Q.value>=we.value);case"<=":return new Ve(Q.value<=we.value)}else if(Q instanceof ve&&we instanceof ve)switch(O.operator.value){case"+":return new ve(Q.value.concat(we.value))}else if(we instanceof ve){const Se=we.value.find(We=>We.value===Q.value)!==void 0;switch(O.operator.value){case"in":return new Ve(Se);case"not in":return new Ve(!Se)}}if(Q instanceof ee||we instanceof ee)switch(O.operator.value){case"+":return new ee(Q.value.toString()+we.value.toString())}if(Q instanceof ee&&we instanceof ee)switch(O.operator.value){case"in":return new Ve(we.value.includes(Q.value));case"not in":return new Ve(!we.value.includes(Q.value))}if(Q instanceof ee&&we instanceof Re)switch(O.operator.value){case"in":return new Ve(we.value.has(Q.value));case"not in":return new Ve(!we.value.has(Q.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${Q.type} and ${we.type}`)}evaluateArguments(O,le){const Q=[],we=new Map;for(const Se of O)if(Se.type==="KeywordArgumentExpression"){const We=Se;we.set(We.key.value,this.evaluate(We.value,le))}else{if(we.size>0)throw new Error("Positional arguments must come before keyword arguments");Q.push(this.evaluate(Se,le))}return[Q,we]}evaluateFilterExpression(O,le){const Q=this.evaluate(O.operand,le);if(O.filter.type==="Identifier"){const we=O.filter;if(we.value==="tojson")return new ee(lt(Q));if(Q instanceof ve)switch(we.value){case"list":return Q;case"first":return Q.value[0];case"last":return Q.value[Q.value.length-1];case"length":return new Xe(Q.value.length);case"reverse":return new ve(Q.value.reverse());case"sort":return new ve(Q.value.sort((Se,We)=>{if(Se.type!==We.type)throw new Error(`Cannot compare different types: ${Se.type} and ${We.type}`);switch(Se.type){case"NumericValue":return Se.value-We.value;case"StringValue":return Se.value.localeCompare(We.value);default:throw new Error(`Cannot compare type: ${Se.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${we.value}`)}else if(Q instanceof ee)switch(we.value){case"length":return new Xe(Q.value.length);case"upper":return new ee(Q.value.toUpperCase());case"lower":return new ee(Q.value.toLowerCase());case"title":return new ee(Ee(Q.value));case"capitalize":return new ee(Q.value.charAt(0).toUpperCase()+Q.value.slice(1));case"trim":return new ee(Q.value.trim());case"indent":return new ee(Q.value.split(` +`).map((Se,We)=>We===0||Se.length===0?Se:" "+Se).join(` +`));case"string":return Q;default:throw new Error(`Unknown StringValue filter: ${we.value}`)}else if(Q instanceof Xe)switch(we.value){case"abs":return new Xe(Math.abs(Q.value));default:throw new Error(`Unknown NumericValue filter: ${we.value}`)}else if(Q instanceof Re)switch(we.value){case"items":return new ve(Array.from(Q.value.entries()).map(([Se,We])=>new ve([new ee(Se),We])));case"length":return new Xe(Q.value.size);default:throw new Error(`Unknown ObjectValue filter: ${we.value}`)}throw new Error(`Cannot apply filter "${we.value}" to type: ${Q.type}`)}else if(O.filter.type==="CallExpression"){const we=O.filter;if(we.callee.type!=="Identifier")throw new Error(`Unknown filter: ${we.callee.type}`);const Se=we.callee.value;if(Se==="tojson"){const[,We]=this.evaluateArguments(we.args,le),qe=We.get("indent")??new Ue;if(!(qe instanceof Xe||qe instanceof Ue))throw new Error("If set, indent must be a number");return new ee(lt(Q,qe.value))}if(Q instanceof ve){switch(Se){case"selectattr":case"rejectattr":{const We=Se==="selectattr";if(Q.value.some(ss=>!(ss instanceof Re)))throw new Error(`\`${Se}\` can only be applied to array of objects`);if(we.args.some(ss=>ss.type!=="StringLiteral"))throw new Error(`arguments of \`${Se}\` must be strings`);const[qe,tt,st]=we.args.map(ss=>this.evaluate(ss,le));let ft;if(tt){const ss=le.tests.get(tt.value);if(!ss)throw new Error(`Unknown test: ${tt.value}`);ft=ss}else ft=(...ss)=>ss[0].__bool__().value;const Nt=Q.value.filter(ss=>{const Ts=ss.value.get(qe.value),ms=Ts?ft(Ts,st):!1;return We?ms:!ms});return new ve(Nt)}case"map":{const[,We]=this.evaluateArguments(we.args,le);if(We.has("attribute")){const qe=We.get("attribute");if(!(qe instanceof ee))throw new Error("attribute must be a string");const tt=We.get("default"),st=Q.value.map(ft=>{if(!(ft instanceof Re))throw new Error("items in map must be an object");return ft.value.get(qe.value)??tt??new ze});return new ve(st)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Se}`)}else if(Q instanceof ee){switch(Se){case"indent":{const[We,qe]=this.evaluateArguments(we.args,le),tt=We.at(0)??qe.get("width")??new Xe(4);if(!(tt instanceof Xe))throw new Error("width must be a number");const st=We.at(1)??qe.get("first")??new Ve(!1),ft=We.at(2)??qe.get("blank")??new Ve(!1),Nt=Q.value.split(` +`),ss=" ".repeat(tt.value),Ts=Nt.map((ms,Ps)=>!st.value&&Ps===0||!ft.value&&ms.length===0?ms:ss+ms);return new ee(Ts.join(` +`))}}throw new Error(`Unknown StringValue filter: ${Se}`)}else throw new Error(`Cannot apply filter "${Se}" to type: ${Q.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,le){const Q=this.evaluate(O.operand,le),we=le.tests.get(O.test.value);if(!we)throw new Error(`Unknown test: ${O.test.value}`);const Se=we(Q);return new Ve(O.negate?!Se:Se)}evaluateUnaryExpression(O,le){const Q=this.evaluate(O.argument,le);switch(O.operator.value){case"not":return new Ve(!Q.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,le){return this.evaluateBlock(O.body,le)}evaluateBlock(O,le){let Q="";for(const we of O){const Se=this.evaluate(we,le);Se.type!=="NullValue"&&Se.type!=="UndefinedValue"&&(Q+=Se.value)}return new ee(Q)}evaluateIdentifier(O,le){return le.lookupVariable(O.value)}evaluateCallExpression(O,le){const[Q,we]=this.evaluateArguments(O.args,le);we.size>0&&Q.push(new te(we));const Se=this.evaluate(O.callee,le);if(Se.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Se.type}`);return Se.value(Q,le)}evaluateSliceExpression(O,le,Q){if(!(O instanceof ve||O instanceof ee))throw new Error("Slice object must be an array or string");const we=this.evaluate(le.start,Q),Se=this.evaluate(le.stop,Q),We=this.evaluate(le.step,Q);if(!(we instanceof Xe||we instanceof ze))throw new Error("Slice start must be numeric or undefined");if(!(Se instanceof Xe||Se instanceof ze))throw new Error("Slice stop must be numeric or undefined");if(!(We instanceof Xe||We instanceof ze))throw new Error("Slice step must be numeric or undefined");return O instanceof ve?new ve(de(O.value,we.value,Se.value,We.value)):new ee(de(Array.from(O.value),we.value,Se.value,We.value).join(""))}evaluateMemberExpression(O,le){const Q=this.evaluate(O.object,le);let we;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(Q,O.property,le);we=this.evaluate(O.property,le)}else we=new ee(O.property.value);let Se;if(Q instanceof Re){if(!(we instanceof ee))throw new Error(`Cannot access property with non-string: got ${we.type}`);Se=Q.value.get(we.value)??Q.builtins.get(we.value)}else if(Q instanceof ve||Q instanceof ee)if(we instanceof Xe)Se=Q.value.at(we.value),Q instanceof ee&&(Se=new ee(Q.value.at(we.value)));else if(we instanceof ee)Se=Q.builtins.get(we.value);else throw new Error(`Cannot access property with non-string/non-number: got ${we.type}`);else{if(!(we instanceof ee))throw new Error(`Cannot access property with non-string: got ${we.type}`);Se=Q.builtins.get(we.value)}return Se instanceof Oe?Se:new ze}evaluateSet(O,le){const Q=this.evaluate(O.value,le);if(O.assignee.type==="Identifier"){const we=O.assignee.value;le.setVariable(we,Q)}else if(O.assignee.type==="MemberExpression"){const we=O.assignee,Se=this.evaluate(we.object,le);if(!(Se instanceof Re))throw new Error("Cannot assign to member of non-object");if(we.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Se.value.set(we.property.value,Q)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new Ue}evaluateIf(O,le){const Q=this.evaluate(O.test,le);return this.evaluateBlock(Q.__bool__().value?O.body:O.alternate,le)}evaluateFor(O,le){const Q=new Ze(le);let we,Se;if(O.iterable.type==="SelectExpression"){const ft=O.iterable;Se=this.evaluate(ft.iterable,Q),we=ft.test}else Se=this.evaluate(O.iterable,Q);if(!(Se instanceof ve))throw new Error(`Expected iterable type in for loop: got ${Se.type}`);const We=[],qe=[];for(let ft=0;ftms.setVariable(O.loopvar.value,ss);else if(O.loopvar.type==="TupleLiteral"){const ms=O.loopvar;if(ss.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ss.type}`);const Ps=ss;if(ms.value.length!==Ps.value.length)throw new Error(`Too ${ms.value.length>Ps.value.length?"few":"many"} items to unpack`);Ts=As=>{for(let tr=0;tr0?We[ft-1]:new ze],["nextitem",ft{const Se=new Ze(we);Q=Q.slice();let We;Q.at(-1)?.type==="KeywordArgumentsValue"&&(We=Q.pop());for(let qe=0;qethis.evaluate(Q,le)));case"TupleLiteral":return new Ke(O.value.map(Q=>this.evaluate(Q,le)));case"ObjectLiteral":{const Q=new Map;for(const[we,Se]of O.value){const We=this.evaluate(we,le);if(!(We instanceof ee))throw new Error(`Object keys must be strings: got ${We.type}`);Q.set(We.value,this.evaluate(Se,le))}return new Re(Q)}case"Identifier":return this.evaluateIdentifier(O,le);case"CallExpression":return this.evaluateCallExpression(O,le);case"MemberExpression":return this.evaluateMemberExpression(O,le);case"UnaryExpression":return this.evaluateUnaryExpression(O,le);case"BinaryExpression":return this.evaluateBinaryExpression(O,le);case"FilterExpression":return this.evaluateFilterExpression(O,le);case"TestExpression":return this.evaluateTestExpression(O,le);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function mt(O){switch(typeof O){case"number":return new Xe(O);case"string":return new ee(O);case"boolean":return new Ve(O);case"undefined":return new ze;case"object":return O===null?new Ue:Array.isArray(O)?new ve(O.map(mt)):new Re(new Map(Object.entries(O).map(([le,Q])=>[le,mt(Q)])));case"function":return new Ne((le,Q)=>{const we=O(...le.map(Se=>Se.value))??null;return mt(we)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function lt(O,le,Q){const we=Q??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const Se=le?" ".repeat(le):"",We=` +`+Se.repeat(we),qe=We+Se;if(O.type==="ArrayValue"){const tt=O.value.map(st=>lt(st,le,we+1));return le?`[${qe}${tt.join(`,${qe}`)}${We}]`:`[${tt.join(", ")}]`}else{const tt=Array.from(O.value.entries()).map(([st,ft])=>{const Nt=`"${st}": ${lt(ft,le,we+1)}`;return le?`${qe}${Nt}`:Nt});return le?`{${tt.join(",")}${We}}`:`{${tt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var ct=class{parsed;constructor(O){const le=x(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=_e(le)}render(O){const le=new Ze;le.set("false",!1),le.set("true",!0),le.set("raise_exception",Se=>{throw new Error(Se)}),le.set("range",X);for(const[Se,We]of Object.entries(O))le.set(Se,We);return new at(le).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(ke,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>N,resolveBackendAndExecutionProviders:()=>j});const g=new Map,$=[],N=(y,T,b)=>{if(T&&typeof T.init=="function"&&typeof T.createInferenceSessionHandler=="function"){const x=g.get(y);if(x===void 0)g.set(y,{backend:T,priority:b});else{if(x.priority>b)return;if(x.priority===b&&x.backend!==T)throw new Error(`cannot register backend "${y}" using priority ${b}`)}if(b>=0){const v=$.indexOf(y);v!==-1&&$.splice(v,1);for(let L=0;L<$.length;L++)if(g.get($[L]).priority<=b){$.splice(L,0,y);return}$.push(y)}return}throw new TypeError("not a valid backend")},Z=async y=>{const T=g.get(y);if(!T)return"backend not found.";if(T.initialized)return T.backend;if(T.aborted)return T.error;{const b=!!T.initPromise;try{return b||(T.initPromise=T.backend.init(y)),await T.initPromise,T.initialized=!0,T.backend}catch(x){return b||(T.error=`${x}`,T.aborted=!0),T.error}finally{delete T.initPromise}}},j=async y=>{const T=y.executionProviders||[],b=T.map(oe=>typeof oe=="string"?oe:oe.name),x=b.length===0?$:b;let v;const L=[],K=new Set;for(const oe of x){const V=await Z(oe);typeof V=="string"?L.push({name:oe,err:V}):(v||(v=V),v===V&&K.add(oe))}if(!v)throw new Error(`no available backend found. ERR: ${L.map(oe=>`[${oe.name}] ${oe.err}`).join(", ")}`);for(const{name:oe,err:V}of L)b.includes(oe)&&console.warn(`removing requested execution provider "${oe}" from session options because it is not available: ${V}`);const se=T.filter(oe=>K.has(typeof oe=="string"?oe:oe.name));return[v,new Proxy(y,{get:(oe,V)=>V==="executionProviders"?se:Reflect.get(oe,V)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(ke,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":(ke,A,r)=>{r.r(A),r.d(A,{env:()=>N});var g=r("./node_modules/onnxruntime-common/dist/esm/version.js");let $="warning";const N={wasm:{},webgl:{},webgpu:{},versions:{common:g.version},set logLevel(Z){if(Z!==void 0){if(typeof Z!="string"||["verbose","info","warning","error","fatal"].indexOf(Z)===-1)throw new Error(`Unsupported logging level: ${Z}`);$=Z}},get logLevel(){return $}};Object.defineProperty(N,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(ke,A,r)=>{r.r(A),r.d(A,{env:()=>$});var g=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const $=g.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(ke,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>N.InferenceSession,TRACE:()=>j.TRACE,TRACE_FUNC_BEGIN:()=>j.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>j.TRACE_FUNC_END,Tensor:()=>Z.Tensor,TrainingSession:()=>y.TrainingSession,env:()=>$.env,registerBackend:()=>g.registerBackend});var g=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),$=r("./node_modules/onnxruntime-common/dist/esm/env.js"),N=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Z=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 j=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":(ke,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>Z});var g=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),$=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),N=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class Z{constructor(y){this.handler=y}async run(y,T,b){(0,N.TRACE_FUNC_BEGIN)();const x={};let v={};if(typeof y!="object"||y===null||y instanceof $.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let L=!0;if(typeof T=="object"){if(T===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(T instanceof $.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.");L=!1;for(const oe of T){if(typeof oe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(oe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${oe}.`);x[oe]=null}if(typeof b=="object"&&b!==null)v=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let oe=!1;const V=Object.getOwnPropertyNames(T);for(const U of this.outputNames)if(V.indexOf(U)!==-1){const H=T[U];(H===null||H instanceof $.Tensor)&&(oe=!0,L=!1,x[U]=H)}if(oe){if(typeof b=="object"&&b!==null)v=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else v=T}}else if(typeof T<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const oe of this.inputNames)if(typeof y[oe]>"u")throw new Error(`input '${oe}' is missing in 'feeds'.`);if(L)for(const oe of this.outputNames)x[oe]=null;const K=await this.handler.run(y,x,v),se={};for(const oe in K)if(Object.hasOwnProperty.call(K,oe)){const V=K[oe];V instanceof $.Tensor?se[oe]=V:se[oe]=new $.Tensor(V.type,V.data,V.dims)}return(0,N.TRACE_FUNC_END)(),se}async release(){return this.handler.dispose()}static async create(y,T,b,x){(0,N.TRACE_FUNC_BEGIN)();let v,L={};if(typeof y=="string"){if(v=y,typeof T=="object"&&T!==null)L=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(y instanceof Uint8Array){if(v=y,typeof T=="object"&&T!==null)L=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(y instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&y instanceof SharedArrayBuffer){const V=y;let U=0,H=y.byteLength;if(typeof T=="object"&&T!==null)L=T;else if(typeof T=="number"){if(U=T,!Number.isSafeInteger(U))throw new RangeError("'byteOffset' must be an integer.");if(U<0||U>=V.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${V.byteLength}).`);if(H=y.byteLength-U,typeof b=="number"){if(H=b,!Number.isSafeInteger(H))throw new RangeError("'byteLength' must be an integer.");if(H<=0||U+H>V.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${V.byteLength-U}].`);if(typeof x=="object"&&x!==null)L=x;else if(typeof x<"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 T<"u")throw new TypeError("'options' must be an object.");v=new Uint8Array(V,U,H)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[K,se]=await(0,g.resolveBackendAndExecutionProviders)(L),oe=await K.createInferenceSessionHandler(v,se);return(0,N.TRACE_FUNC_END)(),new Z(oe)}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":(ke,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>$});var g=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const $=g.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(ke,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(ke,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(ke,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>g,tensorToImageData:()=>$});const g=(N,Z)=>{const j=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);j.width=N.dims[3],j.height=N.dims[2];const y=j.getContext("2d");if(y!=null){let T,b;Z?.tensorLayout!==void 0&&Z.tensorLayout==="NHWC"?(T=N.dims[2],b=N.dims[3]):(T=N.dims[3],b=N.dims[2]);const x=Z?.format!==void 0?Z.format:"RGB",v=Z?.norm;let L,K;v===void 0||v.mean===void 0?L=[255,255,255,255]:typeof v.mean=="number"?L=[v.mean,v.mean,v.mean,v.mean]:(L=[v.mean[0],v.mean[1],v.mean[2],0],v.mean[3]!==void 0&&(L[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 se=b*T;let oe=0,V=se,U=se*2,H=-1;x==="RGBA"?(oe=0,V=se,U=se*2,H=se*3):x==="RGB"?(oe=0,V=se,U=se*2):x==="RBG"&&(oe=0,U=se,V=se*2);for(let I=0;I{const j=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let y;if(j!=null){let T,b,x;Z?.tensorLayout!==void 0&&Z.tensorLayout==="NHWC"?(T=N.dims[2],b=N.dims[1],x=N.dims[3]):(T=N.dims[3],b=N.dims[2],x=N.dims[1]);const v=Z!==void 0&&Z.format!==void 0?Z.format:"RGB",L=Z?.norm;let K,se;L===void 0||L.mean===void 0?K=[255,255,255,255]:typeof L.mean=="number"?K=[L.mean,L.mean,L.mean,L.mean]:(K=[L.mean[0],L.mean[1],L.mean[2],255],L.mean[3]!==void 0&&(K[3]=L.mean[3])),L===void 0||L.bias===void 0?se=[0,0,0,0]:typeof L.bias=="number"?se=[L.bias,L.bias,L.bias,L.bias]:(se=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(se[3]=L.bias[3]));const oe=b*T;if(Z!==void 0&&(Z.format!==void 0&&x===4&&Z.format!=="RGBA"||x===3&&Z.format!=="RGB"&&Z.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const V=4;let U=0,H=1,I=2,S=3,w=0,P=oe,F=oe*2,ae=-1;v==="RGBA"?(w=0,P=oe,F=oe*2,ae=oe*3):v==="RGB"?(w=0,P=oe,F=oe*2):v==="RBG"&&(w=0,F=oe,P=oe*2),y=j.createImageData(T,b);for(let ie=0;ie{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(ke,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>$,tensorFromGpuBuffer:()=>j,tensorFromImage:()=>N,tensorFromMLTensor:()=>y,tensorFromPinnedBuffer:()=>T,tensorFromTexture:()=>Z});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const $=(b,x)=>{if(b===void 0)throw new Error("Image buffer must be defined");if(x.height===void 0||x.width===void 0)throw new Error("Image height and width must be defined");if(x.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:v,width:L}=x,K=x.norm??{mean:255,bias:0};let se,oe;typeof K.mean=="number"?se=[K.mean,K.mean,K.mean,K.mean]:se=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?oe=[K.bias,K.bias,K.bias,K.bias]:oe=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];const V=x.format!==void 0?x.format:"RGBA",U=x.tensorFormat!==void 0&&x.tensorFormat!==void 0?x.tensorFormat:"RGB",H=v*L,I=U==="RGBA"?new Float32Array(H*4):new Float32Array(H*3);let S=4,w=0,P=1,F=2,ae=3,ie=0,ye=H,ge=H*2,re=-1;V==="RGB"&&(S=3,w=0,P=1,F=2,ae=-1),U==="RGBA"?re=H*3:U==="RBG"?(ie=0,ge=H,ye=H*2):U==="BGR"&&(ge=0,ye=H,ie=H*2);for(let pe=0;pe{const v=typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement,L=typeof ImageData<"u"&&b instanceof ImageData,K=typeof ImageBitmap<"u"&&b instanceof ImageBitmap,se=typeof b=="string";let oe,V=x??{};const U=()=>{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=I=>typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?I.getContext("2d"):null;if(v){const I=U();I.width=b.width,I.height=b.height;const S=H(I);if(S!=null){let w=b.height,P=b.width;if(x!==void 0&&x.resizedHeight!==void 0&&x.resizedWidth!==void 0&&(w=x.resizedHeight,P=x.resizedWidth),x!==void 0){if(V=x,x.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");V.tensorFormat="RGBA",V.height=w,V.width=P}else V.tensorFormat="RGBA",V.height=w,V.width=P;S.drawImage(b,0,0),oe=S.getImageData(0,0,P,w).data}else throw new Error("Can not access image data")}else if(L){let I,S;if(x!==void 0&&x.resizedWidth!==void 0&&x.resizedHeight!==void 0?(I=x.resizedHeight,S=x.resizedWidth):(I=b.height,S=b.width),x!==void 0&&(V=x),V.format="RGBA",V.height=I,V.width=S,x!==void 0){const w=U();w.width=S,w.height=I;const P=H(w);if(P!=null)P.putImageData(b,0,0),oe=P.getImageData(0,0,S,I).data;else throw new Error("Can not access image data")}else oe=b.data}else if(K){if(x===void 0)throw new Error("Please provide image config with format for Imagebitmap");const I=U();I.width=b.width,I.height=b.height;const S=H(I);if(S!=null){const w=b.height,P=b.width;return S.drawImage(b,0,0,P,w),oe=S.getImageData(0,0,P,w).data,V.height=w,V.width=P,$(oe,V)}else throw new Error("Can not access image data")}else{if(se)return new Promise((I,S)=>{const w=U(),P=H(w);if(!b||!P)return S();const F=new Image;F.crossOrigin="Anonymous",F.src=b,F.onload=()=>{w.width=F.width,w.height=F.height,P.drawImage(F,0,0,w.width,w.height);const ae=P.getImageData(0,0,w.width,w.height);V.height=w.height,V.width=w.width,I($(ae.data,V))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(oe!==void 0)return $(oe,V);throw new Error("Input data provided is not supported - aborted tensor creation")},Z=(b,x)=>{const{width:v,height:L,download:K,dispose:se}=x,oe=[1,L,v,4];return new g.Tensor({location:"texture",type:"float32",texture:b,dims:oe,download:K,dispose:se})},j=(b,x)=>{const{dataType:v,dims:L,download:K,dispose:se}=x;return new g.Tensor({location:"gpu-buffer",type:v??"float32",gpuBuffer:b,dims:L,download:K,dispose:se})},y=(b,x)=>{const{dataType:v,dims:L,download:K,dispose:se}=x;return new g.Tensor({location:"ml-tensor",type:v??"float32",mlTensor:b,dims:L,download:K,dispose:se})},T=(b,x,v)=>new g.Tensor({location:"cpu-pinned",type:b,data:x,dims:v??[x.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(ke,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(ke,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>$,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>g,checkTypedArray:()=>Z});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]]),$=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let N=!1;const Z=()=>{if(!N){N=!0;const j=typeof BigInt64Array<"u"&&BigInt64Array.from,y=typeof BigUint64Array<"u"&&BigUint64Array.from,T=typeof Float16Array<"u"&&Float16Array.from;j&&(g.set("int64",BigInt64Array),$.set(BigInt64Array,"int64")),y&&(g.set("uint64",BigUint64Array),$.set(BigUint64Array,"uint64")),T?(g.set("float16",Float16Array),$.set(Float16Array,"float16")):g.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(ke,A,r)=>{r.r(A),r.d(A,{Tensor:()=>j});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),$=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),N=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Z=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class j{constructor(T,b,x){(0,N.checkTypedArray)();let v,L;if(typeof T=="object"&&"location"in T)switch(this.dataLocation=T.location,v=T.type,L=T.dims,T.location){case"cpu-pinned":{const se=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(!se)throw new TypeError(`unsupported type "${v}" to create tensor from pinned buffer`);if(!(T.data instanceof se))throw new TypeError(`buffer should be of type ${se.name}`);this.cpuData=T.data;break}case"texture":{if(v!=="float32")throw new TypeError(`unsupported type "${v}" to create tensor from texture`);this.gpuTextureData=T.texture,this.downloader=T.download,this.disposer=T.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=T.gpuBuffer,this.downloader=T.download,this.disposer=T.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=T.mlTensor,this.downloader=T.download,this.disposer=T.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let se,oe;if(typeof T=="string")if(v=T,oe=x,T==="string"){if(!Array.isArray(b))throw new TypeError("A string tensor's data must be a string array.");se=b}else{const V=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(T);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${T}.`);if(Array.isArray(b)){if(T==="float16"&&V===Uint16Array||T==="uint4"||T==="int4")throw new TypeError(`Creating a ${T} tensor from number array is not supported. Please use ${V.name} as data.`);T==="uint64"||T==="int64"?se=V.from(b,BigInt):se=V.from(b)}else if(b instanceof V)se=b;else if(b instanceof Uint8ClampedArray)if(T==="uint8")se=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 ${V}`)}else if(oe=b,Array.isArray(T)){if(T.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const V=typeof T[0];if(V==="string")v="string",se=T;else if(V==="boolean")v="bool",se=Uint8Array.from(T);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(T instanceof Uint8ClampedArray)v="uint8",se=Uint8Array.from(T);else{const V=N.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(T.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${T.constructor}.`);v=V,se=T}if(oe===void 0)oe=[se.length];else if(!Array.isArray(oe))throw new TypeError("A tensor's dims must be a number array");L=oe,this.cpuData=se,this.dataLocation="cpu"}const K=(0,Z.calculateSize)(L);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=L,this.size=K}static async fromImage(T,b){return(0,$.tensorFromImage)(T,b)}static fromTexture(T,b){return(0,$.tensorFromTexture)(T,b)}static fromGpuBuffer(T,b){return(0,$.tensorFromGpuBuffer)(T,b)}static fromMLTensor(T,b){return(0,$.tensorFromMLTensor)(T,b)}static fromPinnedBuffer(T,b,x){return(0,$.tensorFromPinnedBuffer)(T,b,x)}toDataURL(T){return(0,g.tensorToDataURL)(this,T)}toImageData(T){return(0,g.tensorToImageData)(this,T)}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(T){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,T&&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(T){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Z.tensorReshape)(this,T)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(ke,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>$,tensorReshape:()=>N});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const $=Z=>{let j=1;for(let y=0;y{switch(Z.location){case"cpu":return new g.Tensor(Z.type,Z.data,j);case"cpu-pinned":return new g.Tensor({location:"cpu-pinned",data:Z.data,type:Z.type,dims:j});case"texture":return new g.Tensor({location:"texture",texture:Z.texture,type:Z.type,dims:j});case"gpu-buffer":return new g.Tensor({location:"gpu-buffer",gpuBuffer:Z.gpuBuffer,type:Z.type,dims:j});case"ml-tensor":return new g.Tensor({location:"ml-tensor",mlTensor:Z.mlTensor,type:Z.type,dims:j});default:throw new Error(`tensorReshape: tensor location ${Z.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(ke,A,r)=>{r.r(A),r.d(A,{Tensor:()=>$});var g=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const $=g.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(ke,A,r)=>{r.r(A),r.d(A,{TRACE:()=>$,TRACE_FUNC_BEGIN:()=>Z,TRACE_FUNC_END:()=>j});var g=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const $=(y,T)=>{(typeof g.env.trace>"u"?!g.env.wasm.trace:!g.env.trace)||console.timeStamp(`${y}::ORT::${T}`)},N=(y,T)=>{const b=new Error().stack?.split(/\r\n|\r|\n/g)||[];let x=!1;for(let v=0;v{(typeof g.env.trace>"u"?!g.env.wasm.trace:!g.env.trace)||N("BEGIN",y)},j=y=>{(typeof g.env.trace>"u"?!g.env.wasm.trace:!g.env.trace)||N("END",y)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(ke,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>Z});var g=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),$=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const N="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Z{constructor(y,T,b){this.handler=y,this.hasOptimizerModel=T,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,T){const b=y.evalModel||"",x=y.optimizerModel||"",v=T||{},[L,K]=await(0,g.resolveBackendAndExecutionProviders)(v);if(L.createTrainingSessionHandler){const se=await L.createTrainingSessionHandler(y.checkpointState,y.trainModel,b,x,K);return new Z(se,!!y.optimizerModel,!!y.evalModel)}else throw new Error(N)}typeNarrowingForRunStep(y,T,b,x,v){const L={};let K={};if(typeof b!="object"||b===null||b instanceof $.Tensor||Array.isArray(b))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let se=!0;if(typeof x=="object"){if(x===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(x instanceof $.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(x)){if(x.length===0)throw new TypeError("'fetches' cannot be an empty array.");se=!1;for(const oe of x){if(typeof oe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(T.indexOf(oe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${oe}.`);L[oe]=null}if(typeof v=="object"&&v!==null)K=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else{let oe=!1;const V=Object.getOwnPropertyNames(x);for(const U of T)if(V.indexOf(U)!==-1){const H=x[U];(H===null||H instanceof $.Tensor)&&(oe=!0,se=!1,L[U]=H)}if(oe){if(typeof v=="object"&&v!==null)K=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else K=x}}else if(typeof x<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const oe of y)if(typeof b[oe]>"u")throw new Error(`input '${oe}' is missing in 'feeds'.`);if(se)for(const oe of T)L[oe]=null;return[L,K]}convertHandlerReturnTypeToMapOfTensors(y){const T={};for(const b in y)if(Object.hasOwnProperty.call(y,b)){const x=y[b];x instanceof $.Tensor?T[b]=x:T[b]=new $.Tensor(x.type,x.data,x.dims)}return T}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(y,T,b){const[x,v]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,y,T,b),L=await this.handler.runTrainStep(y,x,v);return this.convertHandlerReturnTypeToMapOfTensors(L)}async runOptimizerStep(y){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(y||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(y,T,b){if(this.hasEvalModel){const[x,v]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,y,T,b),L=await this.handler.runEvalStep(y,x,v);return this.convertHandlerReturnTypeToMapOfTensors(L)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(y=!0){return this.handler.getParametersSize(y)}async loadParametersBuffer(y,T=!0){const b=await this.getParametersSize(T);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,T)}async getContiguousParameters(y=!0){return this.handler.getContiguousParameters(y)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(ke,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>$});var g=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const $=g.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(ke,A,r)=>{r.r(A),r.d(A,{version:()=>g});const g="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(ke,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>lt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>ze,Tensor:()=>te,default:()=>xf,env:()=>F,registerBackend:()=>K});/*! + * ONNX Runtime Web v1.21.0-dev.20250114-228dd16893 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var g=Object.defineProperty,$=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyNames,Z=Object.prototype.hasOwnProperty,j=(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),T=(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 i of N(t))!Z.call(e,i)&&i!==s&&g(e,i,{get:()=>t[i],enumerable:!(n=$(t,i))||n.enumerable});return e},x=e=>b(g({},"__esModule",{value:!0}),e),v,L,K,se,oe,V=y(()=>{v=new Map,L=[],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 i=L.indexOf(e);i!==-1&&L.splice(i,1);for(let o=0;o{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}}},oe=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?L:s,i,o=[],a=new Set;for(let p of n){let h=await se(p);typeof h=="string"?o.push({name:p,err:h}):(i||(i=h),i===h&&a.add(p))}if(!i)throw new Error(`no available backend found. ERR: ${o.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of o)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[i,new Proxy(e,{get:(p,h)=>h==="executionProviders"?c:Reflect.get(p,h)})]}}),U=y(()=>{V()}),H,I=y(()=>{H="1.21.0-dev.20241212-1f88284f96"}),S,w,P=y(()=>{I(),S="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}`);S=e}},get logLevel(){return S}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),F,ae=y(()=>{P(),F=w}),ie,ye,ge=y(()=>{ie=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let i,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],o=e.dims[3]):(i=e.dims[3],o=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 C=o*i,u=0,k=C,B=C*2,R=-1;a==="RGBA"?(u=0,k=C,B=C*2,R=C*3):a==="RGB"?(u=0,k=C,B=C*2):a==="RBG"&&(u=0,B=C,k=C*2);for(let z=0;z{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let i,o,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],o=e.dims[1],a=e.dims[3]):(i=e.dims[3],o=e.dims[2],a=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t?.norm,h,C;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?C=[0,0,0,0]:typeof p.bias=="number"?C=[p.bias,p.bias,p.bias,p.bias]:(C=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(C[3]=p.bias[3]));let u=o*i;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 k=4,B=0,R=1,z=2,ne=3,J=0,W=u,ue=u*2,he=-1;c==="RGBA"?(J=0,W=u,ue=u*2,he=u*3):c==="RGB"?(J=0,W=u,ue=u*2):c==="RBG"&&(J=0,ue=u,W=u*2),n=s.createImageData(i,o);for(let be=0;be{Re(),re=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,i=t.norm??{mean:255,bias:0},o,a;typeof i.mean=="number"?o=[i.mean,i.mean,i.mean,i.mean]:o=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?a=[i.bias,i.bias,i.bias,i.bias]:a=[i.bias[0],i.bias[1],i.bias[2],i.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,C=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),u=4,k=0,B=1,R=2,z=3,ne=0,J=h,W=h*2,ue=-1;c==="RGB"&&(u=3,k=0,B=1,R=2,z=-1),p==="RGBA"?ue=h*3:p==="RBG"?(ne=0,W=h,J=h*2):p==="BGR"&&(W=0,J=h,ne=h*2);for(let he=0;he{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=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=C=>typeof HTMLCanvasElement<"u"&&C instanceof HTMLCanvasElement||C instanceof OffscreenCanvas?C.getContext("2d"):null;if(s){let C=p();C.width=e.width,C.height=e.height;let u=h(C);if(u!=null){let k=e.height,B=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(k=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=k,c.width=B}else c.tensorFormat="RGBA",c.height=k,c.width=B;u.drawImage(e,0,0),a=u.getImageData(0,0,B,k).data}else throw new Error("Can not access image data")}else if(n){let C,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(C=t.resizedHeight,u=t.resizedWidth):(C=e.height,u=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=C,c.width=u,t!==void 0){let k=p();k.width=u,k.height=C;let B=h(k);if(B!=null)B.putImageData(e,0,0),a=B.getImageData(0,0,u,C).data;else throw new Error("Can not access image data")}else a=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let C=p();C.width=e.width,C.height=e.height;let u=h(C);if(u!=null){let k=e.height,B=e.width;return u.drawImage(e,0,0,B,k),a=u.getImageData(0,0,B,k).data,c.height=k,c.width=B,re(a,c)}else throw new Error("Can not access image data")}else{if(o)return new Promise((C,u)=>{let k=p(),B=h(k);if(!e||!B)return u();let R=new Image;R.crossOrigin="Anonymous",R.src=e,R.onload=()=>{k.width=R.width,k.height=R.height,B.drawImage(R,0,0,k.width,k.height);let z=B.getImageData(0,0,k.width,k.height);c.height=k.height,c.width=k.width,C(re(z.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return re(a,c);throw new Error("Input data provided is not supported - aborted tensor creation")},pe=(e,t)=>{let{width:s,height:n,download:i,dispose:o}=t,a=[1,n,s,4];return new Ve({location:"texture",type:"float32",texture:e,dims:a,download:i,dispose:o})},Ce=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:o}=t;return new Ve({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:i,dispose:o})},Ae=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:o}=t;return new Ve({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:i,dispose:o})},Pe=(e,t,s)=>new Ve({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),je,_e,X,de,Ee=y(()=>{je=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),_e=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),X=!1,de=()=>{if(!X){X=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(je.set("int64",BigInt64Array),_e.set(BigInt64Array,"int64")),t&&(je.set("uint64",BigUint64Array),_e.set(BigUint64Array,"uint64")),s?(je.set("float16",Float16Array),_e.set(Float16Array,"float16")):je.set("float16",Uint16Array)}}}),Oe,Xe,ee=y(()=>{Re(),Oe=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Ve(e.type,e.data,t);case"cpu-pinned":return new Ve({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ve({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ve({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ve({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ve,Re=y(()=>{ge(),Je(),Ee(),ee(),Ve=class{constructor(e,t,s){de();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let a=je.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=je.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=_e.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");i=c,this.cpuData=a,this.dataLocation="cpu"}let o=Oe(i);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=o}static async fromImage(e,t){return Me(e,t)}static fromTexture(e,t){return pe(e,t)}static fromGpuBuffer(e,t){return Ce(e,t)}static fromMLTensor(e,t){return Ae(e,t)}static fromPinnedBuffer(e,t,s){return Pe(e,t,s)}toDataURL(e){return ie(this,e)}toImageData(e){return ye(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,e)}}}),te,ve=y(()=>{Re(),te=Ve}),Ke,Ne,Ue,ze,Ze=y(()=>{P(),Ke=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ne=(e,t)=>{let s=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let i=0;i{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ne("BEGIN",e)},ze=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ne("END",e)}}),at,mt=y(()=>{V(),ve(),Ze(),at=class hf{constructor(t){this.handler=t}async run(t,s,n){Ue();let i={},o={};if(typeof t!="object"||t===null||t instanceof te||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 te)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}.`);i[h]=null}if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,C=Object.getOwnPropertyNames(s);for(let u of this.outputNames)if(C.indexOf(u)!==-1){let k=s[u];(k===null||k instanceof te)&&(h=!0,a=!1,i[u]=k)}if(h){if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else o=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)i[h]=null;let c=await this.handler.run(t,i,o),p={};for(let h in c)if(Object.hasOwnProperty.call(c,h)){let C=c[h];C instanceof te?p[h]=C:p[h]=new te(C.type,C.data,C.dims)}return ze(),p}async release(){return this.handler.dispose()}static async create(t,s,n,i){Ue();let o,a={};if(typeof t=="string"){if(o=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(o=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 C=t,u=0,k=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>=C.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${C.byteLength}).`);if(k=t.byteLength-u,typeof n=="number"){if(k=n,!Number.isSafeInteger(k))throw new RangeError("'byteLength' must be an integer.");if(k<=0||u+k>C.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${C.byteLength-u}].`);if(typeof i=="object"&&i!==null)a=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(C,u,k)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,p]=await oe(a),h=await c.createInferenceSessionHandler(o,p);return ze(),new hf(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,ct=y(()=>{mt(),lt=at}),O=y(()=>{}),le=y(()=>{}),Q=y(()=>{}),we=y(()=>{}),Se={};T(Se,{InferenceSession:()=>lt,TRACE:()=>Ke,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>ze,Tensor:()=>te,env:()=>F,registerBackend:()=>K});var We=y(()=>{U(),ae(),ct(),ve(),O(),le(),Ze(),Q(),we()}),qe=y(()=>{}),tt={};T(tt,{default:()=>Nt});var st,ft,Nt,ss=y(()=>{Ch(),br(),Lr(),st="ort-wasm-proxy-worker",ft=globalThis.self?.name===st,ft&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":dn(s.wasm).then(()=>{Zd(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:i}=s;ec(i,n).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:n}=s,i=ur(n);postMessage({type:t,out:i});break}case"create":{let{model:n,options:i}=s;Up(n,i).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":Wp(s),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:i,inputs:o,outputIndices:a,options:c}=s;Kp(n,i,o,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},qp([...o,...p]))},p=>{postMessage({type:t,err:p})});break}case"end-profiling":Hp(s),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),Nt=ft?null:e=>new Worker(e??Ns,{type:"module",name:st})}),Ts={};T(Ts,{default:()=>As});var ms,Ps,As,tr=y(()=>{Ps=(ms=import.meta.url,async function(e={}){function t(){return Vt.buffer!=Xt.buffer&&ir(),Xt}function s(){return Vt.buffer!=Xt.buffer&&ir(),Ut}function n(){return Vt.buffer!=Xt.buffer&&ir(),$s}function i(){return Vt.buffer!=Xt.buffer&&ir(),ut}function o(){return Vt.buffer!=Xt.buffer&&ir(),xt}function a(){return Vt.buffer!=Xt.buffer&&ir(),hs}function c(){return Vt.buffer!=Xt.buffer&&ir(),vs}function p(){return Vt.buffer!=Xt.buffer&&ir(),er}var h,C,u=Object.assign({},e),k=new Promise((l,m)=>{h=l,C=m}),B=typeof window=="object",R=typeof importScripts=="function",z=R&&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 ne=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let J=()=>{let l=(E,D,G)=>(...fe)=>{let Qe=ln,et=D?.();fe=E(...fe);let bt=D?.();return et!==bt&&(E=bt,G(et),D=G=null),ln!=Qe?new Promise((Pt,Rt)=>{hh={resolve:Pt,reject:Rt}}):fe},m=E=>async(...D)=>{try{if(u.Gb)throw Error("Session already started");let G=u.Gb={hc:D[0],errors:[]},fe=await E(...D);if(u.Gb!==G)throw Error("Session mismatch");u.Hb?.flush();let Qe=G.errors;if(0bt),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),J=void 0};u.jsepInit=(l,m)=>{if(J?.(),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=(D,G,fe,Qe)=>E.registerBuffer(D,G,fe,Qe),u.jsepGetBuffer=D=>E.getBuffer(D),u.jsepCreateDownloader=(D,G,fe)=>E.createDownloader(D,G,fe),u.jsepOnCreateSession=D=>{E.onCreateSession(D)},u.jsepOnReleaseSession=D=>{E.onReleaseSession(D)},u.jsepOnRunStart=D=>E.onRunStart(D),u.dc=(D,G)=>{E.upload(D,G)}}else if(l==="webnn"){[u.Hb,u.bc,u.Pb,u.jsepEnsureTensor,u.ec,u.jsepDownloadTensor]=m,u.jsepReleaseTensorId=u.Pb;let E=u.Hb;u.jsepOnRunStart=D=>E.onRunStart(D),u.jsepRegisterMLContext=(D,G)=>{E.registerMLContext(D,G)},u.jsepOnReleaseSession=D=>{E.onReleaseSession(D)},u.jsepCreateMLTensorDownloader=(D,G)=>E.createMLTensorDownloader(D,G),u.jsepRegisterMLTensor=(D,G,fe)=>E.registerMLTensor(D,G,fe),u.jsepCreateMLContext=D=>E.createMLContext(D),u.jsepRegisterMLConstant=(D,G,fe,Qe,et)=>E.registerMLConstant(D,G,fe,Qe,et,u.Fb)}};var W,ue,he=Object.assign({},u),be="./this.program",Be=(l,m)=>{throw m},Ie="";(B||R)&&(R?Ie=self.location.href:typeof document<"u"&&document.currentScript&&(Ie=document.currentScript.src),ms&&(Ie=ms),Ie=Ie.startsWith("blob:")?"":Ie.substr(0,Ie.replace(/[?#].*/,"").lastIndexOf("/")+1),R&&(ue=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),W=(l,m,E)=>{var D=new XMLHttpRequest;D.open("GET",l,!0),D.responseType="arraybuffer",D.onload=()=>{D.status==200||D.status==0&&D.response?m(D.response):E()},D.onerror=E,D.send(null)});var nt,dt=console.log.bind(console),Et=console.error.bind(console),zt=dt,It=Et;if(Object.assign(u,he),he=null,z){let l=function(m){try{var E=m.data,D=E.cmd;if(D==="load"){let G=[];self.onmessage=fe=>G.push(fe),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let fe of G)l(fe);self.onmessage=l};for(let fe of E.handlers)u[fe]&&!u[fe].proxy||(u[fe]=(...Qe)=>{postMessage({Nb:"callHandler",pc:fe,args:Qe})},fe=="print"&&(zt=u[fe]),fe=="printErr"&&(It=u[fe]));Vt=E.wasmMemory,ir(),ht(E.wasmModule)}else if(D==="run"){gh(E.pthread_ptr,0,0,1,0,0),ch(E.pthread_ptr),Cf(),Yh(),Jt||(qm(),Jt=!0);try{kf(E.start_routine,E.arg)}catch(G){if(G!="unwind")throw G}}else D==="cancel"?Pa()&&Ap(-1):E.target!=="setimmediate"&&(D==="checkMailbox"?Jt&&bp():D&&(It(`worker: received unknown command ${D}`),It(E)))}catch(G){throw Qm(),G}};var ht,Jt=!1;It=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(D=>{ht=G=>{G=new WebAssembly.Instance(G,Kh()),E(G),D()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}u.wasmBinary&&(nt=u.wasmBinary);var Vt,St,ts,Xt,Ut,$s,ut,xt,hs,vs,xs,xn,er,Ss=!1;function ir(){var l=Vt.buffer;u.HEAP8=Xt=new Int8Array(l),u.HEAP16=$s=new Int16Array(l),u.HEAPU8=Ut=new Uint8Array(l),u.HEAPU16=ut=new Uint16Array(l),u.HEAP32=xt=new Int32Array(l),u.HEAPU32=hs=new Uint32Array(l),u.HEAPF32=vs=new Float32Array(l),u.HEAPF64=er=new Float64Array(l),u.HEAP64=xs=new BigInt64Array(l),u.HEAPU64=xn=new BigUint64Array(l)}if(!z){if(!((Vt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof ne))throw It("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");ir()}var yp=[],rc=[],Tf=[],nc=0,ic=null;function jh(){if(--nc==0&&ic){var l=ic;ic=null,l()}}function Hn(l){throw It(l="Aborted("+l+")"),Ss=!0,ts=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),C(l),l}var Zp,Vh=l=>l.startsWith("data:application/octet-stream;base64,"),Uh=l=>l.startsWith("file://");function Wh(l){if(l==Zp&&nt)return new Uint8Array(nt);if(ue)return ue(l);throw"both async and sync fetching of the wasm failed"}function Gh(l,m,E){return function(D){if(!nt&&(B||R)){if(typeof fetch=="function"&&!Uh(D))return fetch(D,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${D}'`;return G.arrayBuffer()}).catch(()=>Wh(D));if(W)return new Promise((G,fe)=>{W(D,Qe=>G(new Uint8Array(Qe)),fe)})}return Promise.resolve().then(()=>Wh(D))}(l).then(D=>WebAssembly.instantiate(D,m)).then(E,D=>{It(`failed to asynchronously prepare wasm: ${D}`),Hn(D)})}function Kh(){return{a:{O:Ef,Aa:Pf,b:$f,aa:tm,B:nm,qa:im,Y:am,_:lm,ra:um,oa:dm,ha:cm,na:pm,L:hm,Z:mm,W:fm,pa:_m,X:gm,va:Af,F:If,Q:Ff,P:Df,E:zf,u:Bf,q:Rf,G:Nf,A:Hf,R:qf,ua:Qf,ka:Xf,U:Yf,ba:Jf,H:Zf,ja:ch,ta:e_,t:t_,Ba:s_,x:i_,n:o_,l:l_,c:uh,o:u_,j:p_,w:h_,p:m_,f:f_,s:__,m:g_,e:w_,k:y_,i:M_,h:b_,d:v_,ea:x_,fa:T_,ga:P_,ca:Am,da:Im,T:E_,g:C_,D:k_,I:S_,M:$_,y:A_,sa:I_,V:F_,v:Om,z:O_,N:D_,S:L_,za:z_,ya:B_,la:zm,ma:Bm,$:nh,C:Rm,K:Nm,ia:jm,J:Vm,a:Vt,xa:rh,wa:Gm,r:j_}}}var eh={913700:(l,m,E,D,G)=>{if(u===void 0||!u.Fb)return 1;if((l=Ws(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=u.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),D=Number(D>>>0),m+E>l.byteLength)return 3;try{let fe=l.subarray(m,m+E);switch(G){case 0:s().set(fe,D>>>0);break;case 1:u.dc(D,fe);break;default:return 4}return 0}catch{return 4}},914415:(l,m,E)=>{u.ec(l,s().subarray(m>>>0,m+E>>>0))},914478:()=>u.bc(),914519:l=>{u.Pb(l)},914555:()=>{u.Wb()},914586:()=>{u.Xb()},914615:()=>{u.ac()},914640:l=>u.Vb(l),914673:l=>u.Zb(l),914705:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E),!0)},914768:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E))},914825:()=>typeof wasmOffsetConverter<"u",914882:l=>{u.kb("Abs",l,void 0)},914933:l=>{u.kb("Neg",l,void 0)},914984:l=>{u.kb("Floor",l,void 0)},915037:l=>{u.kb("Ceil",l,void 0)},915089:l=>{u.kb("Reciprocal",l,void 0)},915147:l=>{u.kb("Sqrt",l,void 0)},915199:l=>{u.kb("Exp",l,void 0)},915250:l=>{u.kb("Erf",l,void 0)},915301:l=>{u.kb("Sigmoid",l,void 0)},915356:(l,m,E)=>{u.kb("HardSigmoid",l,{alpha:m,beta:E})},915435:l=>{u.kb("Log",l,void 0)},915486:l=>{u.kb("Sin",l,void 0)},915537:l=>{u.kb("Cos",l,void 0)},915588:l=>{u.kb("Tan",l,void 0)},915639:l=>{u.kb("Asin",l,void 0)},915691:l=>{u.kb("Acos",l,void 0)},915743:l=>{u.kb("Atan",l,void 0)},915795:l=>{u.kb("Sinh",l,void 0)},915847:l=>{u.kb("Cosh",l,void 0)},915899:l=>{u.kb("Asinh",l,void 0)},915952:l=>{u.kb("Acosh",l,void 0)},916005:l=>{u.kb("Atanh",l,void 0)},916058:l=>{u.kb("Tanh",l,void 0)},916110:l=>{u.kb("Not",l,void 0)},916161:(l,m,E)=>{u.kb("Clip",l,{min:m,max:E})},916230:l=>{u.kb("Clip",l,void 0)},916282:(l,m)=>{u.kb("Elu",l,{alpha:m})},916340:l=>{u.kb("Gelu",l,void 0)},916392:l=>{u.kb("Relu",l,void 0)},916444:(l,m)=>{u.kb("LeakyRelu",l,{alpha:m})},916508:(l,m)=>{u.kb("ThresholdedRelu",l,{alpha:m})},916578:(l,m)=>{u.kb("Cast",l,{to:m})},916636:l=>{u.kb("Add",l,void 0)},916687:l=>{u.kb("Sub",l,void 0)},916738:l=>{u.kb("Mul",l,void 0)},916789:l=>{u.kb("Div",l,void 0)},916840:l=>{u.kb("Pow",l,void 0)},916891:l=>{u.kb("Equal",l,void 0)},916944:l=>{u.kb("Greater",l,void 0)},916999:l=>{u.kb("GreaterOrEqual",l,void 0)},917061:l=>{u.kb("Less",l,void 0)},917113:l=>{u.kb("LessOrEqual",l,void 0)},917172:(l,m,E,D,G)=>{u.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917347:(l,m,E,D,G)=>{u.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917521:(l,m,E,D,G)=>{u.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917695:(l,m,E,D,G)=>{u.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},917870:(l,m,E,D,G)=>{u.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918044:(l,m,E,D,G)=>{u.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918217:(l,m,E,D,G)=>{u.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918390:(l,m,E,D,G)=>{u.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918567:(l,m,E,D,G)=>{u.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918747:(l,m,E,D,G)=>{u.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},918927:l=>{u.kb("Where",l,void 0)},918980:(l,m,E)=>{u.kb("Transpose",l,{perm:m?Array.from(o().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},919104:(l,m,E,D)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:Ws(E),format:D?"NHWC":"NCHW"})},919237:(l,m,E,D)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:Ws(E),format:D?"NHWC":"NCHW"})},919370:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge,os)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:D,kernelShape:[G],pads:[fe,Qe],strides:[et],wIsConst:()=>!!t()[Pt>>>0],outputPadding:Rt?Array.from(o().subarray(Number(Rt)>>>0,Number(us)>>>0)):[],outputShape:_s?Array.from(o().subarray(Number(_s)>>>0,Number(Ge)>>>0)):[],activation:Ws(os)})},919803:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge)=>{u.kb("ConvTranspose",l,{format:et?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:D,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(fe)>>>0,4+(Number(fe)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Qe)>>>0,2+(Number(Qe)>>>0)>>>0)),wIsConst:()=>!!t()[bt>>>0],outputPadding:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],outputShape:us?Array.from(o().subarray(Number(us)>>>0,Number(_s)>>>0)):[],activation:Ws(Ge)})},920464:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge,os)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:D,kernelShape:[G],pads:[fe,Qe],strides:[et],wIsConst:()=>!!t()[Pt>>>0],outputPadding:Rt?Array.from(o().subarray(Number(Rt)>>>0,Number(us)>>>0)):[],outputShape:_s?Array.from(o().subarray(Number(_s)>>>0,Number(Ge)>>>0)):[],activation:Ws(os)})},920897:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge)=>{u.kb("ConvTranspose",l,{format:et?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:D,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(fe)>>>0,4+(Number(fe)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Qe)>>>0,2+(Number(Qe)>>>0)>>>0)),wIsConst:()=>!!t()[bt>>>0],outputPadding:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],outputShape:us?Array.from(o().subarray(Number(us)>>>0,Number(_s)>>>0)):[],activation:Ws(Ge)})},921558:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},921649:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge)=>{u.kb("AveragePool",l,{format:Ge?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:fe?Array.from(o().subarray(Number(fe)>>>0,Number(Qe)>>>0)):[],kernel_shape:et?Array.from(o().subarray(Number(et)>>>0,Number(bt)>>>0)):[],pads:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:us?Array.from(o().subarray(Number(us)>>>0,Number(_s)>>>0)):[]})},922128:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},922219:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge)=>{u.kb("AveragePool",l,{format:Ge?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:fe?Array.from(o().subarray(Number(fe)>>>0,Number(Qe)>>>0)):[],kernel_shape:et?Array.from(o().subarray(Number(et)>>>0,Number(bt)>>>0)):[],pads:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:us?Array.from(o().subarray(Number(us)>>>0,Number(_s)>>>0)):[]})},922698:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},922785:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge)=>{u.kb("MaxPool",l,{format:Ge?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:fe?Array.from(o().subarray(Number(fe)>>>0,Number(Qe)>>>0)):[],kernel_shape:et?Array.from(o().subarray(Number(et)>>>0,Number(bt)>>>0)):[],pads:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:us?Array.from(o().subarray(Number(us)>>>0,Number(_s)>>>0)):[]})},923260:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},923347:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge)=>{u.kb("MaxPool",l,{format:Ge?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:D,storage_order:G,dilations:fe?Array.from(o().subarray(Number(fe)>>>0,Number(Qe)>>>0)):[],kernel_shape:et?Array.from(o().subarray(Number(et)>>>0,Number(bt)>>>0)):[],pads:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:us?Array.from(o().subarray(Number(us)>>>0,Number(_s)>>>0)):[]})},923822:(l,m,E,D,G)=>{u.kb("Gemm",l,{alpha:m,beta:E,transA:D,transB:G})},923926:l=>{u.kb("MatMul",l,void 0)},923980:(l,m,E,D)=>{u.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:D})},924088:(l,m,E,D)=>{u.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:D})},924196:(l,m)=>{u.kb("Softmax",l,{axis:m})},924259:(l,m)=>{u.kb("Concat",l,{axis:m})},924319:(l,m,E,D,G)=>{u.kb("Split",l,{axis:m,numOutputs:E,splitSizes:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},924475:l=>{u.kb("Expand",l,void 0)},924529:(l,m)=>{u.kb("Gather",l,{axis:Number(m)})},924600:(l,m)=>{u.kb("GatherElements",l,{axis:Number(m)})},924679:(l,m)=>{u.kb("GatherND",l,{batch_dims:Number(m)})},924758:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt)=>{u.kb("Resize",l,{antialias:m,axes:E?Array.from(o().subarray(Number(E)>>>0,Number(D)>>>0)):[],coordinateTransformMode:Ws(G),cubicCoeffA:fe,excludeOutside:Qe,extrapolationValue:et,keepAspectRatioPolicy:Ws(bt),mode:Ws(Pt),nearestMode:Ws(Rt)})},925120:(l,m,E,D,G,fe,Qe)=>{u.kb("Slice",l,{starts:m?Array.from(o().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[],axes:fe?Array.from(o().subarray(Number(fe)>>>0,Number(Qe)>>>0)):[]})},925384:l=>{u.kb("Tile",l,void 0)},925436:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},925550:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},925664:l=>{u.kb("Range",l,void 0)},925717:(l,m)=>{u.kb("Einsum",l,{equation:Ws(m)})},925798:(l,m,E,D,G)=>{u.kb("Pad",l,{mode:m,value:E,pads:D?Array.from(o().subarray(Number(D)>>>0,Number(G)>>>0)):[]})},925941:(l,m,E,D,G,fe)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!D,format:fe?"NHWC":"NCHW"})},926110:(l,m,E,D,G,fe)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!D,format:fe?"NHWC":"NCHW"})},926279:(l,m,E)=>{u.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},926376:(l,m,E)=>{u.kb("DequantizeLinear",l,{axis:m,blockSize:E})},926466:(l,m,E,D,G)=>{u.kb("GridSample",l,{align_corners:m,mode:Ws(E),padding_mode:Ws(D),format:G?"NHWC":"NCHW"})},926636:(l,m,E,D,G)=>{u.kb("GridSample",l,{align_corners:m,mode:Ws(E),padding_mode:Ws(D),format:G?"NHWC":"NCHW"})},926806:(l,m,E,D,G,fe,Qe,et,bt)=>{u.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:D,scale:G,doRotary:fe,qkvHiddenSizes:Qe?Array.from(o().subarray(Number(et)>>>0,Number(et)+Qe>>>0)):[],pastPresentShareBuffer:!!bt})},927078:l=>{u.kb("BiasAdd",l,void 0)},927133:l=>{u.kb("BiasSplitGelu",l,void 0)},927194:l=>{u.kb("FastGelu",l,void 0)},927250:(l,m,E,D,G,fe,Qe,et,bt,Pt,Rt,us,_s,Ge,os,Rs)=>{u.kb("Conv",l,{format:us?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(o().subarray(Number(E)>>>0,Number(D)>>>0)):[],group:G,kernel_shape:fe?Array.from(o().subarray(Number(fe)>>>0,Number(Qe)>>>0)):[],pads:et?Array.from(o().subarray(Number(et)>>>0,Number(bt)>>>0)):[],strides:Pt?Array.from(o().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],w_is_const:()=>!!t()[Number(_s)>>>0],activation:Ws(Ge),activation_params:os?Array.from(c().subarray(Number(os)>>>0,Number(Rs)>>>0)):[]})},927834:l=>{u.kb("Gelu",l,void 0)},927886:(l,m,E,D,G,fe,Qe,et,bt)=>{u.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:D,softcap:G,doRotary:fe,rotaryInterleaved:Qe,smoothSoftmax:et,localWindowSize:bt})},928103:(l,m,E,D)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!D})},928214:(l,m,E,D)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!D})},928325:(l,m,E,D,G,fe)=>{u.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:D,bits:G,blockSize:fe})},928452:(l,m,E,D,G,fe)=>{u.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:D,scale:G,doRotary:fe})},928611:(l,m)=>{u.kb("QuickGelu",l,{alpha:m})},928675:(l,m,E,D,G)=>{u.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:D,scale:G})},928814:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},928916:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},929018:(l,m,E,D)=>{u.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:D})},929139:l=>{u.$b(l)},929173:(l,m)=>u.cc(Number(l),Number(m),u.Gb.hc,u.Gb.errors)};function Pf(l,m,E){return Em(async()=>{await u.Yb(Number(l),Number(m),Number(E))})}function Ef(){return typeof wasmOffsetConverter<"u"}function th(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var sh=l=>{l.terminate(),l.onmessage=()=>{}},Hh=l=>{qn.length==0&&(Zh(),Jh(qn[0]));var m=qn.pop();if(!m)return 6;Si.push(m),on[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},ki=0,Ds=(l,m,...E)=>{for(var D=2*E.length,G=Mh(),fe=yh(8*D),Qe=fe>>>3,et=0;et>>0]=bt)}return l=Xm(l,0,D,fe,m),Ip(G),l};function rh(l){if(z)return Ds(0,1,l);if(ts=l,!(0{if(ts=l,z)throw qh(l),"unwind";rh(l)},qn=[],Si=[],Qh=[],on={},Xh=l=>{var m=l.Bb;delete on[m],qn.push(l),Si.splice(Si.indexOf(l),1),l.Bb=0,wh(m)};function Yh(){Qh.forEach(l=>l())}var Jh=l=>new Promise(m=>{l.onmessage=G=>{var fe=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Pa()){var Qe=on[G.targetThread];Qe?Qe.postMessage(G,G.transferList):It(`Internal error! Worker sent a message "${fe}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else fe==="checkMailbox"?bp():fe==="spawnThread"?Hh(G):fe==="cleanupThread"?Xh(on[G.thread]):fe==="killThread"?(G=G.thread,fe=on[G],delete on[G],sh(fe),wh(G),Si.splice(Si.indexOf(fe),1),fe.Bb=0):fe==="cancelThread"?on[G.thread].postMessage({cmd:"cancel"}):fe==="loaded"?(l.loaded=!0,m(l)):fe==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):fe==="callHandler"?u[G.handler](...G.args):fe&&It(`worker sent an unknown command ${fe}`)},l.onerror=G=>{throw It(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var E,D=[];for(E of[])u.hasOwnProperty(E)&&D.push(E);l.postMessage({cmd:"load",handlers:D,wasmMemory:Vt,wasmModule:St})});function Zh(){var l=new Worker(import.meta.url.startsWith("file:")?new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b):new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});qn.push(l)}var Mp=l=>{for(;0{var l=Pa(),m=a()[l+52>>>2>>>0];l=a()[l+56>>>2>>>0],Jm(m,m-l),Ip(m)},kf=(l,m)=>{ki=0,l=Zm(l,m),0>>=0);throw m>>>=0,E>>>=0,a()[D.Kb+16>>>2>>>0]=0,a()[D.Kb+4>>>2>>>0]=m,a()[D.Kb+8>>>2>>>0]=E,l}function em(l,m,E,D){return z?Ds(2,1,l,m,E,D):tm(l,m,E,D)}function tm(l,m,E,D){if(l>>>=0,m>>>=0,E>>>=0,D>>>=0,ne===void 0)return It("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return z&&G.length===0?em(l,m,E,D):(l={ic:E,Bb:l,Rb:D,nc:G},z?(l.Nb="spawnThread",postMessage(l,G),0):Hh(l))}var sm=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,rm=(l,m,E)=>{var D=(m>>>=0)+E;for(E=m;l[E]&&!(E>=D);)++E;if(16(G=(240&G)==224?(15&G)<<12|fe<<6|Qe:(7&G)<<18|fe<<12|Qe<<6|63&l[m++])?D+=String.fromCharCode(G):(G-=65536,D+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else D+=String.fromCharCode(G)}return D},Ws=(l,m)=>(l>>>=0)?rm(s(),l,m):"";function nm(l,m,E){return z?Ds(3,1,l,m,E):0}function im(l,m){if(z)return Ds(4,1,l,m)}var ih=l=>{for(var m=0,E=0;E=D?m++:2047>=D?m+=2:55296<=D&&57343>=D?(m+=4,++E):m+=3}return m},om=(l,m,E,D)=>{if(!(0>>=0;D=E+D-1;for(var fe=0;fe=Qe&&(Qe=65536+((1023&Qe)<<10)|1023&l.charCodeAt(++fe)),127>=Qe){if(E>=D)break;m[E++>>>0]=Qe}else{if(2047>=Qe){if(E+1>=D)break;m[E++>>>0]=192|Qe>>6}else{if(65535>=Qe){if(E+2>=D)break;m[E++>>>0]=224|Qe>>12}else{if(E+3>=D)break;m[E++>>>0]=240|Qe>>18,m[E++>>>0]=128|Qe>>12&63}m[E++>>>0]=128|Qe>>6&63}m[E++>>>0]=128|63&Qe}}return m[E>>>0]=0,E-G},xa=(l,m,E)=>om(l,s(),m,E);function am(l,m){if(z)return Ds(5,1,l,m)}function lm(l,m,E){if(z)return Ds(6,1,l,m,E)}function um(l,m,E){return z?Ds(7,1,l,m,E):0}function dm(l,m){if(z)return Ds(8,1,l,m)}function cm(l,m,E){if(z)return Ds(9,1,l,m,E)}function pm(l,m,E,D){if(z)return Ds(10,1,l,m,E,D)}function hm(l,m,E,D){if(z)return Ds(11,1,l,m,E,D)}function mm(l,m,E,D){if(z)return Ds(12,1,l,m,E,D)}function fm(l){if(z)return Ds(13,1,l)}function _m(l,m){if(z)return Ds(14,1,l,m)}function gm(l,m,E){if(z)return Ds(15,1,l,m,E)}var wm,Qn,Af=()=>{Hn("")},an=l=>{for(var m="";s()[l>>>0];)m+=wm[s()[l++>>>0]];return m},oh={},ah={};function Tn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(D,G,fe={}){var Qe=G.name;if(!D)throw new Qn(`type "${Qe}" must have a positive integer typeid pointer`);if(ah.hasOwnProperty(D)){if(fe.Tb)return;throw new Qn(`Cannot register type '${Qe}' twice`)}ah[D]=G,oh.hasOwnProperty(D)&&(G=oh[D],delete oh[D],G.forEach(et=>et()))}(l,m,E)}var ym=(l,m,E)=>{switch(m){case 1:return E?D=>t()[D>>>0]:D=>s()[D>>>0];case 2:return E?D=>n()[D>>>1>>>0]:D=>i()[D>>>1>>>0];case 4:return E?D=>o()[D>>>2>>>0]:D=>a()[D>>>2>>>0];case 8:return E?D=>xs[D>>>3]:D=>xn[D>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function If(l,m,E){E>>>=0,Tn(l>>>=0,{name:m=an(m>>>0),fromWireType:D=>D,toWireType:function(D,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(D=typeof G)=="object"||D==="array"||D==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:Xn,readValueFromPointer:ym(m,E,m.indexOf("u")==-1),Eb:null})}var Xn=8;function Ff(l,m,E,D){Tn(l>>>=0,{name:m=an(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,fe){return fe?E:D},argPackAdvance:Xn,readValueFromPointer:function(G){return this.fromWireType(s()[G>>>0])},Eb:null})}var lh=[],Pn=[];function uh(l){9<(l>>>=0)&&--Pn[l+1]==0&&(Pn[l]=void 0,lh.push(l))}var xr=l=>{if(!l)throw new Qn("Cannot use deleted val. handle = "+l);return Pn[l]},Or=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=lh.pop()||Pn.length;return Pn[m]=l,Pn[m+1]=1,m}};function dh(l){return this.fromWireType(a()[l>>>2>>>0])}var Of={name:"emscripten::val",fromWireType:l=>{var m=xr(l);return uh(l),m},toWireType:(l,m)=>Or(m),argPackAdvance:Xn,readValueFromPointer:dh,Eb:null};function Df(l){return Tn(l>>>0,Of)}var Lf=(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 zf(l,m,E){E>>>=0,Tn(l>>>=0,{name:m=an(m>>>0),fromWireType:D=>D,toWireType:(D,G)=>G,argPackAdvance:Xn,readValueFromPointer:Lf(m,E),Eb:null})}function Bf(l,m,E,D,G){if(l>>>=0,E>>>=0,m=an(m>>>0),G===-1&&(G=4294967295),G=et=>et,D===0){var fe=32-8*E;G=et=>et<>>fe}var Qe=m.includes("unsigned")?function(et,bt){return bt>>>0}:function(et,bt){return bt};Tn(l,{name:m,fromWireType:G,toWireType:Qe,argPackAdvance:Xn,readValueFromPointer:ym(m,E,D!==0),Eb:null})}function Rf(l,m,E){function D(fe){var Qe=a()[fe>>>2>>>0];return fe=a()[fe+4>>>2>>>0],new G(t().buffer,fe,Qe)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Tn(l>>>=0,{name:E=an(E>>>0),fromWireType:D,argPackAdvance:Xn,readValueFromPointer:D},{Tb:!0})}function Nf(l,m){l>>>=0;var E=(m=an(m>>>0))==="std::string";Tn(l,{name:m,fromWireType:function(D){var G=a()[D>>>2>>>0],fe=D+4;if(E)for(var Qe=fe,et=0;et<=G;++et){var bt=fe+et;if(et==G||s()[bt>>>0]==0){if(Qe=Ws(Qe,bt-Qe),Pt===void 0)var Pt=Qe;else Pt+="\0",Pt+=Qe;Qe=bt+1}}else{for(Pt=Array(G),et=0;et>>0]);Pt=Pt.join("")}return un(D),Pt},toWireType:function(D,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var fe=typeof G=="string";if(!(fe||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new Qn("Cannot pass non-string to std::string");var Qe=E&&fe?ih(G):G.length,et=$p(4+Qe+1),bt=et+4;if(a()[et>>>2>>>0]=Qe,E&&fe)xa(G,bt,Qe+1);else if(fe)for(fe=0;fe>>0]=Pt}else for(fe=0;fe>>0]=G[fe];return D!==null&&D.push(un,et),et},argPackAdvance:Xn,readValueFromPointer:dh,Eb(D){un(D)}})}var Mm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,jf=(l,m)=>{for(var E=l>>1,D=E+m/2;!(E>=D)&&i()[E>>>0];)++E;if(32<(E<<=1)-l&&Mm)return Mm.decode(s().slice(l,E));for(E="",D=0;!(D>=m/2);++D){var G=n()[l+2*D>>>1>>>0];if(G==0)break;E+=String.fromCharCode(G)}return E},Vf=(l,m,E)=>{if(E??=2147483647,2>E)return 0;var D=m;E=(E-=2)<2*l.length?E/2:l.length;for(var G=0;G>>1>>>0]=fe,m+=2}return n()[m>>>1>>>0]=0,m-D},Uf=l=>2*l.length,Wf=(l,m)=>{for(var E=0,D="";!(E>=m/4);){var G=o()[l+4*E>>>2>>>0];if(G==0)break;++E,65536<=G?(G-=65536,D+=String.fromCharCode(55296|G>>10,56320|1023&G)):D+=String.fromCharCode(G)}return D},Gf=(l,m,E)=>{if(m>>>=0,E??=2147483647,4>E)return 0;var D=m;E=D+E-4;for(var G=0;G=fe&&(fe=65536+((1023&fe)<<10)|1023&l.charCodeAt(++G)),o()[m>>>2>>>0]=fe,(m+=4)+4>E)break}return o()[m>>>2>>>0]=0,m-D},Kf=l=>{for(var m=0,E=0;E=D&&++E,m+=4}return m};function Hf(l,m,E){if(l>>>=0,m>>>=0,E=an(E>>>=0),m===2)var D=jf,G=Vf,fe=Uf,Qe=et=>i()[et>>>1>>>0];else m===4&&(D=Wf,G=Gf,fe=Kf,Qe=et=>a()[et>>>2>>>0]);Tn(l,{name:E,fromWireType:et=>{for(var bt,Pt=a()[et>>>2>>>0],Rt=et+4,us=0;us<=Pt;++us){var _s=et+4+us*m;us!=Pt&&Qe(_s)!=0||(Rt=D(Rt,_s-Rt),bt===void 0?bt=Rt:(bt+="\0",bt+=Rt),Rt=_s+m)}return un(et),bt},toWireType:(et,bt)=>{if(typeof bt!="string")throw new Qn(`Cannot pass non-string to C++ string type ${E}`);var Pt=fe(bt),Rt=$p(4+Pt+m);return a()[Rt>>>2>>>0]=Pt/m,G(bt,Rt+4,Pt+m),et!==null&&et.push(un,Rt),Rt},argPackAdvance:Xn,readValueFromPointer:dh,Eb(et){un(et)}})}function qf(l,m){Tn(l>>>=0,{Ub:!0,name:m=an(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Qf=()=>1;function Xf(l){gh(l>>>0,!R,1,!B,131072,!1),Yh()}var bm=l=>{if(!Ss)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(o(),l>>>2,l).value.then(bp),l+=128,Atomics.store(o(),l>>>2,1))}var bp=()=>{var l=Pa();l&&(ch(l),bm(Ym))};function Yf(l,m){(l>>>=0)==m>>>0?setTimeout(bp):z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=on[l])&&l.postMessage({cmd:"checkMailbox"})}var ph=[];function Jf(l,m,E,D,G){for(m>>>=0,D/=2,ph.length=D,E=G>>>0>>>3,G=0;G>>0];return(m?eh[m]:V_[l])(...ph)}function Zf(l){l>>>=0,z?postMessage({cmd:"cleanupThread",thread:l}):Xh(on[l])}function e_(l){}var vp=(l,m)=>{var E=ah[l];if(E===void 0)throw l=Hm(l),E=an(l),un(l),new Qn(`${m} has unknown type ${E}`);return E},vm=(l,m,E)=>{var D=[];return l=l.toWireType(D,E),D.length&&(a()[m>>>2>>>0]=Or(D)),l};function t_(l,m,E){return m>>>=0,E>>>=0,l=xr(l>>>0),m=vp(m,"emval::as"),vm(m,E,l)}function s_(l,m){return m>>>=0,l=xr(l>>>0),(m=vp(m,"emval::as")).toWireType(null,l)}var xp=l=>{try{l()}catch(m){Hn(m)}},Yn=0,ln=null,xm=0,Tp=[],Tm={},Pm={},r_=0,hh=null,n_=[];function Em(l){return function(m){if(!Ss){if(Yn===0){var E=!1,D=!1;m((G=0)=>{if(!Ss&&(xm=G,E=!0,D)){Yn=2,xp(()=>sf(ln)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var fe=function(){var bt=o()[ln+8>>>2>>>0];return bt=Bt[Pm[bt]],--ki,bt()}()}catch(bt){fe=bt,G=!0}var Qe=!1;if(!ln){var et=hh;et&&(hh=null,(G?et.reject:et.resolve)(fe),Qe=!0)}if(G&&!Qe)throw fe}}),D=!0,E||(Yn=1,ln=function(){var G=$p(65548),fe=G+12;a()[G>>>2>>>0]=fe,a()[G+4>>>2>>>0]=fe+65536,fe=Tp[0];var Qe=Tm[fe];return Qe===void 0&&(Qe=r_++,Tm[fe]=Qe,Pm[Qe]=fe),fe=Qe,o()[G+8>>>2>>>0]=fe,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),xp(()=>ef(ln)))}else Yn===2?(Yn=0,xp(rf),un(ln),ln=null,n_.forEach(bm)):Hn(`invalid state: ${Yn}`);return xm}}(m=>{l().then(m)})}function i_(l){return l>>>=0,Em(()=>(l=xr(l)).then(Or))}var Pp=[];function o_(l,m,E,D){return E>>>=0,D>>>=0,(l=Pp[l>>>0])(null,m=xr(m>>>0),E,D)}var a_={},Ep=l=>{var m=a_[l];return m===void 0?an(l):m};function l_(l,m,E,D,G){return E>>>=0,D>>>=0,G>>>=0,(l=Pp[l>>>0])(m=xr(m>>>0),m[E=Ep(E)],D,G)}var Cm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function u_(l){return(l>>>=0)==0?Or(Cm()):(l=Ep(l),Or(Cm()[l]))}var d_=l=>{var m=Pp.length;return Pp.push(l),m},c_=(l,m)=>{for(var E=Array(l),D=0;D>>2>>>0],"parameter "+D);return E},km=(l,m)=>Object.defineProperty(m,"name",{value:l});function p_(l,m,E){var D=(m=c_(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { +`,fe=0,Qe=[];E===0&&Qe.push("obj");for(var et=["retType"],bt=[D],Pt=0;PtRt.name).join(", ")}) => ${D.name}>`,d_(km(E,l))}function h_(l){return l=Ep(l>>>0),Or(u[l])}function m_(l,m){return m>>>=0,l=xr(l>>>0),m=xr(m),Or(l[m])}function f_(l){9<(l>>>=0)&&(Pn[l+1]+=1)}function __(){return Or([])}function g_(l){l=xr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function y_(){return Or({})}function M_(l){for(var m=xr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}uh(l)}function b_(l,m,E){m>>>=0,E>>>=0,l=xr(l>>>0),m=xr(m),E=xr(E),l[m]=E}function v_(l,m){return m>>>=0,l=(l=vp(l>>>0,"_emval_take_value")).readValueFromPointer(m),Or(l)}function x_(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[m>>>2>>>0]=l.getUTCSeconds(),o()[m+4>>>2>>>0]=l.getUTCMinutes(),o()[m+8>>>2>>>0]=l.getUTCHours(),o()[m+12>>>2>>>0]=l.getUTCDate(),o()[m+16>>>2>>>0]=l.getUTCMonth(),o()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,o()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[m+28>>>2>>>0]=l}var Ta=l=>l%4==0&&(l%100!=0||l%400==0),Sm=[0,31,60,91,121,152,182,213,244,274,305,335],$m=[0,31,59,90,120,151,181,212,243,273,304,334];function T_(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[m>>>2>>>0]=l.getSeconds(),o()[m+4>>>2>>>0]=l.getMinutes(),o()[m+8>>>2>>>0]=l.getHours(),o()[m+12>>>2>>>0]=l.getDate(),o()[m+16>>>2>>>0]=l.getMonth(),o()[m+20>>>2>>>0]=l.getFullYear()-1900,o()[m+24>>>2>>>0]=l.getDay();var E=(Ta(l.getFullYear())?Sm:$m)[l.getMonth()]+l.getDate()-1|0;o()[m+28>>>2>>>0]=E,o()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var D=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=D&&l.getTimezoneOffset()==Math.min(D,E)),o()[m+32>>>2>>>0]=l}function P_(l){l>>>=0;var m=new Date(o()[l+20>>>2>>>0]+1900,o()[l+16>>>2>>>0],o()[l+12>>>2>>>0],o()[l+8>>>2>>>0],o()[l+4>>>2>>>0],o()[l>>>2>>>0],0),E=o()[l+32>>>2>>>0],D=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),fe=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Qe=Math.min(fe,G);return 0>E?o()[l+32>>>2>>>0]=+(G!=fe&&Qe==D):0>>2>>>0]=m.getDay(),E=(Ta(m.getFullYear())?Sm:$m)[m.getMonth()]+m.getDate()-1|0,o()[l+28>>>2>>>0]=E,o()[l>>>2>>>0]=m.getSeconds(),o()[l+4>>>2>>>0]=m.getMinutes(),o()[l+8>>>2>>>0]=m.getHours(),o()[l+12>>>2>>>0]=m.getDate(),o()[l+16>>>2>>>0]=m.getMonth(),o()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function Am(l,m,E,D,G,fe,Qe){return z?Ds(16,1,l,m,E,D,G,fe,Qe):-52}function Im(l,m,E,D,G,fe){if(z)return Ds(17,1,l,m,E,D,G,fe)}function E_(l,m,E,D){l>>>=0,m>>>=0,E>>>=0,D>>>=0;var G=new Date().getFullYear(),fe=new Date(G,0,1),Qe=new Date(G,6,1);G=fe.getTimezoneOffset();var et=Qe.getTimezoneOffset(),bt=Math.max(G,et);a()[l>>>2>>>0]=60*bt,o()[m>>>2>>>0]=+(G!=et),fe=(l=Pt=>Pt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(fe),Qe=l(Qe),et{mh.length=0;for(var E;E=s()[l++>>>0];){var D=E!=105;m+=(D&=E!=112)&&m%8?4:0,mh.push(E==112?a()[m>>>2>>>0]:E==106?xs[m>>>3]:E==105?o()[m>>>2>>>0]:p()[m>>>3>>>0]),m+=D?8:4}return mh};function C_(l,m,E){return l>>>=0,m=Fm(m>>>0,E>>>0),eh[l](...m)}function k_(l,m,E){return l>>>=0,m=Fm(m>>>0,E>>>0),eh[l](...m)}var S_=()=>{},$_=()=>Date.now();function A_(l,m){return It(Ws(l>>>0,m>>>0))}var Om,I_=()=>{throw ki+=1,"unwind"};function F_(){return 4294901760}Om=()=>performance.timeOrigin+performance.now();var O_=()=>navigator.hardwareConcurrency;function D_(){return Hn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function L_(l){l>>>=0;var m=s().length;if(l<=m||4294901760=E;E*=2){var D=m*(1+.2/E);D=Math.min(D,l+100663296);var G=Math;D=Math.max(l,D);e:{G=(G.min.call(G,4294901760,D+(65536-D%65536)%65536)-Vt.buffer.byteLength+65535)/65536;try{Vt.grow(G),ir();var fe=1;break e}catch{}fe=void 0}if(fe)return!0}return!1}var Cp=()=>(Hn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),oc={},Dm=l=>{l.forEach(m=>{Cp()})};function z_(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),Dm(l),oc.Qb=Cp(),oc.fc=l,oc.Qb}function B_(l,m,E){if(l>>>=0,m>>>=0,oc.Qb==l)var D=oc.fc;else(D=Error().stack.toString().split(` +`))[0]=="Error"&&D.shift(),Dm(D);for(var G=3;D[G]&&Cp()!=l;)++G;for(l=0;l>>2>>>0]=Cp();return l}var fh,_h={},Lm=()=>{if(!fh){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",_:be};for(l in _h)_h[l]===void 0?delete m[l]:m[l]=_h[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);fh=E}return fh};function zm(l,m){if(z)return Ds(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Lm().forEach((D,G)=>{var fe=m+E;for(G=a()[l+4*G>>>2>>>0]=fe,fe=0;fe>>0]=D.charCodeAt(fe);t()[G>>>0]=0,E+=D.length+1}),0}function Bm(l,m){if(z)return Ds(19,1,l,m);l>>>=0,m>>>=0;var E=Lm();a()[l>>>2>>>0]=E.length;var D=0;return E.forEach(G=>D+=G.length+1),a()[m>>>2>>>0]=D,0}function Rm(l){return z?Ds(20,1,l):52}function Nm(l,m,E,D){return z?Ds(21,1,l,m,E,D):52}function jm(l,m,E,D){return z?Ds(22,1,l,m,E,D):70}var R_=[null,[],[]];function Vm(l,m,E,D){if(z)return Ds(23,1,l,m,E,D);m>>>=0,E>>>=0,D>>>=0;for(var G=0,fe=0;fe>>2>>>0],et=a()[m+4>>>2>>>0];m+=8;for(var bt=0;bt>>0],Rt=R_[l];Pt===0||Pt===10?((l===1?zt:It)(rm(Rt,0)),Rt.length=0):Rt.push(Pt)}G+=et}return a()[D>>>2>>>0]=G,0}var Um=[31,29,31,30,31,30,31,31,30,31,30,31],Wm=[31,28,31,30,31,30,31,31,30,31,30,31],N_=(l,m)=>{t().set(l,m>>>0)};function Gm(l,m,E,D){function G(Ge,os,Rs){for(Ge=typeof Ge=="number"?Ge.toString():Ge||"";Ge.lengthof?-1:0$i-Ge.getDate())){Ge.setDate(Ge.getDate()+os);break}os-=$i-Ge.getDate()+1,Ge.setDate(1),11>Rs?Ge.setMonth(Rs+1):(Ge.setMonth(0),Ge.setFullYear(Ge.getFullYear()+1))}return Rs=new Date(Ge.getFullYear()+1,0,4),os=et(new Date(Ge.getFullYear(),0,4)),Rs=et(Rs),0>=Qe(os,Ge)?0>=Qe(Rs,Ge)?Ge.getFullYear()+1:Ge.getFullYear():Ge.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,D>>>=0;var Pt=a()[D+40>>>2>>>0];for(var Rt in D={lc:o()[D>>>2>>>0],kc:o()[D+4>>>2>>>0],Ib:o()[D+8>>>2>>>0],Mb:o()[D+12>>>2>>>0],Jb:o()[D+16>>>2>>>0],Db:o()[D+20>>>2>>>0],vb:o()[D+24>>>2>>>0],Cb:o()[D+28>>>2>>>0],sc:o()[D+32>>>2>>>0],jc:o()[D+36>>>2>>>0],mc:Pt?Ws(Pt):""},E=Ws(E),Pt={"%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(Rt,"g"),Pt[Rt]);var us="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),_s="January February March April May June July August September October November December".split(" ");for(Rt in Pt={"%a":Ge=>us[Ge.vb].substring(0,3),"%A":Ge=>us[Ge.vb],"%b":Ge=>_s[Ge.Jb].substring(0,3),"%B":Ge=>_s[Ge.Jb],"%C":Ge=>fe((Ge.Db+1900)/100|0,2),"%d":Ge=>fe(Ge.Mb,2),"%e":Ge=>G(Ge.Mb,2," "),"%g":Ge=>bt(Ge).toString().substring(2),"%G":bt,"%H":Ge=>fe(Ge.Ib,2),"%I":Ge=>((Ge=Ge.Ib)==0?Ge=12:12{for(var os=0,Rs=0;Rs<=Ge.Jb-1;os+=(Ta(Ge.Db+1900)?Um:Wm)[Rs++]);return fe(Ge.Mb+os,3)},"%m":Ge=>fe(Ge.Jb+1,2),"%M":Ge=>fe(Ge.kc,2),"%n":()=>` +`,"%p":Ge=>0<=Ge.Ib&&12>Ge.Ib?"AM":"PM","%S":Ge=>fe(Ge.lc,2),"%t":()=>" ","%u":Ge=>Ge.vb||7,"%U":Ge=>fe(Math.floor((Ge.Cb+7-Ge.vb)/7),2),"%V":Ge=>{var os=Math.floor((Ge.Cb+7-(Ge.vb+6)%7)/7);if(2>=(Ge.vb+371-Ge.Cb-2)%7&&os++,os)os==53&&((Rs=(Ge.vb+371-Ge.Cb)%7)==4||Rs==3&&Ta(Ge.Db)||(os=1));else{os=52;var Rs=(Ge.vb+7-Ge.Cb-1)%7;(Rs==4||Rs==5&&Ta(Ge.Db%400-1))&&os++}return fe(os,2)},"%w":Ge=>Ge.vb,"%W":Ge=>fe(Math.floor((Ge.Cb+7-(Ge.vb+6)%7)/7),2),"%y":Ge=>(Ge.Db+1900).toString().substring(2),"%Y":Ge=>Ge.Db+1900,"%z":Ge=>{var os=0<=(Ge=Ge.jc);return Ge=Math.abs(Ge)/60,(os?"+":"-")+("0000"+(Ge/60*100+Ge%60)).slice(-4)},"%Z":Ge=>Ge.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),Pt)E.includes(Rt)&&(E=E.replace(new RegExp(Rt,"g"),Pt[Rt](D)));return Rt=function(Ge){var os=Array(ih(Ge)+1);return om(Ge,os,0,os.length),os}(E=E.replace(/\0\0/g,"%")),Rt.length>m?0:(N_(Rt,l),Rt.length-1)}function j_(l,m,E,D){return Gm(l>>>0,m>>>0,E>>>0,D>>>0)}z||function(){for(var l=u.numThreads-1;l--;)Zh();yp.unshift(()=>{nc++,function(m){z?m():Promise.all(qn.map(Jh)).then(m)}(()=>jh())})}();for(var Km=Array(256),kp=0;256>kp;++kp)Km[kp]=String.fromCharCode(kp);wm=Km,Qn=u.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},u.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},Pn.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>Pn.length/2-5-lh.length;var V_=[rh,qh,em,nm,im,am,lm,um,dm,cm,pm,hm,mm,fm,_m,gm,Am,Im,zm,Bm,Rm,Nm,jm,Vm],Bt=function(){function l(E,D){return Bt=E.exports,Bt=function(){var G=Bt,fe={};for(let[Qe,et]of Object.entries(G))fe[Qe]=typeof et=="function"?(...bt)=>{Tp.push(Qe);try{return et(...bt)}finally{Ss||(Tp.pop(),ln&&Yn===1&&Tp.length===0&&(Yn=0,ki+=1,xp(tf),typeof Fibers<"u"&&Fibers.tc()))}}:et;return fe}(),Bt=function(){var G=Bt,fe=et=>bt=>et(bt)>>>0,Qe=et=>()=>et()>>>0;return(G=Object.assign({},G)).Da=fe(G.Da),G.gb=Qe(G.gb),G.ib=fe(G.ib),G.emscripten_main_runtime_thread_id=Qe(G.emscripten_main_runtime_thread_id),G.tb=fe(G.tb),G.ub=Qe(G.ub),G}(),Qh.push(Bt.jb),rc.unshift(Bt.Ca),St=D,jh(),Bt}var m=Kh();if(nc++,u.instantiateWasm)try{return u.instantiateWasm(m,l)}catch(E){It(`Module.instantiateWasm callback failed with error: ${E}`),C(E)}return Zp||=u.locateFile?Vh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ie):Ie+"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,D){var G=Zp;return nt||typeof WebAssembly.instantiateStreaming!="function"||Vh(G)||Uh(G)||typeof fetch!="function"?Gh(G,E,D):fetch(G,{credentials:"same-origin"}).then(fe=>WebAssembly.instantiateStreaming(fe,E).then(D,function(Qe){return It(`wasm streaming compile failed: ${Qe}`),It("falling back to ArrayBuffer instantiation"),Gh(G,E,D)}))}(m,function(E){l(E.instance,E.module)}).catch(C),{}}(),Hm=l=>(Hm=Bt.Da)(l),qm=()=>(qm=Bt.Ea)();u._OrtInit=(l,m)=>(u._OrtInit=Bt.Fa)(l,m),u._OrtGetLastError=(l,m)=>(u._OrtGetLastError=Bt.Ga)(l,m),u._OrtCreateSessionOptions=(l,m,E,D,G,fe,Qe,et,bt,Pt)=>(u._OrtCreateSessionOptions=Bt.Ha)(l,m,E,D,G,fe,Qe,et,bt,Pt),u._OrtAppendExecutionProvider=(l,m)=>(u._OrtAppendExecutionProvider=Bt.Ia)(l,m),u._OrtAddFreeDimensionOverride=(l,m,E)=>(u._OrtAddFreeDimensionOverride=Bt.Ja)(l,m,E),u._OrtAddSessionConfigEntry=(l,m,E)=>(u._OrtAddSessionConfigEntry=Bt.Ka)(l,m,E),u._OrtReleaseSessionOptions=l=>(u._OrtReleaseSessionOptions=Bt.La)(l),u._OrtCreateSession=(l,m,E)=>(u._OrtCreateSession=Bt.Ma)(l,m,E),u._OrtReleaseSession=l=>(u._OrtReleaseSession=Bt.Na)(l),u._OrtGetInputOutputCount=(l,m,E)=>(u._OrtGetInputOutputCount=Bt.Oa)(l,m,E),u._OrtGetInputName=(l,m)=>(u._OrtGetInputName=Bt.Pa)(l,m),u._OrtGetOutputName=(l,m)=>(u._OrtGetOutputName=Bt.Qa)(l,m),u._OrtFree=l=>(u._OrtFree=Bt.Ra)(l),u._OrtCreateTensor=(l,m,E,D,G,fe)=>(u._OrtCreateTensor=Bt.Sa)(l,m,E,D,G,fe),u._OrtGetTensorData=(l,m,E,D,G)=>(u._OrtGetTensorData=Bt.Ta)(l,m,E,D,G),u._OrtReleaseTensor=l=>(u._OrtReleaseTensor=Bt.Ua)(l),u._OrtCreateRunOptions=(l,m,E,D)=>(u._OrtCreateRunOptions=Bt.Va)(l,m,E,D),u._OrtAddRunConfigEntry=(l,m,E)=>(u._OrtAddRunConfigEntry=Bt.Wa)(l,m,E),u._OrtReleaseRunOptions=l=>(u._OrtReleaseRunOptions=Bt.Xa)(l),u._OrtCreateBinding=l=>(u._OrtCreateBinding=Bt.Ya)(l),u._OrtBindInput=(l,m,E)=>(u._OrtBindInput=Bt.Za)(l,m,E),u._OrtBindOutput=(l,m,E,D)=>(u._OrtBindOutput=Bt._a)(l,m,E,D),u._OrtClearBoundOutputs=l=>(u._OrtClearBoundOutputs=Bt.$a)(l),u._OrtReleaseBinding=l=>(u._OrtReleaseBinding=Bt.ab)(l),u._OrtRunWithBinding=(l,m,E,D,G)=>(u._OrtRunWithBinding=Bt.bb)(l,m,E,D,G),u._OrtRun=(l,m,E,D,G,fe,Qe,et)=>(u._OrtRun=Bt.cb)(l,m,E,D,G,fe,Qe,et),u._OrtEndProfiling=l=>(u._OrtEndProfiling=Bt.db)(l),u._JsepOutput=(l,m,E)=>(u._JsepOutput=Bt.eb)(l,m,E),u._JsepGetNodeName=l=>(u._JsepGetNodeName=Bt.fb)(l);var Sp,Pa=()=>(Pa=Bt.gb)(),un=u._free=l=>(un=u._free=Bt.hb)(l),$p=u._malloc=l=>($p=u._malloc=Bt.ib)(l),gh=(l,m,E,D,G,fe)=>(gh=Bt.lb)(l,m,E,D,G,fe),Qm=()=>(Qm=Bt.mb)(),Xm=(l,m,E,D,G)=>(Xm=Bt.nb)(l,m,E,D,G),wh=l=>(wh=Bt.ob)(l),Ap=l=>(Ap=Bt.pb)(l),Ym=()=>(Ym=Bt.qb)(),Jm=(l,m)=>(Jm=Bt.rb)(l,m),Ip=l=>(Ip=Bt.sb)(l),yh=l=>(yh=Bt.tb)(l),Mh=()=>(Mh=Bt.ub)(),Zm=u.dynCall_ii=(l,m)=>(Zm=u.dynCall_ii=Bt.wb)(l,m),ef=l=>(ef=Bt.xb)(l),tf=()=>(tf=Bt.yb)(),sf=l=>(sf=Bt.zb)(l),rf=()=>(rf=Bt.Ab)();function nf(){0Mh(),u.stackRestore=l=>Ip(l),u.stackAlloc=l=>yh(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":o()[l>>>2>>>0]=m;break;case"i64":xs[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:Hn(`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 o()[l>>>2>>>0];case"i64":return xs[l>>>3];case"float":return c()[l>>>2>>>0];case"double":return p()[l>>>3>>>0];case"*":return a()[l>>>2>>>0];default:Hn(`invalid type for getValue: ${m}`)}},u.UTF8ToString=Ws,u.stringToUTF8=xa,u.lengthBytesUTF8=ih,ic=function l(){Sp||nf(),Sp||(ic=l)},nf(),u.PTR_SIZE=4,k}),As=Ps,globalThis.self?.name==="em-pthread"&&Ps()}),Tr,Gr,Ns,Mr,Lt,Kr,Pr,Er,Hr,dr,qr,Cr,Dr,Lr=y(()=>{qe(),Tr=typeof location>"u"?void 0:location.origin,Gr=()=>import.meta.url?.startsWith("file:")?new URL(new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b).href,Tr).href:import.meta.url,Ns=Gr(),Mr=()=>{if(Ns&&!Ns.startsWith("blob:"))return Ns.substring(0,Ns.lastIndexOf("/")+1)},Lt=(e,t)=>{try{let s=t??Ns;return(s?new URL(e,s):new URL(e)).origin===Tr}catch{return!1}},Kr=(e,t)=>{let s=t??Ns;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},Pr=(e,t)=>`${t??"./"}${e}`,Er=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Hr=async e=>(await import(e)).default,dr=(ss(),x(tt)).default,qr=async()=>{if(!Ns)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Lt(Ns))return[void 0,dr()];let e=await Er(Ns);return[e,dr(e)]},Cr=(tr(),x(Ts)).default,Dr=async(e,t,s)=>{if(!e&&!t&&Cr&&Ns&&Lt(Ns))return[void 0,Cr];{let n="ort-wasm-simd-threaded.jsep.mjs",i=e??Kr(n,t),o=s&&i&&!Lt(i,t),a=o?await Er(i):i??Pr(n,t);return[o?a:void 0,await Hr(a)]}}}),or,it,vt,Ft,Ys,Cn,dn,gs,br=y(()=>{Lr(),it=!1,vt=!1,Ft=!1,Ys=()=>{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}},Cn=()=>{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}},dn=async e=>{if(it)return Promise.resolve();if(vt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ft)throw new Error("previous call to 'initializeWebAssembly()' failed.");vt=!0;let t=e.initTimeout,s=e.numThreads;if(!Cn())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ys();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let i=e.wasmPaths,o=typeof i=="string"?i:void 0,a=i?.mjs,c=a?.href??a,p=i?.wasm,h=p?.href??p,C=e.wasmBinary,[u,k]=await Dr(c,o,s>1),B=!1,R=[];if(t>0&&R.push(new Promise(z=>{setTimeout(()=>{B=!0,z()},t)})),R.push(new Promise((z,ne)=>{let J={numThreads:s};if(C)J.wasmBinary=C;else if(h||o)J.locateFile=W=>h??o+W;else if(c&&c.indexOf("blob:")!==0)J.locateFile=W=>new URL(W,c).href;else if(u){let W=Mr();W&&(J.locateFile=ue=>W+ue)}k(J).then(W=>{vt=!1,it=!0,or=W,z(),u&&URL.revokeObjectURL(u)},W=>{vt=!1,Ft=!0,ne(W)})})),await Promise.race(R),B)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},gs=()=>{if(it&&or)return or;throw new Error("WebAssembly is not initialized yet.")}}),Ls,Qr,ns,cn=y(()=>{br(),Ls=(e,t)=>{let s=gs(),n=s.lengthBytesUTF8(e)+1,i=s._malloc(n);return s.stringToUTF8(e,i,n),t.push(i),i},Qr=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([i,o])=>{let a=t?t+i:i;if(typeof o=="object")Qr(o,a+".",s,n);else if(typeof o=="string"||typeof o=="number")n(a,o.toString());else if(typeof o=="boolean")n(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ns=e=>{let t=gs(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let o=Number(t.getValue(i,n===4?"i32":"i64")),a=t.getValue(i+n,"*"),c=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(s)}}}),zr,Jn=y(()=>{br(),cn(),zr=e=>{let t=gs(),s=0,n=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let o=0;return e?.tag!==void 0&&(o=Ls(e.tag,n)),s=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,o),s===0&&ns("Can't create run options."),e?.extra!==void 0&&Qr(e.extra,"",new WeakSet,(a,c)=>{let p=Ls(a,n),h=Ls(c,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ns(`Can't set a run config entry: ${a} - ${c}.`)}),[s,n]}catch(o){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(a=>t._free(a)),o}}}),kn,Sn,$n,Br,An,Zn=y(()=>{br(),cn(),kn=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}`)}},Sn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},$n=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)},Br=(e,t,s)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let a=n?.deviceType;if(a){let c=Ls("deviceType",s),p=Ls(a,s);gs()._OrtAddSessionConfigEntry(e,c,p)!==0&&ns(`Can't set a session config entry: 'deviceType' - ${a}.`)}}break;case"webgpu":if(i="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=Ls("preferredLayout",s),p=Ls(a.preferredLayout,s);gs()._OrtAddSessionConfigEntry(e,c,p)!==0&&ns(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let o=Ls(i,s);gs()._OrtAppendExecutionProvider(e,o)!==0&&ns(`Can't append execution provider: ${i}.`)}},An=e=>{let t=gs(),s=0,n=[],i=e||{};$n(i);try{let o=kn(i.graphOptimizationLevel??"all"),a=Sn(i.executionMode??"sequential"),c=typeof i.logId=="string"?Ls(i.logId,n):0,p=i.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=i.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let C=typeof i.optimizedModelFilePath=="string"?Ls(i.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(o,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,c,p,h,C),s===0&&ns("Can't create session options."),i.executionProviders&&Br(s,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let u=Ls("enableGraphCapture",n),k=Ls(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,u,k)!==0&&ns(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[u,k]of Object.entries(i.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof k!="number"||!Number.isInteger(k)||k<0)throw new Error(`free dimension override value must be a non-negative integer: ${k}`);let B=Ls(u,n);t._OrtAddFreeDimensionOverride(s,B,k)!==0&&ns(`Can't set a free dimension override: ${u} - ${k}.`)}return i.extra!==void 0&&Qr(i.extra,"",new WeakSet,(u,k)=>{let B=Ls(u,n),R=Ls(k,n);t._OrtAddSessionConfigEntry(s,B,R)!==0&&ns(`Can't set a session config entry: ${u} - ${k}.`)}),[s,n]}catch(o){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ns("Can't release session options."),n.forEach(a=>t._free(a)),o}}}),Rr,fr,ar,pn,Xr,hn,mn,fn,Ot=y(()=>{Rr=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}`)}},ar=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((i,o)=>i*o,1);return s>0?Math.ceil(n*s):void 0},pn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Xr=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}`)}},hn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",mn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",fn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),_n,In=y(()=>{qe(),_n=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),o;try{o=new ArrayBuffer(n)}catch(c){if(c instanceof RangeError){let p=Math.ceil(n/65536);o=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw c}let a=0;for(;;){let{done:c,value:p}=await i.read();if(c)break;let h=p.byteLength;new Uint8Array(o,a,h).set(p),a+=h}return new Uint8Array(o,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Fn,On,Nr,Dn,gn,Ln,as,Te=y(()=>{Ot(),Fn=["V","I","W","E","F"],On=(e,t)=>{console.log(`[${Fn[e]},${new Date().toISOString()}]${t}`)},gn=(e,t)=>{Nr=e,Dn=t},Ln=(e,t)=>{let s=Xr(e),n=Xr(Nr);s>=n&&On(s,typeof t=="function"?t():t)},as=(...e)=>{Dn&&Ln(...e)}}),M,Y=y(()=>{Ot(),M=(e,t)=>new(pn(t))(e)}),ce=y(()=>{}),me,Fe,Ye,gt,wt,yt,pt,rs,Yt,Ms=y(()=>{Te(),ce(),me=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]]),Fe=[],Ye=e=>Math.ceil(Number(e)/16)*16,gt=e=>{for(let t=0;twt++,pt=async(e,t,s,n)=>{let i=Ye(s),o=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,o,0,i),e.flush(),await o.mapAsync(GPUMapMode.READ);let c=o.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(c,0,s)),p}else return new Uint8Array(c.slice(0,s))}finally{o.destroy()}},rs=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 me)Fe.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,i=t.byteLength,o=Ye(i),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(Number(a.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${i}`);let c=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=c.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,i)),c.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(c,0,a.gpuData.buffer,0,o),this.backend.device.queue.submit([h.finish()]),c.destroy(),as("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=Ye(s.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return as("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=yt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),as("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),as("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=gt(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||o){let c=(i?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:yt(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:Number(e)}),as("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 as("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 pt(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=me.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&&(as("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Yt=(...e)=>new rs(...e)}),Gs,jt,is=y(()=>{Gs=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}},jt=e=>new Gs(e)}),Ks,Js,De,Xs,kr,Es,Hs,$t=y(()=>{Ks=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Js=class{static calcShape(e,t,s=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let o=Math.max(e.length,t.length),a=new Array(o);if(s){if(n<2||i<2)return;let c=Ks.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(c===void 0)return;[a[o-2],a[o-1]]=c}for(let c=s?3:1;c<=o;c++){let p=n-c<0?1:e[n-c],h=i-c<0?1:t[i-c];if(p!==h&&p>1&&h>1)return;let C=Math.max(p,h);if(p&&h)a[o-c]=Math.max(p,h);else{if(C>1)return;a[o-c]=0}}return a}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let i=1;i<=s;i++)if(e[s-i]!==1&&e[s-i]!==t[n-i])return!1;return!0}},De=class Dp{static size(t){return Dp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let i=new Array(n),o=n-1;for(;o>=0;){if(t[o]%s===0){i[o]=t[o]/s;break}if(s%t[o]!==0)throw new Error("cannot convert shape");i[o]=1,s/=t[o],o--}for(o--;o>=0;o--)i[o]=t[o];return i}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Dp.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Dp.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let i=1;for(let o=s;o=0;--i)n[i]=n[i+1]*t[i+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((i,o)=>i+s[o]+s[o+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,i)=>n===s[i])}},Xs=class ac{static adjustPoolAttributes(t,s,n,i,o,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,i,o,a,c){if(c){if(o.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Ot(),$t(),sr=64,_r=(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}`)}},ds=(e,t=1)=>{let s=_r(e,t);return typeof s=="string"?s:s[0]},Cs=(e,t=1)=>{let s=_r(e,t);return typeof s=="string"?s:s[1]},Mt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:De.computeStrides(s)})}),t},Gt=e=>e%4===0?4:e%2===0?2:1,Is=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,ks=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,js=(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,Tt=(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,Yr=(e,t,s,n,i)=>{let o=typeof s=="number",a=o?s:s.length,c=[...new Array(a).keys()],p=a<2?"u32":a<=4?`vec${a}`:`array`,h=_r(t,i),C=typeof h=="string"?h:h[1],u=typeof h=="string"?h:h[0],k={indices:p,value:C,storage:u,tensor:t},B=ut=>typeof ut=="string"?ut:`${ut}u`,R={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},z=o?"uniforms.":"",ne=`${z}${e}_shape`,J=`${z}${e}_strides`,W="";for(let ut=0;ut ${k.indices} { + var indices: ${k.indices}; + var current = offset; + ${W} + return indices; + }`,he=ut=>(R.offsetToIndices=!0,a<2?ut:`o2i_${e}(${ut})`),be=[];if(a>=2)for(let ut=a-1;ut>=0;ut--)be.push(`${Tt(J,ut,a)} * (indices[${ut}])`);let Be=a<2?"":` + fn i2o_${e}(indices: ${k.indices}) -> u32 { + return ${be.join("+")}; + }`,Ie=ut=>(R.indicesToOffset=!0,a<2?ut:`i2o_${e}(${ut})`),nt=(...ut)=>a===0?"0u":`${k.indices}(${ut.map(B).join(",")})`,dt=(ut,xt)=>a<2?`${ut}`:`${Tt(ut,xt,a)}`,Et=(ut,xt,hs)=>a<2?`${ut}=${hs};`:`${Tt(ut,xt,a)}=${hs};`,zt={},It=(ut,xt)=>{R.broadcastedIndicesToOffset=!0;let hs=`${xt.name}broadcastedIndicesTo${e}Offset`;if(hs in zt)return`${hs}(${ut})`;let vs=[];for(let xs=a-1;xs>=0;xs--){let xn=xt.indicesGet("outputIndices",xs+xt.rank-a);vs.push(`${dt(J,xs)} * (${xn} % ${dt(ne,xs)})`)}return zt[hs]=`fn ${hs}(outputIndices: ${xt.type.indices}) -> u32 { + return ${vs.length>0?vs.join("+"):"0u"}; + }`,`${hs}(${ut})`},ht=(ut,xt)=>(()=>{if(k.storage===k.value)return`${e}[${ut}]=${xt};`;if(k.storage==="vec2"&&k.value==="i32")return`${e}[${ut}]=vec2(u32(${xt}), select(0u, 0xFFFFFFFFu, ${xt} < 0));`;if(k.storage==="vec2"&&k.value==="u32")return`${e}[${ut}]=vec2(u32(${xt}), 0u);`;if(k.storage==="u32"&&k.value==="vec4")return`${e}[${ut}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${xt}));`;throw new Error(`not supported combination of storage type ${k.storage} and value type ${k.value} yet`)})(),Jt=ut=>(()=>{if(k.storage===k.value)return`${e}[${ut}]`;if(k.storage==="vec2"&&k.value==="i32")return`i32(${e}[${ut}].x)`;if(k.storage==="vec2"&&k.value==="u32")return`u32(${e}[${ut}].x)`;if(k.storage==="u32"&&k.value==="vec4")return`vec4(bool(${e}[${ut}] & 0xFFu), bool(${e}[${ut}] & 0xFF00u), bool(${e}[${ut}] & 0xFF0000u), bool(${e}[${ut}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${k.storage} and value type ${k.value} yet`)})(),Vt=a<2?"":` + fn get_${e}ByIndices(indices: ${k.indices}) -> ${C} { + return ${Jt(`i2o_${e}(indices)`)}; + }`,St=a<2?"":(()=>{let ut=c.map(hs=>`d${hs}: u32`).join(", "),xt=c.map(hs=>`d${hs}`).join(", ");return` + fn get_${e}(${ut}) -> ${C} { + return get_${e}ByIndices(${nt(xt)}); + }`})(),ts=(...ut)=>{if(ut.length!==a)throw new Error(`indices length must be ${a}`);let xt=ut.map(B).join(",");return a===0?Jt("0u"):a===1?Jt(xt[0]):(R.get=!0,R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}(${xt})`)},Xt=ut=>a<2?Jt(ut):(R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}ByIndices(${ut})`),Ut=a<2?"":` + fn set_${e}ByIndices(indices: ${k.indices}, value: ${C}) { + ${ht(`i2o_${e}(indices)`,"value")} + }`,$s=a<2?"":(()=>{let ut=c.map(hs=>`d${hs}: u32`).join(", "),xt=c.map(hs=>`d${hs}`).join(", ");return` + fn set_${e}(${ut}, value: ${C}) { + set_${e}ByIndices(${nt(xt)}, value); + }`})();return{impl:()=>{let ut=[],xt=!1;return R.offsetToIndices&&(ut.push(ue),xt=!0),R.indicesToOffset&&(ut.push(Be),xt=!0),R.broadcastedIndicesToOffset&&(Object.values(zt).forEach(hs=>ut.push(hs)),xt=!0),R.set&&(ut.push($s),xt=!0),R.setByIndices&&(ut.push(Ut),xt=!0),R.get&&(ut.push(St),xt=!0),R.getByIndices&&(ut.push(Vt),xt=!0),!o&&xt&&ut.unshift(`const ${ne} = ${k.indices}(${s.join(",")});`,`const ${J} = ${k.indices}(${De.computeStrides(s).join(",")});`),ut.join(` +`)},type:k,offsetToIndices:he,indicesToOffset:Ie,broadcastedIndicesToOffset:It,indices:nt,indicesGet:dt,indicesSet:Et,set:(...ut)=>{if(ut.length!==a+1)throw new Error(`indices length must be ${a}`);let xt=ut[a];if(typeof xt!="string")throw new Error("value must be string");let hs=ut.slice(0,a).map(B).join(",");return a===0?ht("0u",xt):a===1?ht(hs[0],xt):(R.set=!0,R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}(${hs}, ${xt})`)},setByOffset:ht,setByIndices:(ut,xt)=>a<2?ht(ut,xt):(R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}ByIndices(${ut}, ${xt});`),get:ts,getByOffset:Jt,getByIndices:Xt,usage:n,name:e,strides:J,shape:ne,rank:a}},He=(e,t,s,n=1)=>Yr(e,t,s,"input",n),Ct=(e,t,s,n=1)=>Yr(e,t,s,"output",n),Ea=(e,t,s)=>Yr(e,t,s,"atomicOutput",1),Ii=(e,t,s,n=1)=>Yr(e,t,s,"internal",n),Ca=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=sr){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=i?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,a=i?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) + fn main(${o}) { + ${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 i=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${i}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},ka=(e,t)=>new Ca(e,t)}),Sa,Fi,Oi,$a,Aa,Di,cr,Ia,Li,jr=y(()=>{Ot(),$t(),is(),qt(),Sa=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Fi=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Oi=(e,t)=>De.sortBasedOnPerm(e,Fi(e.length,t)),$a=(e,t,s,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`;for(let o=0;o{let s=[],n=[];for(let i=0;i{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,i=Fi(n,t),o=Oi(e.dims,i),a=e.dims,c=o,p=n<2||Di(i,e.dims),h;if(p)return h=R=>{let z=He("input",s,a,4),ne=Ct("output",s,c,4);return` + ${R.registerUniform("output_size","u32").declareVariables(z,ne)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let R=De.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(R/4)}]}},getShaderSource:h};let{newShape:C,newPerm:u}=Aa(e.dims,i),k=De.areEqual(u,[2,3,1]),B=De.areEqual(u,[3,1,2]);if(C.length===2||k||B){a=k?[C[0],C[1]*C[2]]:B?[C[0]*C[1],C[2]]:C,c=[a[1],a[0]];let R=16;return h=z=>{let ne=He("a",s,a.length),J=Ct("output",s,c.length);return` + ${z.registerUniform("output_size","u32").declareVariables(ne,J)} + var tile : array, ${R}>; + ${z.mainStart([R,R,1])} + let stride = (uniforms.output_shape[1] - 1) / ${R} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${R}u + local_id.x; + let input_row = workgroup_id_x * ${R}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${ne.getByIndices(`${ne.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${R}u + local_id.x; + let output_row = workgroup_id_y * ${R}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${J.setByIndices(`${J.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let z=De.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c[1]/R),y:Math.ceil(c[0]/R)},programUniforms:[{type:12,data:z},...Mt(a,c)]}},getShaderSource:h}}return h=R=>{let z=He("a",s,a.length),ne=Ct("output",s,c.length);return` + ${R.registerUniform("output_size","u32").declareVariables(z,ne)} + + ${$a(i,n,z,ne)} + + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${ne.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${ne.setByOffset("global_idx",z.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let R=De.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...Mt(a,c)]}},getShaderSource:h}},Ia=(e,t)=>{Sa(e.inputs,t.perm),e.compute(cr(e.inputs[0],t.perm))},Li=e=>jt({perm:e.perm})}),ei,Fa,Oa,Da,La,za,Ba,Ra,zi,Na,pr,Jr,ja,uc,Va,dc,Ua,Bi,Wa,Ga,Ka,cc=y(()=>{Ot(),$t(),qt(),ri(),jr(),ei={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"},Fa={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"},Oa={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 o=0;oe[o]);return[s,i]},Ba=(e,t)=>{let s=e.length+t.length,n=[],i=0;for(let o=0;o{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,i,o,a)=>{let c=s[0].dims,p=De.size(o),h=De.size(a),C=He("_A",s[0].dataType,c),u=Ct("output",i,o),k=64;p===1&&(k=256);let B=` + var aBestValues : array; + `,R=z=>` + ${z.registerUniform("reduceSize","u32").declareVariables(C,u)} + ${B} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${z.mainStart(k)} + + let outputIndex = global_idx / ${k}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Oa[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${k}) { + let candidate = f32(${C.getByOffset("offset + k")}); + bestValue = ${ei[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${k}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 = ${Fa[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};${k}`,inputDependencies:["type"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},pr=(e,t,s,n)=>{let i=e.inputs.length===1?s:Ri(e.inputs,s),o=i.axes;o.length===0&&!i.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((B,R)=>R));let a=De.normalizeAxes(o,e.inputs[0].dims.length),c=a,p=e.inputs[0],h=zi(c,e.inputs[0].dims.length);h.length>0&&(p=e.compute(cr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],c=La(c.length,p.dims.length));let[C,u]=za(p.dims,c),k=C;i.keepDims&&(k=Ba(C,a)),e.compute(Na(t,i.cacheKey,[p],n,e.inputs[0].dataType,k,u),{inputs:[p]})},Jr=(e,t)=>{pr(e,"ReduceMeanShared",t,"mean")},ja=(e,t)=>{pr(e,"ReduceL1Shared",t,"l1")},uc=(e,t)=>{pr(e,"ReduceL2Shared",t,"l2")},Va=(e,t)=>{pr(e,"ReduceLogSumExpShared",t,"logSumExp")},dc=(e,t)=>{pr(e,"ReduceMaxShared",t,"max")},Ua=(e,t)=>{pr(e,"ReduceMinShared",t,"min")},Bi=(e,t)=>{pr(e,"ReduceProdShared",t,"prod")},Wa=(e,t)=>{pr(e,"ReduceSumShared",t,"sum")},Ga=(e,t)=>{pr(e,"ReduceSumSquareShared",t,"sumSquare")},Ka=(e,t)=>{pr(e,"ReduceLogSumShared",t,"logSum")}}),gr,ti,si,Ri,wr,Ni,Ha,qa,ji,Qa,Xa,Vi,Ya,Ja,Ui,yr,Za,Wi,el,tl,Gi,sl,rl,Ki,nl,il,ri=y(()=>{Ot(),$t(),is(),qt(),cc(),gr=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.")},ti=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],si=(e,t,s,n,i,o,a=!1,c=!1)=>{let p=[],h=s[0].dims,C=h.length,u=De.normalizeAxes(i,C),k=!c&&u.length===0;h.forEach((z,ne)=>{k||u.indexOf(ne)>=0?a&&p.push(1):p.push(z)});let B=p.length,R=De.size(p);return{name:e,shaderCache:t,getShaderSource:z=>{let ne=[],J=He("_A",s[0].dataType,C),W=Ct("output",o,B),ue=n(J,W,u),he=ue[2];for(let be=0,Be=0;be=0?(a&&Be++,he=`for(var j${be}: u32 = 0; j${be} < ${h[be]}; j${be}++) { + ${ue[2].includes("last_index")?`let last_index = j${be};`:""} + ${J.indicesSet("input_indices",be,`j${be}`)} + ${he} + }`):(ne.push(`${J.indicesSet("input_indices",be,W.indicesGet("output_indices",Be))};`),Be++);return` + + ${z.registerUniform("output_size","u32").declareVariables(J,W)} + + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${J.type.indices}; + let output_indices = ${W.offsetToIndices("global_idx")}; + + ${ne.join(` +`)} + ${ue[0]} // init ops for reduce max/min + ${ue[1]} + ${he} + ${ue[3]} + ${ue.length===4?W.setByOffset("global_idx","value"):ue.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...Mt(h,p)]})}},Ri=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),jt({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},wr=(e,t,s,n)=>{let i=e.inputs,o=i.length===1?s:Ri(i,s);e.compute(si(t,{hint:o.cacheKey,inputDependencies:["rank"]},[i[0]],o.noopWithEmptyAxes&&o.axes.length===0?ti:n,o.axes,i[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Ni=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Ha=(e,t)=>{gr(e.inputs),wr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},qa=(e,t)=>{gr(e.inputs),wr(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);"])},ji=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},Qa=(e,t)=>{gr(e.inputs),wr(e,"ReduceMax",t,(s,n,i)=>{let o=[];for(let a=0;a=0||i.length===0)&&o.push(s.indicesSet("input_indices",a,0));return[`${o.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Xa=(e,t)=>{gr(e.inputs),wr(e,"ReduceMean",t,(s,n,i)=>{let o=1;for(let a=0;a=0||i.length===0)&&(o*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${o});`]})},Vi=(e,t)=>{gr(e.inputs),wr(e,"ReduceMin",t,(s,n,i)=>{let o=[];for(let a=0;a=0||i.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Ya=(e,t)=>{gr(e.inputs),wr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Ja=(e,t)=>{gr(e.inputs),wr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Ui=(e,t)=>{gr(e.inputs),wr(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;`,""])},yr=(e,t,s)=>{if(t.length===0)return s;let n=1,i=1;for(let o=0;o1024},Za=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xa(e,t):Jr(e,t)},Wi=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ha(e,t):ja(e,t)},el=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qa(e,t):uc(e,t)},tl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ji(e,t):Va(e,t)},Gi=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Qa(e,t):dc(e,t)},sl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vi(e,t):Ua(e,t)},rl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ya(e,t):Bi(e,t)},Ki=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):Wa(e,t)},nl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ui(e,t):Ga(e,t)},il=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ni(e,t):Ka(e,t)}}),Hi,ol,qi,Qi,pc=y(()=>{Ot(),is(),ri(),Hi=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.")},ol=(e,t)=>{Hi(e.inputs);let s=(n,i,o)=>{let a=[];for(let c=0;c=0||o.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); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(si("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},qi=(e,t)=>{Hi(e.inputs);let s=(n,i,o)=>{let a=[];for(let c=0;c=0||o.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); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(si("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Qi=e=>jt(e)}),Xi,ni,al,Yi,ll,zn,Ji,ul,Zi=y(()=>{Ot(),$t(),ce(),qt(),Xi=(e,t)=>{let s=e[0],n=e[1],i=e[2],o=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],C=s.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==C)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=i.dims[0]/3,k=u,B=k;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ue of t.qkvHiddenSizes)if(ue%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=t.qkvHiddenSizes[0],k=t.qkvHiddenSizes[1],B=t.qkvHiddenSizes[2]}let R=h;if(u!==k)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==u+k+B)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let z=0;if(a){if(k!==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]!==k/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(z=a.dims[3])}let ne=R+z,J=-1,W=0;if(o)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]!==ne)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:z,kvSequenceLength:R,totalSequenceLength:ne,maxSequenceLength:J,inputHiddenSize:C,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:W,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ni=(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,i,o,a,c)=>{let p=Gt(a?1:o),h=64,C=o/p;C{let W=Ct("x",e.dataType,e.dims,p),ue=[W],he=a?He("seq_lens",a.dataType,a.dims):void 0;he&&ue.push(he);let be=c?He("total_sequence_length_input",c.dataType,c.dims):void 0;be&&ue.push(be);let Be=Cs(e.dataType),Ie=[{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; + ${J.registerUniforms(Ie).declareVariables(...ue)} + ${J.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; + ${ni(he,be,!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 = ${R}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${R}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(p){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${h}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${R}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${R}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${h}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${W.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 = ${R}(x[offset + i]); + x[offset + i] = ${W.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] = ${W.type.value}(${Be}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${B};${p}`,inputDependencies:z},getShaderSource:ne,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(o/h),y:i,z:t*s},programUniforms:k})}},Yi=(e,t,s,n,i,o,a,c,p)=>{let h=a+o.kvSequenceLength,C=[o.batchSize,o.numHeads,o.sequenceLength,h],u=e>1&&n,k=o.kvNumHeads?o.kvNumHeads:o.numHeads,B=u?[o.batchSize,k,h,o.headSize]:void 0,R=o.nReps?o.nReps:1,z=o.scale===0?1/Math.sqrt(o.headSize):o.scale,ne=Gt(o.headSize),J=o.headSize/ne,W=12,ue={x:Math.ceil(h/W),y:Math.ceil(o.sequenceLength/W),z:o.batchSize*o.numHeads},he=[{type:12,data:o.sequenceLength},{type:12,data:J},{type:12,data:h},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:z},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:R}],be=u&&n&&De.size(n.dims)>0,Be=["type","type"];be&&Be.push("type"),i&&Be.push("type"),c&&Be.push("type"),p&&Be.push("type");let Ie=[{dims:C,dataType:t.dataType,gpuDataType:0}];u&&Ie.push({dims:B,dataType:t.dataType,gpuDataType:0});let nt=dt=>{let Et=He("q",t.dataType,t.dims,ne),zt=He("key",s.dataType,s.dims,ne),It=[Et,zt];if(be){let Ut=He("past_key",n.dataType,n.dims,ne);It.push(Ut)}i&&It.push(He("attention_bias",i.dataType,i.dims));let ht=c?He("seq_lens",c.dataType,c.dims):void 0;ht&&It.push(ht);let Jt=p?He("total_sequence_length_input",p.dataType,p.dims):void 0;Jt&&It.push(Jt);let Vt=Ct("output",t.dataType,C),St=[Vt];u&&St.push(Ct("present_key",t.dataType,B,ne));let ts=Cs(1,ne),Xt=[{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 = ${W}u; + + var tileQ: array<${Et.type.storage}, ${W*W}>; + var tileK: array<${Et.type.storage}, ${W*W}>; + ${dt.registerUniforms(Xt).declareVariables(...It,...St)} + ${dt.mainStart([W,W,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${R===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${R===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${ni(ht,Jt,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${be&&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 = ${ts}(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; + ${be&&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 += ${ts}(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(ne){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: ${ne}`)}})()}; + output[outputIdx] = ${Vt.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${ne};${i!==void 0};${n!==void 0};${e}`,inputDependencies:Be},getRunData:()=>({outputs:Ie,dispatchGroup:ue,programUniforms:he}),getShaderSource:nt}},ll=(e,t,s,n,i,o,a=void 0,c=void 0)=>{let p=o+i.kvSequenceLength,h=i.nReps?i.nReps:1,C=i.vHiddenSize*h,u=e>1&&n,k=i.kvNumHeads?i.kvNumHeads:i.numHeads,B=u?[i.batchSize,k,p,i.headSize]:void 0,R=[i.batchSize,i.sequenceLength,C],z=12,ne={x:Math.ceil(i.vHeadSize/z),y:Math.ceil(i.sequenceLength/z),z:i.batchSize*i.numHeads},J=[{type:12,data:i.sequenceLength},{type:12,data:p},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:C},{type:12,data:o},{type:12,data:i.kvSequenceLength},{type:12,data:h}],W=u&&n&&De.size(n.dims)>0,ue=["type","type"];W&&ue.push("type"),a&&ue.push("type"),c&&ue.push("type");let he=[{dims:R,dataType:t.dataType,gpuDataType:0}];u&&he.push({dims:B,dataType:t.dataType,gpuDataType:0});let be=Be=>{let Ie=He("probs",t.dataType,t.dims),nt=He("v",s.dataType,s.dims),dt=[Ie,nt];W&&dt.push(He("past_value",n.dataType,n.dims));let Et=a?He("seq_lens",a.dataType,a.dims):void 0;a&&dt.push(Et);let zt=c?He("total_sequence_length_input",c.dataType,c.dims):void 0;c&&dt.push(zt);let It=[Ct("output",t.dataType,R)];u&&It.push(Ct("present_value",t.dataType,B));let ht=[{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 = ${z}u; + var tileQ: array<${Ie.type.value}, ${z*z}>; + var tileV: array<${Ie.type.value}, ${z*z}>; + ${Be.registerUniforms(ht).declareVariables(...dt,...It)} + ${Be.mainStart([z,z,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; + ${ni(Et,zt,!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 + ${W&&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 = ${Ie.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; + ${W&&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:ue},getRunData:()=>({outputs:he,dispatchGroup:ne,programUniforms:J}),getShaderSource:be}},zn=(e,t,s,n,i,o,a,c,p,h,C=void 0,u=void 0)=>{let k=Math.min(e.outputCount,1+(a?1:0)+(c?1:0)),B=k>1?h.pastSequenceLength:0,R=B+h.kvSequenceLength,z=p&&De.size(p.dims)>0?p:void 0,ne=[t,s];k>1&&a&&De.size(a.dims)>0&&ne.push(a),z&&ne.push(z),C&&ne.push(C),u&&ne.push(u);let J=e.compute(Yi(k,t,s,a,z,h,B,C,u),{inputs:ne,outputs:k>1?[-1,1]:[-1]})[0];e.compute(al(J,h.batchSize,h.numHeads,B,h.sequenceLength,R,C,u),{inputs:C&&u?[J,C,u]:[J],outputs:[]});let W=[J,n];k>1&&c&&De.size(c.dims)>0&&W.push(c),C&&W.push(C),u&&W.push(u),e.compute(ll(k,J,n,c,h,B,C,u),{inputs:W,outputs:k>1?[0,2]:[0]})},Ji=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,o=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:i},{type:12,data:o},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],C=u=>{let k=Ct("output_q",p[0].dataType,s),B=Ct("output_k",p[0].dataType,s),R=Ct("output_v",p[0].dataType,s),z=He("input",p[0].dataType,p[0].dims),ne=He("weight",p[1].dataType,p[1].dims),J=He("bias",p[2].dataType,p[2].dims),W=z.type.storage,ue=[{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<${W}, ${a*a}>; + var tileWeightQ: array<${W}, ${a*a}>; + var tileWeightK: array<${W}, ${a*a}>; + var tileWeightV: array<${W}, ${a*a}>; + ${u.registerUniforms(ue).declareVariables(z,ne,J,k,B,R)} + ${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 = ${W}(0); + var valueK = ${W}(0); + var valueV = ${W}(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:C},{inputs:p,outputs:[-1,-1,-1]})},ul=(e,t)=>{let s=Xi(e.inputs,t),[n,i,o]=Ji(e,s);return zn(e,n,i,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),eo,dl,cl,to,hc=y(()=>{We(),Ot(),$t(),is(),qt(),eo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,i,o)=>{let a=i.length;if(a!==n.length)throw new Error(`${o}: num dimensions != ${a}`);i.forEach((c,p)=>{if(c!==n[p])throw new Error(`${o}: 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:i}=t,o=e[0].dims,a=n?Gt(o[o.length-1]):1,c=i==="NHWC"&&o.length>1?a:1,p=De.size(o)/a,h=n,C=h?o.length:o,u=He("x",e[0].dataType,e[0].dims,a),k=He("scale",e[1].dataType,e[1].dims,c),B=He("bias",e[2].dataType,e[2].dims,c),R=He("inputMean",e[3].dataType,e[3].dims,c),z=He("inputVar",e[4].dataType,e[4].dims,c),ne=Ct("y",e[0].dataType,C,a),J=()=>{let ue="";if(n)ue=`let cOffset = ${o.length===1?"0u":i==="NHWC"?`outputIndices[${o.length-1}] / ${a}`:"outputIndices[1]"};`;else if(i==="NCHW")ue=` + ${ne.indicesSet("outputIndices","0","0")} + let cOffset = ${ne.indicesToOffset("outputIndices")};`;else{ue=`var cIndices = ${k.type.indices}(0); + cIndices[0] = outputIndices[${o.length-1}];`;for(let he=1;he` + const epsilon = ${s}; + ${ue.registerUniform("outputSize","u32").declareVariables(u,k,B,R,z,ne)} + ${ue.mainStart()} + ${ue.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${ne.offsetToIndices(`global_idx * ${a}`)}; + ${J()} + let scale = ${k.getByOffset("cOffset")}; + let bias = ${B.getByOffset("cOffset")}; + let inputMean = ${R.getByOffset("cOffset")}; + let inputVar = ${z.getByOffset("cOffset")}; + let x = ${u.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${ne.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:W,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Mt(o)]:[{type:12,data:p}]})}},cl=e=>jt(e),to=(e,t)=>{let{inputs:s,outputCount:n}=e,i=cl({...t,outputCount:n});if(F.webgpu.validateInputContent&&eo(s,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(dl(s,i))}}),pl,so,hl,mc=y(()=>{$t(),qt(),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")},so=e=>{let t=e[0].dims,s=e[0].dims[2],n=De.size(t)/4,i=e[0].dataType,o=He("input",i,t,4),a=He("bias",i,[s],4),c=He("residual",i,t,4),p=Ct("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` + const channels = ${s}u / 4; + ${h.declareVariables(o,a,c,p)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${o.getByOffset("global_idx")} + + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")}; + ${p.setByOffset("global_idx","value")} + }`}},hl=e=>{pl(e.inputs),e.compute(so(e.inputs))}}),ro,ls,ml,no,fl,_l,io,gl,wl,oo,yl,Ml,bl,vl,ao,xl,Bn,lo,ii,Tl,uo,Pl,El,co,Cl,kl,po,Sl,$l,ho,Al,Il,mo,Fl,Ol,fo,Dl,oi,_o,Ll,zl,Bl,go,Rl,Nl,wo=y(()=>{Ot(),$t(),is(),qt(),ro=(e,t,s,n,i,o,a)=>{let c=Math.ceil(t/4),p="";typeof i=="string"?p=`${i}(a)`:p=i("a");let h=He("inputData",s,[c],4),C=Ct("outputData",n,[c],4),u=[{name:"vec_size",type:"u32"}];return a&&u.push(...a),` + ${e.registerUniforms(u).declareVariables(h,C)} + + ${o??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${h.getByOffset("global_idx")}; + ${C.setByOffset("global_idx",p)} + }`},ls=(e,t,s,n,i,o=e.dataType,a,c)=>{let p=[{type:12,data:Math.ceil(De.size(e.dims)/4)}];return a&&p.push(...a),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:h=>ro(h,De.size(e.dims),e.dataType,o,s,n,c),getRunData:h=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(De.size(h[0].dims)/64/4)},programUniforms:p})}},ml=e=>{e.compute(ls(e.inputs[0],"Abs","abs"))},no=e=>{e.compute(ls(e.inputs[0],"Acos","acos"))},fl=e=>{e.compute(ls(e.inputs[0],"Acosh","acosh"))},_l=e=>{e.compute(ls(e.inputs[0],"Asin","asin"))},io=e=>{e.compute(ls(e.inputs[0],"Asinh","asinh"))},gl=e=>{e.compute(ls(e.inputs[0],"Atan","atan"))},wl=e=>{e.compute(ls(e.inputs[0],"Atanh","atanh"))},oo=e=>jt(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(ls(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},Ml=e=>{let t,s,n=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return jt({min:t,max:s})},bl=(e,t)=>{let s=t||Ml(e.inputs),n=Cs(e.inputs[0].dataType);e.compute(ls(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},vl=e=>{e.compute(ls(e.inputs[0],"Ceil","ceil"))},ao=e=>{e.compute(ls(e.inputs[0],"Cos","cos"))},xl=e=>{e.compute(ls(e.inputs[0],"Cosh","cosh"))},Bn=e=>jt(e),lo=(e,t)=>{let s=Cs(e.inputs[0].dataType);e.compute(ls(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))},ii=(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)); +}`,Tl=e=>{let t=Cs(e.inputs[0].dataType);e.compute(ls(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ii(t)))},uo=e=>{e.compute(ls(e.inputs[0],"Exp","exp"))},Pl=e=>{e.compute(ls(e.inputs[0],"Floor","floor"))},El=e=>{let t=Cs(e.inputs[0].dataType);e.compute(ls(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,ii(t)))},co=(e,t)=>{let s=Cs(e.inputs[0].dataType);e.compute(ls(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(ls(e.inputs[0],"Not",t=>`!${t}`))},kl=e=>{e.compute(ls(e.inputs[0],"Neg",t=>`-${t}`))},po=e=>{e.compute(ls(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Sl=e=>{let t=Cs(e.inputs[0].dataType);e.compute(ls(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},$l=e=>{e.compute(ls(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},ho=e=>jt(e),Al=(e,t)=>{let s=Cs(e.inputs[0].dataType);e.compute(ls(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(ls(e.inputs[0],"Sin","sin"))},mo=e=>{e.compute(ls(e.inputs[0],"Sinh","sinh"))},Fl=e=>{e.compute(ls(e.inputs[0],"Sqrt","sqrt"))},Ol=e=>{e.compute(ls(e.inputs[0],"Tan","tan"))},fo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Dl=e=>{e.compute(ls(e.inputs[0],"Tanh",fo))},oi=(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 ${fo("v")}; +} +`,_o=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ll=e=>{let t=Cs(e.inputs[0].dataType);e.compute(ls(e.inputs[0],"FastGelu",_o,oi(t),void 0,e.inputs[0].dataType))},zl=(e,t)=>{let s=Cs(e.inputs[0].dataType);return e.compute(ls(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(ls(e.inputs[0],"Log","log"))},go=(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=Cs(e.inputs[0].dataType);e.compute(ls(e.inputs[0],"QuickGelu",Rl,go(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),jl,yo,Vl,fc=y(()=>{$t(),qt(),wo(),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")},yo=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=He("input",e[0].dataType,e[0].dims,4),n=He("bias",e[0].dataType,[e[0].dims[2]],4),i=Ct("output",e[0].dataType,t,4),o=De.size(t)/4,a=ds(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:c=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${c.declareVariables(s,n,i)} + + ${ii(a)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes(o)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Vl=e=>{jl(e.inputs),e.compute(yo(e.inputs))}}),Ul,Wl,hr,Gl,Kl,Mo,Hl,ql,bo,Ql,Xl,vo,Yl,_c=y(()=>{Ot(),$t(),qt(),Ul=(e,t,s,n,i,o,a,c,p,h,C,u)=>{let k,B;typeof c=="string"?k=B=(W,ue)=>`${c}((${W}),(${ue}))`:typeof c=="function"?k=B=c:(k=c.scalar,B=c.vector);let R=Ct("outputData",C,n.length,4),z=He("aData",p,t.length,4),ne=He("bData",h,s.length,4),J;if(i)if(o){let W=De.size(t)===1,ue=De.size(s)===1,he=t.length>0&&t[t.length-1]%4===0,be=s.length>0&&s[s.length-1]%4===0;W||ue?J=R.setByOffset("global_idx",B(W?`${z.type.value}(${z.getByOffset("0")}.x)`:z.getByOffset("global_idx"),ue?`${ne.type.value}(${ne.getByOffset("0")}.x)`:ne.getByOffset("global_idx"))):J=` + let outputIndices = ${R.offsetToIndices("global_idx * 4u")}; + let offsetA = ${z.broadcastedIndicesToOffset("outputIndices",R)}; + let offsetB = ${ne.broadcastedIndicesToOffset("outputIndices",R)}; + ${R.setByOffset("global_idx",B(a||he?z.getByOffset("offsetA / 4u"):`${z.type.value}(${z.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||be?ne.getByOffset("offsetB / 4u"):`${ne.type.value}(${ne.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else J=R.setByOffset("global_idx",B(z.getByOffset("global_idx"),ne.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let W=(ue,he,be="")=>{let Be=`aData[indexA${he}][componentA${he}]`,Ie=`bData[indexB${he}][componentB${he}]`;return` + let outputIndices${he} = ${R.offsetToIndices(`global_idx * 4u + ${he}u`)}; + let offsetA${he} = ${z.broadcastedIndicesToOffset(`outputIndices${he}`,R)}; + let offsetB${he} = ${ne.broadcastedIndicesToOffset(`outputIndices${he}`,R)}; + let indexA${he} = offsetA${he} / 4u; + let indexB${he} = offsetB${he} / 4u; + let componentA${he} = offsetA${he} % 4u; + let componentB${he} = offsetB${he} % 4u; + ${ue}[${he}] = ${be}(${k(Be,Ie)}); + `};C===9?J=` + var data = vec4(0); + ${W("data",0,"u32")} + ${W("data",1,"u32")} + ${W("data",2,"u32")} + ${W("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:J=` + ${W("outputData[global_idx]",0)} + ${W("outputData[global_idx]",1)} + ${W("outputData[global_idx]",2)} + ${W("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(z,ne,R)} + + ${u??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${J} + }`},Wl=(e,t,s,n,i,o,a=s.dataType)=>{let c=s.dims.map(z=>Number(z)??1),p=n.dims.map(z=>Number(z)??1),h=!De.areEqual(c,p),C=c,u=De.size(c),k=!1,B=!1,R=[h];if(h){let z=Js.calcShape(c,p,!1);if(!z)throw new Error("Can't perform binary op on the given tensors");C=z.slice(),u=De.size(C);let ne=De.size(c)===1,J=De.size(p)===1,W=c.length>0&&c[c.length-1]%4===0,ue=p.length>0&&p[p.length-1]%4===0;R.push(ne),R.push(J),R.push(W),R.push(ue);let he=1;for(let be=1;bez.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:z=>Ul(z,c,p,C,k,h,B,i,s.dataType,n.dataType,a,o),getRunData:()=>({outputs:[{dims:C,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(De.size(C)/4)},...Mt(c,p,C)]})}},hr=(e,t,s,n,i,o)=>{e.compute(Wl(t,i??"",e.inputs[0],e.inputs[1],s,n,o))},Gl=e=>{hr(e,"Add",(t,s)=>`${t}+${s}`)},Kl=e=>{hr(e,"Div",(t,s)=>`${t}/${s}`)},Mo=e=>{hr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},Hl=e=>{hr(e,"Mul",(t,s)=>`${t}*${s}`)},ql=e=>{let t=He("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;hr(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)); + } + `)},bo=e=>{hr(e,"Sub",(t,s)=>`${t}-${s}`)},Ql=e=>{hr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},Xl=e=>{hr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},vo=e=>{hr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},Yl=e=>{hr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),xo,Jl,Zl,ai,eu,tu,su=y(()=>{Ot(),$t(),is(),qt(),xo=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],i=n.dataType,o=n.dims.length;e.forEach((a,c)=>{if(c!==s){if(a.dataType!==i)throw new Error("input tensors should be one type");if(a.dims.length!==o)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 i=0;i{let i=De.size(s),o=new Array(e.length),a=new Array(e.length),c=0,p=[],h=[],C=[{type:12,data:i}];for(let z=0;z`uniforms.sizeInConcatAxis${z}`).join(","),R=z=>` + + ${(()=>{z.registerUniform("outputSize","u32");for(let ne=0;ne(${B}); + ${k} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Zl(a,u)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:C}),getShaderSource:R}},eu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=De.normalizeAxis(t.axis,n.length);xo(s,i);let o=n.slice();o[i]=s.reduce((c,p)=>c+(p.dims.length>i?p.dims[i]:0),0);let a=s.filter(c=>De.size(c.dims)>0);e.compute(ai(a,i,o,s[0].dataType),{inputs:a})},tu=e=>jt({axis:e.axis})}),Vr,Zr,Ur,To,en=y(()=>{Ot(),$t(),Vr=(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}`)}},Zr=(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})},Ur=(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"})},To=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||[Es,Hs];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}}}),qs,Po,Eo=y(()=>{qs=(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.`)}},Po=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),ru,gc=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)); +} +`}),wn,Co,ko=y(()=>{Ot(),$t(),qt(),en(),wn=(e,t,s,n,i)=>{let o=n-s;return` + ${Array.from({length:s}).map((a,c)=>` + if (${Tt(t.shape,c,t.rank)} != 1) { + ${t.indicesSet(e,c,Tt(i,c+o,n))} + } else { + ${t.indicesSet(e,c,0)} + }`).join("")} +`},Co=(e,t,s,n,i=!1,o)=>{let a=e[0].dims,c=e[1].dims,p=a[a.length-2],h=c[c.length-1],C=a[a.length-1],u=Gt(h),k=Gt(C),B=Gt(p),R=De.size(s)/u/B,z=e.length>2,ne=n?n.slice(0,-2):s.slice(0,-2),J=[De.size(ne),p,h],W=[{type:12,data:R},{type:12,data:p},{type:12,data:h},{type:12,data:C}];Zr(t,W),W.push(...Mt(ne,a,c)),z&&W.push(...Mt(e[2].dims)),W.push(...Mt(J));let ue=he=>{let be=Ii("batch_dims",e[0].dataType,ne.length),Be=He("a",e[0].dataType,a.length,k),Ie=He("b",e[1].dataType,c.length,u),nt=Ct("output",e[0].dataType,J.length,u),dt=ds(nt.type.tensor),Et=Vr(t,nt.type.value,dt),zt=[Be,Ie],It="";if(z){let Vt=i?u:1;zt.push(He("bias",e[2].dataType,e[2].dims.length,Vt)),It=`${i?`value += bias[col / ${Vt}];`:`value += ${nt.type.value}(bias[row + i]);`}`}let ht=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ur(t,ht);let Jt=()=>{let Vt=`var a_data: ${Be.type.value};`;for(let St=0;St; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${k}) { + ${Jt()} + } + for (var i = 0u; i < ${B}u; i++) { + var value = values[i]; + ${It} + ${Et} + let cur_indices = ${nt.type.indices}(batch, row + i, col); + let offset = ${nt.indicesToOffset("cur_indices")}; + ${nt.setByOffset(`offset / ${u}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${u};${k};${B};${i}`,inputDependencies:z?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:W}),getShaderSource:ue}}}),So,nu,$o,li,iu,Ao,Io,ui,Fo=y(()=>{Ot(),$t(),qt(),en(),ko(),Eo(),So=(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];"} + }`,$o=(e,t,s="f32",n,i=!1,o=32,a=!1,c=32)=>{let p=t[1]*e[1],h=t[0]*e[0],C=i?p:o,u=i?o:p,k=C/t[0],B=o/t[1];if(!((i&&k===4&&e[1]===4||!i&&(k===3||k===4))&&C%t[0]===0&&o%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${k} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${k} must be 3 or 4. + tileAWidth ${C} must be divisible by workgroupSize[0]${t[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${C/k}>, ${u}>; +var mm_Bsub: array, ${h/e[0]}>, ${o}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${k}; +const tileInner = ${o}; + +@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/o)}`:"(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; + ${So(i,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${k===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${nu(i,k)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},li=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${t?", batchIndices":""}); + `,iu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ao=(e,t,s="f32",n,i=!1,o=32,a=!1,c=32,p=!1)=>{let h=e[1]*t[1],C=e[0]*t[0],u=i?h:o,k=i?o:h;if(!(k%t[1]===0&&u%t[0]===0&&o%t[1]===0))throw new Error(`tileAHight ${k} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${o} must be divisible by workgroupSize[1]${t[1]}`);let B=k/t[1],R=u/t[0],z=o/t[1],ne=p?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${h}; + let globalColStart = i32(workgroupId.x) * ${C}; + + // 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 < ${k}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) { + ${li(i,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${C}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${h}; + +let tileRowA = i32(localId.y) * ${B}; +let tileColA = i32(localId.x) * ${R}; +let tileRowB = i32(localId.y) * ${z}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${li(i,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${z}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${iu(i)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${k}>; + var mm_Bsub : array, ${o}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${o}; + +@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/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${c}`:"0"}; + + var acc : array, rowPerThread>; + ${ne} + } +`},Io=(e,t,s,n,i=!1)=>{let[o,a,c,p]=n,h=ds(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${qs(e,h)} { + var value = ${qs(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${a.type.indices}; + ${wn("aIndices",a,a.rank-2,o.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: ${o.type.indices}) -> ${qs(e,h)} { + var value = ${qs(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${c.type.indices}; + ${wn("bIndices",c,c.rank-2,o.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: ${qs(e,h)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${i?"bias[colIn]":`${qs(e,h)}(bias[row])`};`:""} + ${s} + ${p.setByIndices("vec3(coords)","value")} + } + } + `},ui=(e,t,s,n,i=!1,o)=>{let a=e[0].dims,c=e[1].dims,p=a.slice(0,-2),h=c.slice(0,-2),C=n?n.slice(0,-2):s.slice(0,-2),u=De.size(C),k=a[a.length-2],B=a[a.length-1],R=c[c.length-1],z=B%4===0&&R%4===0,ne=k<=8?[4,1,1]:[4,4,1],J=[8,8,1],W=[Math.ceil(R/J[0]/ne[0]),Math.ceil(k/J[1]/ne[1]),Math.ceil(u/J[2]/ne[2])],ue=z?4:1,he=[...p,k,B/ue],be=he.length,Be=[...h,B,R/ue],Ie=Be.length,nt=[u,k,R/ue],dt=[{type:6,data:k},{type:6,data:R},{type:6,data:B}];Zr(t,dt),dt.push(...Mt(C,he,Be));let Et=["rank","rank"],zt=e.length>2;zt&&(dt.push(...Mt(e[2].dims)),Et.push("rank")),dt.push(...Mt(nt));let It=ht=>{let Jt=C.length,Vt=Ii("batchDims",e[0].dataType,Jt,1),St=ds(e[0].dataType),ts=He("a",e[0].dataType,be,ue),Xt=He("b",e[1].dataType,Ie,ue),Ut=Ct("result",e[0].dataType,nt.length,ue),$s=[ts,Xt];if(zt){let xs=i?ue:1;$s.push(He("bias",e[2].dataType,e[2].dims.length,xs))}let ut=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ur(t,ut);let xt=ds(Ut.type.tensor),hs=Vr(t,Ut.type.value,xt),vs=Io(ue,zt,hs,[Vt,ts,Xt,Ut],i);return` + ${ht.registerUniforms(ut).registerInternalVariables(Vt).declareVariables(...$s,Ut)} + ${vs} + ${z?$o(ne,J,St,Vt):Ao(ne,J,St,Vt)} + `};return{name:"MatMul",shaderCache:{hint:`${ne};${t.activation};${z};${i}`,inputDependencies:Et},getRunData:()=>({outputs:[{dims:o?o(s):s,dataType:e[0].dataType}],dispatchGroup:{x:W[0],y:W[1],z:W[2]},programUniforms:dt}),getShaderSource:It}}}),Oo,ou,wc=y(()=>{Ot(),Te(),qt(),en(),Eo(),gc(),Fo(),Oo=(e,t,s,n,i=!1,o,a=4,c=4,p=4,h="f32")=>{let C=dt=>{switch(dt){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 ${dt} is not supported.`)}},u=dt=>{switch(dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${dt} is not supported.`)}},k=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,B=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,R=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",z=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",ne=e?"row":"col",J=e?"col":"row",W=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${ne} / outWidth; + let outCol = ${ne} % outWidth; + + let WRow = ${J} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${J} / 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 = ${J} % inChannels; + var resData = ${qs(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 < ${R} && xCol >= 0 && xCol < ${z}) { + ${k} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${C(a)} + } + return resData;`,ue=e?t&&n?` + let col = colIn * ${a}; + ${W}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${W} + } + return ${qs(a,h)}(0.0);`:n&&s?` + let col = colIn * ${a}; + ${W}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${W} + } + return ${qs(a,h)}(0.0);`,he=e?n&&s?u(c):` + let col = colIn * ${c}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${u(c)} + } + return ${qs(c,h)}(0.0);`:` + let col = colIn * ${c}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${u(c)} + } + return ${qs(c,h)}(0.0);`,be=qs(p,h),Be=qs(e?a:c,h),Ie=qs(e?c:a,h),nt=Vr(o,be,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Be} { + ${e?ue:he} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ie} { + ${e?he:ue} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${be}) { + 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} + ${Po(i)} + ${nt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},ou=(e,t,s,n,i,o,a,c,p)=>{let h=t.format==="NHWC",C=h?e[0].dims[3]:e[0].dims[1],u=s[0],k=h?s[2]:s[3],B=h?s[1]:s[2],R=h?s[3]:s[1],z=h&&(C%4===0||C%3===0)&&R%4===0,ne=h?R:k*B,J=h?k*B:R,W=[8,8,1],ue=n<=8?[4,1,1]:[4,4,1],he=[Math.ceil(ne/W[0]/ue[0]),Math.ceil(J/W[1]/ue[1]),Math.ceil(u/W[2]/ue[2])];as("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${he}`);let be=z?h&&C%4!==0?3:4:1,Be=W[1]*ue[1],Ie=W[0]*ue[0],nt=Math.max(W[0]*be,W[1]),dt=n%Be===0,Et=i%Ie===0,zt=o%nt===0,It=z?[be,4,4]:[1,1,1],ht=[{type:6,data:n},{type:6,data:i},{type:6,data:o},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Zr(t,ht),ht.push(...Mt(e[0].dims,e[1].dims));let Jt=["rank","rank"];a&&(ht.push(...Mt(e[2].dims)),Jt.push("rank")),ht.push(...Mt(s));let Vt=St=>{let ts=[{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}];Ur(t,ts);let Xt=z?4:1,Ut=ds(e[0].dataType),$s=` + fn setOutputAtIndex(flatIndex : i32, value : ${z?`vec4<${Ut}>`:Ut}) { + result[flatIndex] = ${z?`vec4<${Ut}>`:Ut}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${z?`vec4<${Ut}>`:Ut}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${z?"/ 4":""}, value); + }`,ut=He("x",e[0].dataType,e[0].dims.length,be===3?1:be),xt=He("w",e[1].dataType,e[1].dims.length,Xt),hs=[ut,xt],vs=Ct("result",e[0].dataType,s.length,Xt);if(a){let xs=He("bias",e[2].dataType,e[2].dims.length,Xt);hs.push(xs),$s+=` + fn getBiasByOutputCoords(coords : vec4) -> ${z?`vec4<${Ut}>`:Ut} { + return bias[coords.${h?"w":"y"}${z?"/ 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 }; + ${St.registerUniforms(ts).declareVariables(...hs,vs)} + ${$s} + ${Oo(h,dt,Et,zt,a,t,It[0],It[1],It[2],Ut)} + ${z?$o(ue,W,Ut,void 0,!h,nt):Ao(ue,W,Ut,void 0,!h,nt,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${be};${z};${dt};${Et};${zt};${Be};${Ie};${nt}`,inputDependencies:Jt},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:he[0],y:he[1],z:he[2]},programUniforms:ht}),getShaderSource:Vt}}}),Do,Lo,Rn,au,zo,di,lu,uu,yc=y(()=>{Ot(),Te(),$t(),qt(),en(),Eo(),Do=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,Rn=(e,t)=>t<=1?e:e+(e-1)*(t-1),au=(e,t,s,n=1)=>{let i=Rn(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)},zo=(e,t,s,n,i)=>{i==null&&(i=au(e,t[0],n[0]));let o=[0,0,0,s];for(let a=0;a<3;a++)e[a]+2*i>=t[a]&&(o[a]=Math.trunc((e[a]-t[a]+2*i)/n[a]+1));return o},di=(e,t,s,n,i,o,a,c,p,h)=>{let C,u,k,B;if(e==="VALID"&&(e=0),typeof e=="number"){C={top:e,bottom:e,left:e,right:e,front:e,back:e};let R=zo([t,s,n,1],[c,p,h],1,[i,o,a],e);u=R[0],k=R[1],B=R[2]}else if(Array.isArray(e)){if(!e.every((z,ne,J)=>z===J[0]))throw Error(`Unsupported padding parameter: ${e}`);C={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let R=zo([t,s,n,1],[c,p,h],1,[i,o,a],e[0]);u=R[0],k=R[1],B=R[2]}else if(e==="SAME_UPPER"){u=Math.ceil(t/i),k=Math.ceil(s/o),B=Math.ceil(n/a);let R=(u-1)*i+c-t,z=(k-1)*o+p-s,ne=(B-1)*a+h-n,J=Math.floor(R/2),W=R-J,ue=Math.floor(z/2),he=z-ue,be=Math.floor(ne/2),Be=ne-be;C={top:ue,bottom:he,left:be,right:Be,front:J,back:W}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:C,outDepth:u,outHeight:k,outWidth:B}},lu=(e,t,s,n,i,o=!1,a="channelsLast")=>{let c,p,h,C,u;if(a==="channelsLast")[c,p,h,C,u]=e;else if(a==="channelsFirst")[c,u,p,h,C]=e;else throw new Error(`Unknown dataFormat ${a}`);let[k,,B,R,z]=t,[ne,J,W]=Lo(s),[ue,he,be]=Lo(n),Be=Rn(B,ue),Ie=Rn(R,he),nt=Rn(z,be),{padInfo:dt,outDepth:Et,outHeight:zt,outWidth:It}=di(i,p,h,C,ne,J,W,Be,Ie,nt),ht=o?k*u:k,Jt=[0,0,0,0,0];return a==="channelsFirst"?Jt=[c,ht,Et,zt,It]:a==="channelsLast"&&(Jt=[c,Et,zt,It,ht]),{batchSize:c,dataFormat:a,inDepth:p,inHeight:h,inWidth:C,inChannels:u,outDepth:Et,outHeight:zt,outWidth:It,outChannels:ht,padInfo:dt,strideDepth:ne,strideHeight:J,strideWidth:W,filterDepth:B,filterHeight:R,filterWidth:z,effectiveFilterDepth:Be,effectiveFilterHeight:Ie,effectiveFilterWidth:nt,dilationDepth:ue,dilationHeight:he,dilationWidth:be,inShape:e,outShape:Jt,filterShape:t}},uu=(e,t,s,n,i,o)=>{let a=o==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let c=[64,1,1],p={x:s.map((ne,J)=>J)},h=[Math.ceil(Do(p.x.map(ne=>s[ne]))/c[0]),1,1];as("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let C=1,u=De.size(s),k=[{type:12,data:u},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Zr(t,k),k.push(...Mt(e[0].dims,e[1].dims));let B=["rank","rank"],R=e.length===3;R&&(k.push(...Mt(e[2].dims)),B.push("rank")),k.push(...Mt(s));let z=ne=>{let J=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Ur(t,J);let W=1,ue=ds(e[0].dataType),he=He("x",e[0].dataType,e[0].dims.length,C),be=He("W",e[1].dataType,e[1].dims.length,W),Be=[he,be],Ie=Ct("result",e[0].dataType,s.length,W),nt="";if(R){let zt=He("bias",e[2].dataType,e[2].dims.length,W);Be.push(zt),nt+=` + fn getBiasByOutputCoords(coords : array) -> ${ue} { + return bias[${a?Tt("coords",4,5):Tt("coords",1,5)}]; + }`}let dt=qs(C,ue),Et=Vr(t,dt,ue);return` + ${nt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${he.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${be.getByIndices("aIndices")}; + } + ${ne.registerUniforms(J).declareVariables(...Be,Ie)} + ${ne.mainStart()} + ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ie.offsetToIndices("global_idx")}; + let batch = ${Tt("coords",0,he.rank)}; + let d2 = ${a?Tt("coords",he.rank-1,he.rank):Tt("coords",1,he.rank)}; + let xFRCCorner = vec3(${a?Tt("coords",1,he.rank):Tt("coords",2,he.rank)}, + ${a?Tt("coords",2,he.rank):Tt("coords",3,he.rank)}, + ${a?Tt("coords",3,he.rank):Tt("coords",4,he.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${a?Tt("uniforms.x_shape",1,he.rank):Tt("uniforms.x_shape",2,he.rank)}; + let xShapeZ = ${a?Tt("uniforms.x_shape",2,he.rank):Tt("uniforms.x_shape",3,he.rank)}; + let xShapeW = ${a?Tt("uniforms.x_shape",3,he.rank):Tt("uniforms.x_shape",4,he.rank)}; + let xShapeU = ${a?Tt("uniforms.x_shape",4,he.rank):Tt("uniforms.x_shape",1,he.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${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); + } + } + } + } + ${R?"value = value + getBiasByOutputCoords(coords)":""}; + ${Et} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${C};${R}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:k}),getShaderSource:z}}}),du,cu,pu=y(()=>{Ot(),$t(),qt(),en(),du=(e,t,s,n)=>{let i=e.length>2,o=i?"value += b[output_channel];":"",a=e[0].dims,c=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],C=h/t.group,u=p&&C>=4?Gt(h):1,k=De.size(s)/u,B=[{type:12,data:k},{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:C}];Zr(t,B),B.push(...Mt(a,[c[0],c[1],c[2],c[3]/u]));let R=i?["rank","rank","rank"]:["rank","rank"];B.push(...Mt([s[0],s[1],s[2],s[3]/u]));let z=ne=>{let J=Ct("output",e[0].dataType,s.length,u),W=ds(J.type.tensor),ue=Vr(t,J.type.value,W),he=He("x",e[0].dataType,a.length),be=He("w",e[1].dataType,c.length,u),Be=[he,be];i&&Be.push(He("b",e[2].dataType,e[2].dims,u));let Ie=[{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"}];Ur(t,Ie);let nt=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 = ${he.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${be.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${he.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${be.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${ne.registerUniforms(Ie).declareVariables(...Be,J)} + + ${ne.mainStart()} + ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${J.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: ${J.type.value} = ${J.type.value}(0); + ${nt} + ${o} + ${ue} + ${J.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:B}),getShaderSource:z}},cu=(e,t,s,n)=>{let i=e.length>2,o=Gt(s[3]),a=Gt(s[2]),c=De.size(s)/o/a,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],C=[s[0],s[1],s[2],s[3]/o],u=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Zr(t,u),u.push(...Mt(p,h,C));let k=(a-1)*t.strides[1]+h[1],B=R=>{let z=Ct("output",e[0].dataType,C.length,o),ne=ds(z.type.tensor),J=Vr(t,z.type.value,ne),W=He("x",e[0].dataType,p.length,o),ue=He("w",e[1].dataType,h.length,o),he=[W,ue];i&&he.push(He("b",e[2].dataType,e[2].dims,o));let be=i?"value += b[output_channel];":"",Be=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ur(t,Be),` + ${R.registerUniforms(Be).declareVariables(...he,z)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${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<${W.type.value}, ${k}>; + var values: array<${z.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 < ${k}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${W.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${W.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { + let w_val = ${ue.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]; + ${be} + ${J} + ${z.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${o};${a};${k};${h[0]};${h[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u}),getShaderSource:B}}}),hu,ci,Bo,pi,Ro,No,mu,jo,Vo,Mc=y(()=>{$t(),wc(),yc(),Fo(),pu(),en(),ko(),jr(),hu=(e,t,s,n,i,o)=>{let a=e[0],c=e.slice(o?1:2,o?3:4),p=c.length,h=t[0],C=t.slice(2).map((k,B)=>k+(k-1)*(s[B]-1)),u=c.map((k,B)=>k+n[B]+n[B+p]).map((k,B)=>Math.floor((k-C[B]+i[B])/i[B]));return u.splice(0,0,a),u.splice(o?3:1,0,h),u},ci=[2,3,1,0],Bo=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},pi=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=To(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,o=e.group,a=e.kernel_shape,c=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:i,group:o,kernelShape:a,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},No=(e,t,s,n)=>{let i=s.format==="NHWC",o=hu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,i);if(s.group!==1){let Be=[t[0]];if(i){let Ie=e.kernelCustomData.wT??e.compute(cr(t[1],ci),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ie),Be.push(Ie)}else Be.push(t[1]);t.length===3&&Be.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(cu(Be,s,o,n),{inputs:Be}):e.compute(du(Be,s,o,n),{inputs:Be});return}let a=t.length===3,c=t[0].dims[i?1:2],p=t[0].dims[i?2:3],h=t[0].dims[i?3:1],C=t[1].dims[2],u=t[1].dims[3],k=o[i?1:2],B=o[i?2:3],R=o[i?3:1],z=i&&C===c&&u===p&&s.pads[0]===0&&s.pads[1]===0;if(z||C===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=o[0],Ie,nt,dt,Et=[];if(i){let ht=e.kernelCustomData.wT??e.compute(cr(t[1],ci),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ht),z){let Jt=c*p*h;Ie=t[0].reshape([1,Be,Jt]),nt=ht.reshape([1,Jt,R]),dt=[1,Be,R]}else Ie=t[0].reshape([Be,c*p,h]),nt=ht.reshape([1,h,R]),dt=[Be,k*B,R];Et.push(Ie),Et.push(nt)}else Ie=t[0].reshape([Be,h,c*p]),nt=t[1].reshape([1,R,h]),dt=[Be,R,k*B],Et.push(nt),Et.push(Ie);a&&Et.push(t[2]);let zt=dt[2],It=Et[0].dims[Et[0].dims.length-1];zt<8&&It<8?e.compute(Co(Et,s,o,dt,i,n),{inputs:Et}):e.compute(ui(Et,s,o,dt,i,n),{inputs:Et});return}let ne=!0,J=e.kernelCustomData.wT??e.compute(cr(t[1],ci),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=J);let W=[t[0],J];a&&W.push(t[2]);let ue=i?k*B:R,he=i?R:k*B,be=C*u*h;e.compute(ou(W,s,o,ue,he,be,a,ne,n),{inputs:W})},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 i=[0,t.pads[0],0,t.pads[1]],o=[1].concat(t.strides),a=[1].concat(t.dilations),c=[1].concat(t.kernelShape),p=pi({...t,pads:i,strides:o,dilations:a,kernelShape:c},n);No(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},jo=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",i=pi(s,t),o=s.autoPad==="NOTSET"?s.pads:s.autoPad,a=lu(t[0].dims,t[1].dims,s.strides,s.dilations,o,!1,n);e.compute(uu(t,i,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},Vo=(e,t)=>{if(Bo(e.inputs,t),e.inputs[0].dims.length===3)mu(e,t);else if(e.inputs[0].dims.length===5)jo(e,e.inputs,t);else{let s=pi(t,e.inputs);No(e,e.inputs,s)}}}),Uo,bc=y(()=>{Ot(),Te(),$t(),qt(),Uo=(e,t,s)=>{let n=e.length>2,i=t.outputShape,o=t.format==="NHWC",a=t.group,c=e[1].dims,p=c[2]/a,h=c[3],C=o?Gt(p):1,u=o?Gt(h):1,k=o?h===1?C:u:1,B=De.size(i)/u,R=[Math.ceil(B/64),1,1];as("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${R}`);let z=["rank","rank"],ne=[t.strides[0],t.strides[1]],J=[t.kernelShape[o?1:2],t.kernelShape[o?2:3]],W=[t.dilations[0],t.dilations[1]],ue=[J[0]+(t.dilations[0]<=1?0:(t.kernelShape[o?1:2]-1)*(t.dilations[0]-1)),J[1]+(t.dilations[1]<=1?0:(t.kernelShape[o?2:3]-1)*(t.dilations[1]-1))],he=[ue[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),ue[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],be=[{type:12,data:B},{type:12,data:ne},{type:12,data:J},{type:12,data:W},{type:12,data:ue},{type:6,data:he},{type:12,data:p},{type:12,data:h},...Mt(e[0].dims,e[1].dims)];n&&(be.push(...Mt(e[2].dims)),z.push("rank")),be.push(...Mt(i));let Be=Ie=>{let nt=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:ne.length},{name:"filter_dims",type:"u32",length:J.length},{name:"dilations",type:"u32",length:J.length},{name:"effective_filter_dims",type:"u32",length:ue.length},{name:"pads",type:"i32",length:he.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],dt=ds(e[0].dataType),Et=o?1:2,zt=o?2:3,It=o?3:1,ht=He("W",e[1].dataType,e[1].dims.length,k),Jt=He("Dy",e[0].dataType,e[0].dims.length,C),Vt=[Jt,ht];n&&Vt.push(He("bias",e[2].dataType,[i[It]].length,u));let St=Ct("result",e[0].dataType,i.length,u),ts=()=>{let Ut="";if(C===1)Ut+=` + let w_offset = ${ht.indicesToOffset(`${ht.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${ht.getByOffset(`w_offset / ${k}`)}; + dotProd = dotProd + xValue * wValue;`;else if(h===1)Ut+=` + let wValue = ${ht.getByOffset(`${ht.indicesToOffset(`${ht.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${k}`)}; + dotProd = dotProd + dot(xValue, wValue);`;else for(let $s=0;$s(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 = ${St.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 = (${dt}(dyRCorner) + ${dt}(wR)) / ${dt}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${dt}(uniforms.Dy_shape[${Et}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + wR = wR + uniforms.strides[0] - 1; + 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 = (${dt}(dyCCorner) + ${dt}(wC)) / ${dt}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${dt}(uniforms.Dy_shape[${zt}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + wC = wC + uniforms.strides.y - 1; + 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 + ${C}) { + let xValue = ${o?Jt.getByOffset(`${Jt.indicesToOffset(`${Jt.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${C}`):Jt.get("batch","inputChannel","idyR","idyC")}; + ${ts()} + inputChannel = inputChannel + ${C}; + } + } + } + let value = dotProd${n?` + bias[d1 / ${u}]`:""}; + ${St.setByOffset("global_idx","value")}; + `;return` + ${Ie.registerUniforms(nt).declareVariables(...Vt,St)} + ${Ie.mainStart()} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${Xt}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${C}${k}${u}${h===1}`,inputDependencies:z},getRunData:()=>({dispatchGroup:{x:R[0],y:R[1],z:R[2]},outputs:[{dims:s?s(i):i,dataType:e[0].dataType}],programUniforms:be}),getShaderSource:Be}}}),fu,Wo,_u,Go,Ko,gu,Ho,wu,yu,Mu=y(()=>{bc(),en(),jr(),fu=(e,t,s,n,i,o)=>(e-1)*t+s+(n-1)*i+1-o,Wo=(e,t,s,n,i)=>{let o=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=o,s[i]=e-o):t==="SAME_LOWER"&&(s[n]=e-o,s[i]=o)},_u=(e,t,s,n,i,o,a,c,p,h)=>{let C=e.length-2,u=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,k)=>u*k,1)===0){s.length=0;for(let u=2;uu+k,0)===0){let u=t[0].dims.length-2;p=new Array(u).fill(1)}let h=e.strides.slice();if(h.reduce((u,k)=>u+k,0)===0){let u=t[0].dims.length-2;h=new Array(u).fill(1)}_u(c,s,p,e.autoPad,e.group,i,h,n,a,o);let C=Object.assign({},e);return Object.assign(C,{kernelShape:s,pads:i,outputPadding:a,outputShape:o,dilations:p,strides:h}),C},Ko=e=>{let t=To(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,o=e.group,a=e.kernelShape,c=e.pads,p=e.strides,h=e.wIsConst(),C=e.outputPadding,u=e.outputShape;return{autoPad:n,format:s,dilations:i,group:o,kernelShape:a,outputPadding:C,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 i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.reduce((a,c)=>a+c,0)>0&&t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.reduce((a,c)=>a+c,0)>0&&t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.reduce((a,c)=>a+c,0)>0&&t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.outputPadding.length!==o&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${o}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")},Ho=(e,t,s,n)=>{let i=e.kernelCustomData.wT??e.compute(cr(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let o=[t[0],i];t.length===3&&o.push(t[2]),e.compute(Uo(o,s,n),{inputs:o})},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 i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let o=t.dilations;(o.length===0||o[0]===0)&&(o=[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),o=[1].concat(o),i=[1].concat(i);let p=Go({...t,pads:c,strides:a,dilations:o,kernelShape:i},n);Ho(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=Go(t,e.inputs);Ho(e,e.inputs,s)}}}),bu,vu,xu,vc=y(()=>{Ot(),$t(),is(),qt(),bu=(e,t,s,n)=>{let i=De.size(t),o=t.length,a=He("input",e,o),c=Ct("output",e,o),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=De.normalizeAxis(p,o),C=u=>{let k=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,B=Tt("uniforms.input_shape","uniforms.axis",o),R=n.reverse?k+(n.exclusive?" + 1":""):"0",z=n.reverse?B:k+(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 = ${R}; + let last : i32 = ${z}; + 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(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...Mt(t,t)]}),getShaderSource:C}},vu=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(bu(n,s,i,t),{inputs:[0]})},xu=e=>{let t=e.exclusive===1,s=e.reverse===1;return jt({exclusive:t,reverse:s})}}),Tu,Pu,qo,Eu,Cu,ku=y(()=>{Ot(),$t(),is(),qt(),Tu=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.")},Pu=(e,t,s,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let o=0;o{let s,n,i,o,a,c,p=t.format==="NHWC",h=t.blocksize,C=t.mode==="DCR";p?([s,n,i,o]=e.dims,a=C?[s,n,i,h,h,o/h**2]:[s,n,i,o/h**2,h,h],c=C?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,i,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=C?[s,h,h,o/h**2,n,i]:[s,o/h**2,h,h,n,i],c=C?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),k=u.dims.length,B=e.dataType,R=He("a",B,k),z=Ct("output",B,k),ne=J=>` + ${J.registerUniform("output_size","u32").declareVariables(R,z)} + + ${Pu(c,k,R,z)} + + ${J.mainStart()} + ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${z.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${z.setByOffset("global_idx",R.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:J=>{let W=p?[s,n*h,i*h,o/h**2]:[s,o/h**2,n*h,i*h],ue=De.size(W),he=u.dims,be=De.sortBasedOnPerm(he,c);return{outputs:[{dims:W,dataType:J[0].dataType}],dispatchGroup:{x:Math.ceil(ue/64)},programUniforms:[{type:12,data:ue},...Mt(he,be)]}},getShaderSource:ne}},Eu=(e,t)=>{Tu(e.inputs),e.compute(qo(e.inputs[0],t))},Cu=e=>jt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),hi,Nn,Sr,Su,$u,Au,Iu,mi,Fu,Ou,Du,xc=y(()=>{Ot(),$t(),is(),qt(),hi="[a-zA-Z]|\\.\\.\\.",Nn="("+hi+")+",Sr="^"+Nn+"$",Su="("+Nn+",)*"+Nn,$u="^"+Su+"$",Au=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)}},Iu=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($u)))throw new Error("Invalid LHS term");if(s.split(",").forEach((i,o)=>{let a=e[o].dims.slice();if(!i.match(RegExp(Sr)))throw new Error("Invalid LHS term");let c=this.processTerm(i,!0,a,o);this.lhs.push(c)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([i,o])=>o.count===1||i==="...").map(([i])=>i).join("");else if(!n.match(RegExp(Nn)))throw new Error("Invalid RHS");n.match(RegExp(hi,"g"))?.forEach(i=>{if(i==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(i);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let i=s.length,o=!1,a=[],c=0;if(!e.match(RegExp(Sr))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(hi,"g")),h=new Au(n);return p?.forEach((C,u)=>{if(C==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let k=i-p.length+1;if(k<0)throw new Error("Ellipsis out of bounds");if(a=s.slice(c,c+k),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",Fu=(e,t,s,n)=>{let i=e.map(h=>h.length).map((h,C)=>He(`input${C}`,t,h)),o=De.size(n),a=Ct("output",t,n.length),c=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let C=[],u="var prod = 1.0;",k="var sum = 0.0;",B="sum += prod;",R=[],z=[],ne=[],J=[],W=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((he,be)=>{if(s.rhs.symbolToIndices.has(be)){let Be=s.rhs.symbolToIndices.get(be)?.[0];Be!==void 0&&s.lhs.forEach((Ie,nt)=>{if(he.inputIndices.includes(nt)){let dt=Ie.symbolToIndices.get(be);if(dt===void 0)throw new Error("Invalid symbol error");dt.forEach(Et=>{C.push(`${i[nt].indicesSet(`input${nt}Indices`,Et,a.indicesGet("outputIndices",Be))}`)})}})}else s.lhs.forEach((Be,Ie)=>{if(he.inputIndices.includes(Ie)){let nt=Be.symbolToIndices.get(be);if(nt===void 0)throw new Error("Invalid symbol error");nt.forEach(dt=>{R.push(`${i[Ie].indicesSet(`input${Ie}Indices`,dt,`${be}`)}`)}),J.push(`prod *= ${i[Ie].getByIndices(`input${Ie}Indices`)};`)}}),z.push(`for(var ${be}: u32 = 0; ${be} < uniforms.${mi(be)}; ${be}++) {`),ne.push("}")});let ue=W?[...C,`let sum = ${i.map((he,be)=>he.getByIndices(`input${be}Indices`)).join(" * ")};`]:[...C,k,...z,...R,u,...J,B,...ne];return` + ${h.registerUniforms(c.map(he=>({name:`${mi(he)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,a)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${a.offsetToIndices("global_idx")}; + ${i.map((he,be)=>`var input${be}Indices: ${i[be].type.indices};`).join(` +`)} + ${ue.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:o});let C=e.map((u,k)=>[...Mt(u)]).reduce((u,k)=>u.concat(k),h);return C.push(...Mt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:C}},getShaderSource:p}},Ou=(e,t)=>{let s=new Iu(e.inputs,t.equation),n=s.outputDims,i=e.inputs.map((o,a)=>o.dims);e.compute(Fu(i,e.inputs[0].dataType,s,n))},Du=e=>{let t=e.equation.replace(/\s+/g,"");return jt({equation:t})}}),fi,Qo,Lu,zu,jn,Tc=y(()=>{Ot(),$t(),qt(),fi=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let i=0;ie.length>t.length?Qo(e,t):Qo(t,e),zu=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Lu(t,s),i=e[0].dataType,o=i===9||De.size(t)===1,a=i===9||t.length>0&&t[t.length-1]%4===0?4:1,c=o||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(De.size(n)/c),h=u=>{let k=He("input",i,t.length,a),B=Ct("output",i,n.length,c),R;if(i===9){let z=(ne,J,W="")=>` + let outputIndices${J} = ${B.offsetToIndices(`outputOffset + ${J}u`)}; + let offset${J} = ${k.broadcastedIndicesToOffset(`outputIndices${J}`,B)}; + let index${J} = offset${J} / 4u; + let component${J} = offset${J} % 4u; + ${ne}[${J}] = ${W}(${k.getByOffset(`index${J}`)}[component${J}]); + `;R=` + let outputOffset = global_idx * ${c}; + var data = vec4(0); + ${z("data",0,"u32")} + ${z("data",1,"u32")} + ${z("data",2,"u32")} + ${z("data",3,"u32")} + ${B.setByOffset("global_idx","data")} + }`}else R=` + let outputIndices = ${B.offsetToIndices(`global_idx * ${c}`)}; + let inputOffset = ${k.broadcastedIndicesToOffset("outputIndices",B)}; + let data = ${B.type.value}(${k.getByOffset(`inputOffset / ${a}`)}); + ${B.setByOffset("global_idx","data")} + }`;return` + ${u.registerUniform("vec_size","u32").declareVariables(k,B)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${R}`},C=[{type:12,data:p},...Mt(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:C})}},jn=e=>{fi(e.inputs),e.compute(zu(e.inputs),{inputs:[0]})}}),Bu,Ru,Pc=y(()=>{Ot(),$t(),qt(),wo(),Bu=e=>{let t=e[0].dataType,s=De.size(e[0].dims),n=De.size(e[1].dims),i=n%4===0,o=a=>{let c=He("x",t,[1],4),p=He("bias",t,[1],4),h=Ct("y",t,[1],4),C=[{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];`,k=i?` + 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(C).declareVariables(c,p,h)} + + ${oi(Cs(t))} + + ${a.mainStart(sr)} + ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${c.getByOffset("global_idx")}; + ${k} + let x_in = x + bias; + ${h.setByOffset("global_idx",_o("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:o,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/sr/4)}})}},Ru=e=>{e.inputs.length<2||De.size(e.inputs[1].dims)===0?Ll(e):e.compute(Bu(e.inputs))}}),_i,Nu,ju,Vu,Bp=y(()=>{Ot(),$t(),is(),qt(),_i=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Nu=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,o=De.normalizeAxis(t.axis,i),a=s.slice(0);a.splice(o,1,...n);let c=s[o],p=e[0].dataType===9?4:1,h=Math.ceil(De.size(a)/p),C=[{type:12,data:h},{type:6,data:c},{type:12,data:o},...Mt(e[0].dims,e[1].dims,a)],u=k=>{let B=He("data",e[0].dataType,e[0].dims.length,p),R=He("inputIndices",e[1].dataType,e[1].dims.length),z=Ct("output",e[0].dataType,a.length,p),ne=W=>{let ue=n.length,he=`var indicesIndices${W} = ${R.type.indices}(0);`;for(let be=0;be1?`indicesIndices${W}[${be}]`:`indicesIndices${W}`} = ${a.length>1?`outputIndices${W}[uniforms.axis + ${be}]`:`outputIndices${W}`};`;he+=` + var idx${W} = ${R.getByIndices(`indicesIndices${W}`)}; + if (idx${W} < 0) { + idx${W} = idx${W} + uniforms.axisDimLimit; + } + var dataIndices${W} : ${B.type.indices}; + `;for(let be=0,Be=0;be1?`dataIndices${W}[${be}]`:`dataIndices${W}`} = u32(idx${W});`,Be+=ue):(he+=`${i>1?`dataIndices${W}[${be}]`:`dataIndices${W}`} = ${a.length>1?`outputIndices${W}[${Be}]`:`outputIndices${W}`};`,Be++);return he},J;if(e[0].dataType===9){let W=(ue,he,be="")=>` + let outputIndices${he} = ${z.offsetToIndices(`outputOffset + ${he}u`)}; + ${ne(he)}; + let offset${he} = ${B.indicesToOffset(`dataIndices${he}`)}; + let index${he} = offset${he} / 4u; + let component${he} = offset${he} % 4u; + ${ue}[${he}] = ${be}(${B.getByOffset(`index${he}`)}[component${he}]); + `;J=` + let outputOffset = global_idx * ${p}; + var value = vec4(0); + ${W("value",0,"u32")} + ${W("value",1,"u32")} + ${W("value",2,"u32")} + ${W("value",3,"u32")} + ${z.setByOffset("global_idx","value")} + `}else J=` + let outputIndices = ${z.offsetToIndices("global_idx")}; + ${ne("")}; + let value = ${B.getByIndices("dataIndices")}; + ${z.setByOffset("global_idx","value")}; + `;return` + ${k.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(B,R,z)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${J} + }`};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:C}),getShaderSource:u}},ju=e=>jt({axis:e.axis}),Vu=(e,t)=>{let s=e.inputs;_i(s),e.compute(Nu(e.inputs,t))}}),Uu,Wu,Gu,Vn=y(()=>{Ot(),$t(),qt(),Uu=(e,t,s,n,i,o,a,c,p)=>{let h=[{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:12,data:s},{type:12,data:a},{type:12,data:c},{type:12,data:p}],C=[o];h.push(...Mt(t.dims,C));let u=k=>{let B=He("indices_data",t.dataType,t.dims.length),R=Ct("input_slice_offsets_data",12,1,1),z=[B,R],ne=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${k.registerUniforms(ne).declareVariables(...z)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${i.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:C,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:h}),getShaderSource:u},{inputs:[t],outputs:[-1]})[0]},Wu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=s[0].dataType,o=s[1].dims,a=o[o.length-1],c=De.sizeToDimension(o,o.length-1),p=De.sizeFromDimension(n,t.batchDims+a),h=De.sizeToDimension(n,t.batchDims),C=De.sizeFromDimension(n,t.batchDims),u=c/h,k=new Array(a),B=p;for(let he=0;hen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let ne=o.slice(0,-1).concat(n.slice(z)),J=De.size(ne),W=[{type:12,data:J},{type:12,data:p},...Mt(s[0].dims,R.dims,ne)],ue=he=>{let be=He("data",s[0].dataType,s[0].dims.length),Be=He("slice_offsets",12,R.dims.length),Ie=Ct("output",s[0].dataType,ne.length);return` + ${he.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(be,Be,Ie)} + ${he.mainStart()} + ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:ne,dataType:i}],dispatchGroup:{x:Math.ceil(J/64)},programUniforms:W}),getShaderSource:ue},{inputs:[s[0],R]})},Gu=e=>({batchDims:e.batch_dims,cacheKey:""})}),Ku,Hu,qu,Qu,Ec=y(()=>{Ot(),$t(),is(),qt(),Ku=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=De.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],o=e[2],a=e.length===4?e[3]:void 0;if(o.dims.length!==i.dims.length||!i.dims.map((c,p)=>p===s?Math.ceil(c/n)===o.dims[p]:c===o.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!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==o.dims.length||!a.dims.map((c,p)=>c===o.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.")}},Hu=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,o=De.normalizeAxis(t.gatherAxis,i),a=De.normalizeAxis(t.quantizeAxis,i),c=s.slice(0);c.splice(o,1,...n);let p=De.size(c),h=e[2].dataType,C=e[0].dataType===22,u=[{type:12,data:p},{type:12,data:a},{type:12,data:o},{type:12,data:t.blockSize},...Mt(...e.map((B,R)=>B.dims),c)],k=B=>{let R=He("data",e[0].dataType,e[0].dims.length),z=He("inputIndices",e[1].dataType,e[1].dims.length),ne=He("scales",e[2].dataType,e[2].dims.length),J=e.length>3?He("zeroPoint",e[3].dataType,e[3].dims.length):void 0,W=Ct("output",h,c.length),ue=[R,z,ne];J&&ue.push(J);let he=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${B.registerUniforms(he).declareVariables(...ue,W)} + ${B.mainStart()} + let output_indices = ${W.offsetToIndices("global_idx")}; + var indices_indices = ${z.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${W.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${z.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${W.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${R.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${W.indicesGet("output_indices","i")}; + ${R.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${z.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${s[o]}; + } + ${R.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) { + let index = ${W.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${R.indicesSet("data_indices","i","index")}; + } + let data_offset = ${R.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${C?"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 = ${ne.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${ne.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${ne.getByIndices("scale_indices")}; + ${J?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${J.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${J.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${C?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Cs(h)}(quantized_data - zero_point) * scale; + ${W.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((B,R)=>R!==1).map(B=>B.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(B,R)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:u}),getShaderSource:k}},qu=(e,t)=>{let s=e.inputs;Ku(s,t),e.compute(Hu(e.inputs,t))},Qu=e=>jt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Xu,Yu,gi,Cc,kc=y(()=>{Ot(),$t(),is(),qt(),Xu=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.`)},Yu=(e,t)=>{let s=e[0].dims,n=e[0].dataType,i=s.length,o=e[1].dims,a=e[1].dataType,c=De.normalizeAxis(t.axis,i),p=s[c],h=o.slice(0),C=De.size(h),u=He("input",n,i),k=He("indicesInput",a,o.length),B=Ct("output",n,h.length),R=[{type:12,data:C},{type:6,data:p},{type:12,data:c}];return R.push(...Mt(s,o,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:R}),getShaderSource:z=>` + ${z.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,k,B)} + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${B.offsetToIndices("global_idx")}; + + var idx = ${k.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=>jt({axis:e.axis}),Cc=(e,t)=>{let s=e.inputs;Xu(s),e.compute(Yu(e.inputs,t))}}),Ju,Zu,ed,td,sd=y(()=>{Ot(),$t(),qt(),Ju=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")},Zu=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[i,o,a]=kr.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),c=[i,o];if(!c)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(o/p),C=Math.ceil(i/p),u=!0,k=De.size(c),B=[{type:12,data:u?h:k},{type:12,data:i},{type:12,data:o},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],R=["type","type"];e.length===3&&(B.push(...Mt(e[2].dims)),R.push("rank")),B.push(...Mt(c));let z=J=>{let W="";t.transA&&t.transB?W="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?W="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?W="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(W="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let ue=t.alpha===1?"":"value *= uniforms.alpha;",he=He("a",e[0].dataType,e[0].dims),be=He("b",e[1].dataType,e[1].dims),Be=he.type.value,Ie=null,nt=[he,be];e.length===3&&(Ie=He("c",e[2].dataType,e[2].dims.length),nt.push(Ie));let dt=Ct("output",e[0].dataType,c.length);nt.push(dt);let Et=[{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` + ${J.registerUniforms(Et).declareVariables(...nt)} + + ${J.mainStart()} + ${J.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++) { + ${W} + } + + ${ue} + ${Ie!=null?`let cOffset = ${Ie.broadcastedIndicesToOffset("vec2(m, n)",dt)}; value += ${Be}(uniforms.beta) * ${Ie.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},ne=J=>{let W=He("a",e[0].dataType,e[0].dims),ue=He("b",e[1].dataType,e[1].dims),he=null,be=[W,ue];e.length===3&&(he=He("c",e[2].dataType,e[2].dims.length),be.push(he));let Be=Ct("output",e[0].dataType,c.length);be.push(Be);let Ie=[{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"}],nt="",dt="";t.transA&&t.transB?(dt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${W.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] = ${ue.type.value}(0); + } + `,nt="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(dt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${W.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] = ${ue.type.value}(0); + } + `,nt="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(dt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${W.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] = ${ue.type.value}(0); + } + `,nt="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(dt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${W.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] = ${ue.type.value}(0); + } + `,nt="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Et=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${J.registerUniforms(Ie).declareVariables(...be)} + var tile_a: array, ${p}>; + var tile_b: array, ${p}>; + ${J.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++) { + ${dt} + k_start = k_start + ${p}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${p}; k++) { + ${nt} + } + workgroupBarrier(); + } + + ${Et} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${he!=null?`let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)",Be)}; value += ${Be.type.value}(uniforms.beta) * ${he.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return u?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:h*C},programUniforms:B}),getShaderSource:ne}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:B}),getShaderSource:z}},ed=e=>{let t=e.transA,s=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:s,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},td=(e,t)=>{Ju(e.inputs),e.compute(Zu(e.inputs,t))}}),vr,$r,Wr,tn,rd,Xo,nd,id,wi,od,ad,ld,ud,Yo,Jo=y(()=>{Ot(),$t(),is(),qt(),[vr,$r,Wr,tn]=[0,1,2,3],rd=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")},Xo=` + 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; + } +`,nd=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; + } +`,id=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)); + `} + } +`,wi=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); + }`:""} +`,od=(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[${vr}] = batch; + indices[${$r}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Wr}] = u32(r); + indices[${tn}] = u32(c); + } + `;case"border":return` + indices[${Wr}] = u32(clamp(r, 0, H - 1)); + indices[${tn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Wr}] = gs_reflect(r, border[1], border[3]); + indices[${tn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,ad=(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[${vr}], indices[${$r}], 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[${vr}], indices[${$r}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${vr}], indices[${$r}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${vr}], indices[${$r}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${vr}], indices[${$r}], 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[${vr}], indices[${$r}], 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")}`,ld=(e,t)=>{let s=He("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=He("grid",e[1].dataType,n.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[vr,$r,Wr,tn]=[0,3,1,2]);let a=Ct("output",e[0].dataType,o.length),c=s.type.value,p=De.size(o),h=[{type:12,data:p},...Mt(e[0].dims,n,o)],C=u=>` + ${u.registerUniform("output_size","u32").declareVariables(s,i,a)} + ${Xo} + ${nd(c)} + ${id(t)} + ${wi(t)} + ${od(s,c,t)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Wr}]); + let W_in = i32(uniforms.x_shape[${tn}]); + + ${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[${vr}], indices[${Wr}], indices[${tn}]); + let nxy = ${i.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${ad(a,c,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let k=De.size(o);return{outputs:[{dims:o,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:h}},getShaderSource:C}},ud=(e,t)=>{rd(e.inputs),e.compute(ld(e.inputs,t))},Yo=e=>jt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),rr,dd,cd,yi,pd,Un,Zo,hd=y(()=>{Ot(),$t(),is(),ce(),Zi(),qt(),jr(),rr=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,dd=(e,t)=>{let s=e[0],n=rr(e,1),i=rr(e,2),o=rr(e,3),a=rr(e,4),c=rr(e,5),p=rr(e,6),h=rr(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 C=s.dims[0],u=s.dims[1],k=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],B=u,R=0,z=0,ne=Math.floor(k/t.numHeads);if(p&&h&&De.size(p.dims)&&De.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==C||p.dims[1]!==t.numHeads||p.dims[3]!==ne)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==C||h.dims[1]!==t.numHeads||h.dims[3]!==ne)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');R=p.dims[2],z=p.dims[2]}else if(p&&De.size(p.dims)||h&&De.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let J;if(n&&De.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)');J=2,B=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==ne)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');J=5,B=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==ne)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');J=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');J=3}if(o&&De.size(o.dims)>0){if(o.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 W=R+B,ue=0;if(a&&De.size(a.dims)>0){ue=8;let Ie=a.dims;throw Ie.length===1?Ie[0]===C?ue=1:Ie[0]===3*C+2&&(ue=3):Ie.length===2&&Ie[0]===C&&Ie[1]===W&&(ue=5),ue===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let he=!1,be=k;if(i&&De.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(B!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');be=i.dims[2]}else{if(B!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');be=i.dims[1]*i.dims[3],he=!0}}let Be=!1;if(a&&De.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(c&&De.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]!==C||c.dims[1]!==t.numHeads||c.dims[2]!==u||c.dims[3]!==W)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:C,sequenceLength:u,pastSequenceLength:R,kvSequenceLength:B,totalSequenceLength:W,maxSequenceLength:z,inputHiddenSize:0,hiddenSize:k,vHiddenSize:be,headSize:ne,vHeadSize:Math.floor(be/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ue,scale:t.scale,broadcastResPosBias:Be,passPastInKv:he,qkvFormat:J}},cd=e=>jt({...e}),yi=jt({perm:[0,2,1,3]}),pd=(e,t,s,n,i,o,a)=>{let c=[n,i,o],p=De.size(c),h=[{type:12,data:p},{type:12,data:a},{type:12,data:o}],C=u=>{let k=Ct("qkv_with_bias",t.dataType,c),B=He("qkv",t.dataType,c),R=He("bias",s.dataType,c),z=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${u.registerUniforms(z).declareVariables(B,R,k)} + ${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:C},{inputs:[t,s],outputs:[-1]})[0]},Un=(e,t,s,n,i,o,a,c)=>{let p=o;if(a&&De.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=pd(e,o,a,t,n,s*i,c),p=p.reshape([t,n,s,i]),s===1||n===1?p:e.compute(cr(p,yi.perm),{inputs:[p],outputs:[-1]})[0]}else return o.dims.length===3&&(p=o.reshape([t,n,s,i])),s===1||n===1?p:e.compute(cr(p,yi.perm),{inputs:[p],outputs:[-1]})[0]},Zo=(e,t)=>{let s=dd(e.inputs,t),n=e.inputs[0],i=rr(e.inputs,1),o=rr(e.inputs,2),a=rr(e.inputs,3),c=rr(e.inputs,4),p=rr(e.inputs,5),h=rr(e.inputs,6),C=rr(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(i?.dims.length===5)throw new Error("Packed KV is not implemented");let u=i&&o&&i.dims.length===4&&o.dims.length===4,k=Un(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,a,0);if(u)return zn(e,k,i,o,c,void 0,h,C,p,s);if(!i||!o)throw new Error("key and value must be provided");let B=Un(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,i,a,s.hiddenSize),R=Un(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,o,a,2*s.hiddenSize);zn(e,k,B,R,c,void 0,h,C,p,s)}}),md,ea,Sc,$c,Mi,ta,fd,_d=y(()=>{Ot(),$t(),is(),qt(),md=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ea=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),n=s.length),jt({numOutputs:n,axis:t.axis,splitSizes:s})},Sc=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${Tt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,$c=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=De.size(s),i=e[0].dataType,o=De.normalizeAxis(t.axis,s.length),a=new Array(t.numOutputs),c=He("input",i,s.length),p=new Array(t.numOutputs),h=[],C=[],u=0,k=[{type:12,data:n}];for(let R=0;R` + ${R.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(c,...a)} + ${Sc(p.length)} + ${$c(a)} + + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${c.offsetToIndices("global_idx")}; + var index = ${c.indicesGet("indices",o)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Tt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; + ${c.indicesSet("indices",o,"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:k})}},ta=(e,t)=>{md(e.inputs);let s=e.inputs.length===1?t:ea(e.inputs,t);e.compute(Mi(e.inputs,s),{inputs:[0]})},fd=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 jt({axis:t,numOutputs:n,splitSizes:s})}}),sa,gd,ra,na,Ac=y(()=>{is(),Zi(),hd(),_d(),jr(),sa=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],i=e[2],o=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],C=s.dims.length===3?c?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],u=h,k=0,B=!n||n.dims.length===0,R=Math.floor(B?C/(t.numHeads+2*t.kvNumHeads):C/t.numHeads);B&&(C=R*t.numHeads);let z=o&&o.dims.length!==0,ne=a&&a.dims.length!==0;if(z&&o.dims.length===4&&o.dims[0]===p&&o.dims[1]!==t.kvNumHeads&&o.dims[2]===t.kvNumHeads&&o.dims[3]===R)throw new Error("BSNH pastKey/pastValue is not supported");if(z&&ne){if(o.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');k=o.dims[2]}else if(z||ne)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let J=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]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');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');J=3}let W=0,ue=!1,he=t.kvNumHeads?R*t.kvNumHeads:C;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(u!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');he=i.dims[2]}else{if(u!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');he=i.dims[1]*i.dims[3],ue=!0}}let be=e.length>4?e[5]:void 0;if(be&&be.dims.length!==1&&be.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:k,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:C,vHiddenSize:he,headSize:R,vHeadSize:Math.floor(he/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:W,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ue,qkvFormat:J}},gd=jt({perm:[0,2,1,3]}),ra=(e,t,s)=>{let n=t,i=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,i,s.headSize]),n=e.compute(cr(n,gd.perm),{inputs:[n],outputs:[-1]})[0]),n},na=(e,t)=>{let s=sa(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],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=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,C=s.kvNumHeads?s.kvNumHeads:s.numHeads,u=jt({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,C*s.headSize,C*s.headSize]}),[k,B,R]=!i&&!o?e.compute(Mi([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,o],z=Un(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,k,void 0,0);zn(e,z,ra(e,B,s),ra(e,R,s),void 0,void 0,a,c,void 0,s,p,h)}}),ia,oa,wd,yd,Ic=y(()=>{Ot(),$t(),jr(),qt(),ia=(e,t,s,n,i,o,a,c)=>{let p=Gt(o),h=p===1?"f32":`vec${p}f`,C=p===1?"vec2f":`mat2x${p}f`,u=i*a,k=64;u===1&&(k=256);let B=[i,a,o/p],R=[i,a,2],z=["rank","type","type"],ne=[];ne.push(...Mt(B,R));let J=W=>{let ue=He("x",t.dataType,3,p),he=He("scale",s.dataType,s.dims),be=He("bias",n.dataType,n.dims),Be=Ct("output",1,3,2),Ie=[ue,he,be,Be];return` + var workgroup_shared : array<${C}, ${k}>; + const workgroup_size = ${k}u; + ${W.declareVariables(...Ie)} + ${W.mainStart(k)} + 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}(${ue.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${C}(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 = ${js("workgroup_shared[0][0]",p)} / f32(hight * ${p}); + let squared_sum_final = ${js("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};${k}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:R,dataType:1}],dispatchGroup:{x:u},programUniforms:ne}),getShaderSource:J},{inputs:[t,s,n],outputs:[-1]})[0]},oa=(e,t,s)=>{let n=t[0].dims,i=n,o=2,a=n[0],c=n[1],p=De.sizeFromDimension(n,o),h=Gt(p),C=De.size(i)/h,u=ia(e,t[0],t[1],t[2],a,p,c,s.epsilon),k=[a,c,p/h],B=[a,c],R=["type","none"],z=ne=>{let J=He("x",t[0].dataType,k.length,h),W=He("scale_shift",1,B.length,2),ue=Ct("output",t[0].dataType,k.length,h),he=[J,W,ue];return` + ${ne.registerUniform("output_size","u32").declareVariables(...he)} + ${ne.mainStart()} + ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${ue.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${W.getByIndices("vec2(batch, channel)")}; + let value = ${J.getByOffset("global_idx")} * ${ue.type.value}(scale_shift.x) + ${ue.type.value}(scale_shift.y); + ${ue.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...Mt(k,B,k)]}),getShaderSource:z},{inputs:[t[0],u]})},wd=(e,t,s)=>{let n=t[0].dims,i=n,o=n[0],a=n[n.length-1],c=De.sizeFromDimension(n,1)/a,p=Gt(a),h=De.size(i)/p,C=[{type:12,data:c},{type:12,data:Math.floor(a/p)}],u=["type","type"],k=!1,B=[0,n.length-1];for(let J=0;Jn[B[W]])),z=ia(e,R,t[1],t[2],o,c,a,s.epsilon),ne=J=>{let W=ds(t[0].dataType),ue=p===1?"vec2f":`mat${p}x2f`,he=Ie=>{let nt=Ie===0?"x":"y",dt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${W}(${dt}(scale.${nt}))`;case 2:return`vec2<${W}>(${dt}(scale[0].${nt}, scale[1].${nt}))`;case 4:return`vec4<${W}>(${dt}(scale[0].${nt}, scale[1].${nt}, scale[2].${nt}, scale[3].${nt}))`;default:throw new Error(`Not supported compoents ${p}`)}},be=He("input",t[0].dataType,t[0].dims,p),Be=Ct("output",t[0].dataType,i,p);return` + @group(0) @binding(0) var input : array<${be.type.storage}>; + @group(0) @binding(1) var scale_input : array<${ue}>; + @group(0) @binding(2) var output : array<${Be.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${J.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${he(0)}, ${he(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:C}),getShaderSource:ne},{inputs:[t[0],z]})},yd=(e,t)=>{t.format==="NHWC"?wd(e,e.inputs,t):oa(e,e.inputs,t)}}),Md,bd,vd,Fc=y(()=>{Ot(),$t(),qt(),Md=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},bd=(e,t,s)=>{let n=t.simplified,i=e[0].dims,o=e[1],a=!n&&e[2],c=i,p=De.normalizeAxis(t.axis,i.length),h=De.sizeToDimension(i,p),C=De.sizeFromDimension(i,p),u=De.size(o.dims),k=a?De.size(a.dims):0;if(u!==C||a&&k!==C)throw new Error(`Size of X.shape()[axis:] == ${C}. + Size of scale and bias (if provided) must match this. + Got scale size of ${u} and bias size of ${k}`);let B=[];for(let be=0;be1,W=s>2,ue=be=>{let Be=ds(e[0].dataType),Ie=[He("x",e[0].dataType,e[0].dims,R),He("scale",o.dataType,o.dims,R)];a&&Ie.push(He("bias",a.dataType,a.dims,R)),Ie.push(Ct("output",e[0].dataType,c,R)),J&&Ie.push(Ct("mean_data_output",1,B)),W&&Ie.push(Ct("inv_std_output",1,B));let nt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${be.registerUniforms(nt).declareVariables(...Ie)} + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Is("f32",R)}; + var mean_square_vector = ${Is("f32",R)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${ks(Be,R,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${js("mean_vector",R)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${js("mean_square_vector",R)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${ks(Be,R,"x[j + offset]")}; + let f32scale = ${ks(Be,R,"scale[j]")}; + output[j + offset] = ${Ie[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${a?`+ ${ks(Be,R,"bias[j]")}`:""} + ); + } + + ${J?"mean_data_output[global_idx] = mean":""}; + ${W?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},he=[{dims:c,dataType:e[0].dataType}];return J&&he.push({dims:B,dataType:1}),W&&he.push({dims:B,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${R};${s};${n}`,inputDependencies:z},getRunData:()=>({outputs:he,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:ne}),getShaderSource:ue}},vd=(e,t)=>{Md(e.inputs),e.compute(bd(e.inputs,t,e.outputCount))}}),xd,Td,Pd=y(()=>{$t(),ko(),Fo(),xd=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.")},Td=e=>{xd(e.inputs);let t=Js.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(Co(e.inputs,{activation:""},t));else{let i=t[t.length-2],o=De.size(e.inputs[0].dims.slice(0,-2)),a=De.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&i===1&&a===1){let c=e.inputs[0].reshape([1,o,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,o,s],C=[c,p];e.compute(ui(C,{activation:""},t,h),{inputs:C})}else e.compute(ui(e.inputs,{activation:""},t))}}}),Ed,Cd,aa,kd,Sd,fs=y(()=>{Ot(),$t(),is(),qt(),Ed=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),o=t.blockSize/8*t.bits,a=e[1];if(!De.areEqual(a.dims,[t.n,i,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let c=e[2].dims;if(De.size(c)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(De.size(p)!==h)throw new Error("zeroPoints input size error.")}},Cd=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],o=t.k,a=t.n,c=s.slice(0,n-2),p=De.size(c),h=e[1].dims[2]/4,C=e[0].dataType,u=Gt(t.k),k=Gt(h),B=Gt(a),R=c.concat([i,a]),z=i>1&&a/B%2===0?2:1,ne=De.size(R)/B/z,J=64,W=[],ue=[p,i,o/u],he=De.convertShape(e[1].dims).slice();he.splice(-1,1,h/k),W.push(...Mt(ue)),W.push(...Mt(he)),W.push(...Mt(e[2].dims)),e.length===4&&W.push(...Mt(De.convertShape(e[3].dims)));let be=[p,i,a/B];W.push(...Mt(be));let Be=Ie=>{let nt=ue.length,dt=He("a",e[0].dataType,nt,u),Et=He("b",12,he.length,k),zt=He("scales",e[2].dataType,e[2].dims.length),It=[dt,Et,zt],ht=e.length===4?He("zero_points",12,e[3].dims.length):void 0;ht&&It.push(ht);let Jt=be.length,Vt=Ct("output",e[0].dataType,Jt,B),St=ds(e[0].dataType),ts=(()=>{switch(u){case 1:return`array<${St}, 8>`;case 2:return`mat4x2<${St}>`;case 4:return`mat2x4<${St}>`;default:throw new Error(`${u}-component is not supported.`)}})(),Xt=()=>{let ut=` + // reuse a data + var input_offset = ${dt.indicesToOffset(`${dt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ts}; + for (var j: u32 = 0; j < ${8/u}; j++) { + a_data[j] = ${dt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let xt=0;xt> 4) & b_mask); + b_quantized_values = ${ts}(${Array.from({length:4},(hs,vs)=>`${St}(b_value_lower[${vs}]), ${St}(b_value_upper[${vs}])`).join(", ")}); + b_dequantized_values = ${u===1?`${ts}(${Array.from({length:8},(hs,vs)=>`(b_quantized_values[${vs}] - ${ht?`zero_point${xt}`:"zero_point"}) * scale${xt}`).join(", ")});`:`(b_quantized_values - ${ts}(${Array(8).fill(`${ht?`zero_point${xt}`:"zero_point"}`).join(",")})) * scale${xt};`}; + workgroup_shared[local_id.x * ${z} + ${Math.floor(xt/B)}]${B>1?`[${xt%B}]`:""} += ${Array.from({length:8/u},(hs,vs)=>`${u===1?`a_data[${vs}] * b_dequantized_values[${vs}]`:`dot(a_data[${vs}], b_dequantized_values[${vs}])`}`).join(" + ")}; + `;return ut},Ut=()=>{let ut=` + var col_index = col * ${B}; + ${ht?` + 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 = ${St}(8);`} + `;for(let xt=0;xt> 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 = ${ht.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${xt} = ${St}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return ut},$s=()=>{let ut=`col_index = col * ${B};`;for(let xt=0;xt; + var b_value_upper: vec4; + var b_quantized_values: ${ts}; + var b_dequantized_values: ${ts};`,ut};return` + var workgroup_shared: array<${Vt.type.value}, ${z*J}>; + ${Ie.declareVariables(...It,Vt)} + ${Ie.mainStart([J,1,1])} + let output_indices = ${Vt.offsetToIndices(`(global_idx / ${J}) * ${z}`)}; + 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 += ${J}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/u}; + ${Ut()} + for (var word: u32 = 0; word < ${h}; word += ${k}) { + ${$s()} + for (var i: u32 = 0; i < ${k}; i++) { + ${Xt()} + word_offset += ${8/u}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${z}) { + var output_value: ${Vt.type.value} = ${Vt.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${J}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${z}; + } + ${Vt.setByIndices(`${Vt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${u};${k};${B};${z};${J}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:R,dataType:C}],dispatchGroup:{x:ne},programUniforms:W}),getShaderSource:Be}},aa=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],o=t.k,a=t.n,c=s.slice(0,n-2),p=De.size(c),h=e[1].dims[2]/4,C=e[0].dataType,u=Gt(t.k),k=Gt(h),B=c.concat([i,a]),R=128,z=a%8===0?8:a%4===0?4:1,ne=R/z,J=ne*k*8,W=J/u,ue=J/t.blockSize,he=De.size(B)/z,be=[],Be=[p,i,o/u],Ie=De.convertShape(e[1].dims).slice();Ie.splice(-1,1,h/k),be.push(...Mt(Be)),be.push(...Mt(Ie)),be.push(...Mt(e[2].dims)),e.length===4&&be.push(...Mt(De.convertShape(e[3].dims)));let nt=[p,i,a];be.push(...Mt(nt));let dt=Et=>{let zt=Be.length,It=He("a",e[0].dataType,zt,u),ht=He("b",12,Ie.length,k),Jt=He("scales",e[2].dataType,e[2].dims.length),Vt=[It,ht,Jt],St=e.length===4?He("zero_points",12,e[3].dims.length):void 0;St&&Vt.push(St);let ts=nt.length,Xt=Ct("output",e[0].dataType,ts),Ut=ds(e[0].dataType),$s=()=>{switch(u){case 1:return` + let a_data0 = vec4<${Ut}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Ut}>(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<${Ut}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Ut}>(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<${It.type.value}, ${W}>; + var inter_results: array, ${z}>; + ${Et.declareVariables(...Vt,Xt)} + ${Et.mainStart([ne,z,1])} + let output_indices = ${Xt.offsetToIndices(`workgroup_index * ${z}`)}; + 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) / ${ue} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${W}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${W}; a_offset += ${R}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${It.getByIndices(`${It.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${It.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${ue} + local_id.x; + ${St?` + 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 = ${St.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Ut}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Ut}(8);`} + let scale = ${Jt.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${ht.getByIndices(`${ht.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/u}; + for (var i: u32 = 0; i < ${k}; i++) { + ${$s()} + let b_value = ${k===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<${Ut}>(${Array.from({length:4},(ut,xt)=>`${Ut}(b_value_lower[${xt}]), ${Ut}(b_value_upper[${xt}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Ut}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ut,xt)=>`${`dot(a_data${xt}, b_dequantized_values[${xt}])`}`).join(" + ")}; + word_offset += ${8/u}; + } + workgroupBarrier(); + } + + if (local_idx < ${z}) { + var output_value: ${Xt.type.value} = ${Xt.type.value}(0); + for (var b = 0u; b < ${ne}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Xt.setByIndices(`${Xt.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${u};${k};${ne};${z}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:C}],dispatchGroup:{x:he},programUniforms:be}),getShaderSource:dt}},kd=(e,t)=>{Ed(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(aa(e.inputs,t)):e.compute(Cd(e.inputs,t))},Sd=e=>jt(e)}),Oc,Dc,Lc,la,$d,Ad,Id,Fd,ua,Od=y(()=>{Ot(),$t(),qt(),Oc=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].")}},Dc=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Tt("uniforms.pads",i,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Tt("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${Tt("uniforms.x_strides",i,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},Lc=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Tt("uniforms.pads",i,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Tt("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${Tt("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Tt("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},la=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Tt("uniforms.pads",i,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Tt("uniforms.x_shape",i,t)})) { + k = i32(${Tt("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${Tt("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},$d=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Tt("uniforms.pads",i,s)}; + if (k < 0) { + k += i32(${Tt("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${Tt("uniforms.x_shape",i,t)})) { + k -= i32(${Tt("uniforms.x_shape",i,t)}); + } + offset += k * i32(${Tt("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Ad=(e,t,s)=>{switch(s.mode){case 0:return Dc(e,t,s.pads.length);case 1:return Lc(e,t,s.pads.length);case 2:return la(e,t,s.pads.length);case 3:return $d(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Id=(e,t)=>{let s=De.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=De.size(s),o=[{type:12,data:i},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&o.push({type:a?e[2].dataType:1,data:t.value}),o.push(...Mt(e[0].dims,s));let c=["rank"],p=h=>{let C=Ct("output",e[0].dataType,s.length),u=He("x",e[0].dataType,n.length),k=u.type.value,B=Ad(C,n.length,t),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&R.push({name:"constant_value",type:a?k:"f32"}),` + ${h.registerUniforms(R).declareVariables(u,C)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${C.offsetToIndices("global_idx")}; + + var value = ${k}(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(De.size(s)/64)},programUniforms:o}),getShaderSource:p}},Fd=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,o=new Int32Array(2*i).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let p=0;po[Number(p)]=Number(c));let a=[];return o.forEach(c=>a.push(c)),{mode:t.mode,value:n,pads:a}}else return t},ua=(e,t)=>{Oc(e.inputs);let s=Fd(e.inputs,t);e.compute(Id(e.inputs,s),{inputs:[0]})}}),bi,da,ca,vi,Dd,zc,Ld,pa,ha,zd,Bd,ma,Rd,Nd,fa,jd,Vd,Ud,Bc,Rc=y(()=>{We(),Ot(),$t(),qt(),bi=e=>{if(F.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},da=(e,t,s)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let o=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),c=t.strides.slice(),p=o?t.dilations.slice():[],h=t.pads.slice();Xs.adjustPoolAttributes(s,i,a,c,p,h);let C=Xs.computePoolOutputShape(s,i,c,p,a,h,t.autoPad),u=Object.assign({},t);o?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 k=C.slice();return k.push(k.splice(1,1)[0]),[u,n?k:C]},ca=(e,t)=>{let s=t.format==="NHWC",n=De.size(e),i=De.size(t.kernelShape),o=[{type:12,data:n},{type:12,data:i}],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],C=t.pads[t.pads.length-1],u=!!(h+C);o.push({type:12,data:c},{type:12,data:p},{type:12,data:h},{type:12,data:C}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let k=!1;if(t.kernelShape.length===2){let B=t.kernelShape[t.kernelShape.length-2],R=t.strides[t.strides.length-2],z=t.pads[t.pads.length/2-2],ne=t.pads[t.pads.length-2];k=!!(z+ne),o.push({type:12,data:B},{type:12,data:R},{type:12,data:z},{type:12,data:ne}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,a,!0,u,k]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=De.computeStrides(t.kernelShape);o.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,C)=>h+C);return[o,a,!!p,!1,!1]}},vi=(e,t,s,n,i,o,a,c,p,h,C,u)=>{let k=i.format==="NHWC",B=t.type.value,R=Ct("output",t.type.tensor,n);if(i.kernelShape.length<=2){let z="",ne="",J="",W=s-(k?2:1);if(C?z=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${W}] = indices[${W}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${W}] < 0 || xIndices[${W}] + >= uniforms.x_shape[${W}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`:z=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${W}] = indices[${W}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`,i.kernelShape.length===2){let ue=s-(k?3:2);u?ne=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ue}] = indices[${ue}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${ue}] < 0 || xIndices[${ue}] >= uniforms.x_shape[${ue}]) { + pad += i32(uniforms.kw); + continue; + } + `:ne=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ue}] = indices[${ue}] * uniforms.sh - uniforms.phStart + j; + `,J=` + } + `}return` + ${e.registerUniforms(p).declareVariables(t,R)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${R.offsetToIndices("global_idx")}; + var xIndices = ${R.offsetToIndices("global_idx")}; + + var value = ${B}(${c}); + var pad = 0; + ${ne} + ${z} + ${J} + ${a} + + output[global_idx] = value; + }`}else{if(k)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let z=i.kernelShape.length,ne=i.pads.length,J="";return h?J=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`:J=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + `,` + ${e.registerUniforms(p).declareVariables(t,R)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${R.offsetToIndices("global_idx")}; + var xIndices = ${R.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${B}(${c}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${z-1}u; j++) { + offsets[j] = offset / ${Tt("uniforms.kernelStrides","j",z)}; + offset -= offsets[j] * ${Tt("uniforms.kernelStrides","j",z)}; + } + offsets[${z-1}] = offset; + + isPad = false; + for (var j = ${s-z}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Tt("uniforms.strides",`j - ${s-z}u`,z)} + + offsets[j - ${s-z}u] - ${Tt("uniforms.pads","j - 2u",ne)}; + ${J} + } + ${a} + + output[global_idx] = value; + }`}},Dd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,zc=e=>`${Dd(e)};${e.countIncludePad}`,Ld=e=>`${Dd(e)};${e.storageOrder};${e.dilations}`,pa=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}),ha=(e,t,s,n)=>{let[i,o]=da(t,n,s),a=He("x",t.dataType,t.dims.length),c=a.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${c}(uniforms.kernelSize);`:h+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[C,u,k,B,R]=ca(o,i);C.push(...Mt(t.dims,o));let z=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${k};${B};${R}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(De.size(o)/64)},programUniforms:C}),getShaderSource:ne=>vi(ne,a,t.dims.length,o.length,i,p,h,0,u,k,B,R)}},zd=e=>{let t=e.count_include_pad!==0,s=pa(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:zc(n)}},Bd=(e,t)=>{bi(e.inputs),e.compute(ha("AveragePool",e.inputs[0],!1,t))},ma={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Rd=e=>{let t=e.format;return{format:t,...ma,cacheKey:t}},Nd=(e,t)=>{bi(e.inputs),e.compute(ha("GlobalAveragePool",e.inputs[0],!0,t))},fa=(e,t,s,n)=>{let[i,o]=da(t,n,s),a=` + value = max(x_val, value); + `,c="",p=He("x",t.dataType,t.dims.length),h=["rank"],[C,u,k,B,R]=ca(o,i);return C.push(...Mt(t.dims,o)),{name:e,shaderCache:{hint:`${n.cacheKey};${k};${B};${R}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(De.size(o)/64)},programUniforms:C}),getShaderSource:z=>vi(z,p,t.dims.length,o.length,i,a,c,t.dataType===10?-65504:-1e5,u,k,B,R)}},jd=(e,t)=>{bi(e.inputs),e.compute(fa("MaxPool",e.inputs[0],!1,t))},Vd=e=>{let t=e.storage_order,s=e.dilations,n=pa(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:s,...n,cacheKey:""};return{...i,cacheKey:Ld(i)}},Ud=e=>{let t=e.format;return{format:t,...ma,cacheKey:t}},Bc=(e,t)=>{bi(e.inputs),e.compute(fa("GlobalMaxPool",e.inputs[0],!0,t))}}),Wd,Gd,Kd,Hd,Nc=y(()=>{Ot(),$t(),is(),qt(),Wd=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,o)=>o===t.axis||i===e[0].dims[o]).reduce((i,o)=>i&&o,!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)].")}},Gd=(e,t)=>{let s=De.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,o=e[0].dims,a=e[1].dataType,c=De.size(o),p=n===3||n===2,h=p?[Math.ceil(De.size(e[0].dims)/4)]:e[0].dims,C=e[1].dims,u=e.length>2?e[2]:void 0,k=u?p?[Math.ceil(De.size(u.dims)/4)]:u.dims:void 0,B=C.length===0||C.length===1&&C[0]===1,R=B===!1&&C.length===1,z=Gt(c),ne=B&&(!p||z===4),J=ne?z:1,W=ne&&!p?z:1,ue=He("input",p?12:n,h.length,W),he=He("scale",a,C.length),be=u?He("zero_point",p?12:n,k.length):void 0,Be=Ct("output",a,o.length,J),Ie=[ue,he];be&&Ie.push(be);let nt=[h,C];u&&nt.push(k);let dt=[{type:12,data:c/J},{type:12,data:s},{type:12,data:t.blockSize},...Mt(...nt,o)],Et=zt=>{let It=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${zt.registerUniforms(It).declareVariables(...Ie,Be)} + ${zt.mainStart()} + ${zt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Be.offsetToIndices("global_idx")}; + + // Set input x + ${p?` + let input = ${ue.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${J===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ue.getByOffset("global_idx")};`}; + + // Set scale input + ${B?`let scale_value= ${he.getByOffset("0")}`:R?` + let scale_index = ${Be.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${he.getByOffset("scale_index")};`:` + var scale_indices: ${he.type.indices} = output_indices; + let index = ${he.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${he.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${he.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${be?B?p?` + let zero_point_input = ${be.getByOffset("0")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${be.getByOffset("0")}`:R?p?` + let zero_point_index = ${Be.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${be.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Be.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${be.getByOffset("zero_point_index")};`:p?` + let zero_point_offset = ${he.indicesToOffset("scale_indices")}; + let zero_point_input = ${be.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${be.getByIndices("scale_indices")};`:`let zero_point_value = ${p?i?"i32":"u32":ue.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:be?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Et,getRunData:()=>({outputs:[{dims:o,dataType:a}],dispatchGroup:{x:Math.ceil(c/J/64),y:1,z:1},programUniforms:dt})}},Kd=(e,t)=>{Wd(e.inputs,t),e.compute(Gd(e.inputs,t))},Hd=e=>jt({axis:e.axis,blockSize:e.blockSize})}),jc,Vc,Uc,Rp=y(()=>{We(),Ot(),qt(),jc=(e,t,s)=>{let n=e===t,i=et&&s>0;if(n||i||o)throw new Error("Range these inputs' contents are invalid.")},Vc=(e,t,s,n)=>{let i=Math.abs(Math.ceil((t-e)/s)),o=[i],a=i,c=[{type:12,data:a},{type:n,data:e},{type:n,data:s},...Mt(o)],p=h=>{let C=Ct("output",n,o.length),u=C.type.value,k=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` + ${h.registerUniforms(k).declareVariables(C)} + ${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:o,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c})}},Uc=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]),F.webgpu.validateInputContent&&jc(t,s,n),e.compute(Vc(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Wc,Gc,Kc,Hc,Np=y(()=>{Ot(),$t(),is(),qt(),Wc=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let i=`{ + var oldValue = 0; + loop { + let newValueF32 =`,o=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` + ${i}bitcast<${n}>(oldValue) + (${s})${o}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` + ${i}max(bitcast(oldValue), (${s}))${o}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${i}min(bitcast<${n}>(oldValue), (${s}))${o}`;case"mul":return`${i}(bitcast<${n}>(oldValue) * (${s}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Gc=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s,o=1,a=Math.ceil(De.size(n)/o),c=n[n.length-1],p=De.sizeFromDimension(s,c),h=[{type:12,data:a},{type:12,data:c},{type:12,data:p},...Mt(e[1].dims,e[2].dims,i)],C=u=>{let k=He("indices",e[1].dataType,e[1].dims.length),B=He("updates",e[2].dataType,e[2].dims.length,o),R=t.reduction!=="none"&&t.reduction!==""?Ea("output",e[0].dataType,i.length):Ct("output",e[0].dataType,i.length,o);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(k,B,R)} + ${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]; + ${Wc(t.reduction,"output[data_offset + i]","value",R.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:C}},Kc=e=>jt({reduction:e.reduction}),Hc=(e,t)=>{e.compute(Gc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),qc,Qc,Xc,Yc,Jc,Zc,ep,tp,sp,rp,np,qd,ip,op,ap,lp,up,dp,cp,jp=y(()=>{Ot(),$t(),is(),qt(),qc=(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")}},Qc=(e,t,s)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((i,o)=>n[i]=e[o]),n},Xc=(e,t,s,n,i,o)=>{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(C=>o.push(C));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(C=>n.push(C)),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");qc(n,t),t.axes.length>0&&Qc(n,t.axes,h).forEach((C,u)=>n[u]=C)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(C=>i.push(Number(C))),i.length!==0&&i.length!==h&&s>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof i<"u"&&n.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Yc=(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`)}})()+"}",Jc=(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`)}})()+"}",Zc=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((o,a)=>{n[o]=i[a],n[a+s]=i[t.length+a]}),n):i},ep=(e,t,s,n)=>{let i=[];if(s.length>0)if(n.length>0){if(e.forEach(o=>i.push(o)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((o,a)=>i[o]=s[a])}else s.forEach(o=>i.push(o));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((o,a)=>Math.round(o*t[a]))}return i},tp=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(o=>t[o]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(o=>t[o]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return s.axes.length>0?(s.axes.forEach(o=>t[o]=n),s.axes.forEach(o=>i[o]=Math.round(e[o]*t[o]))):(t.fill(n,0,t.length),i.forEach((o,a)=>i[a]=Math.round(o*t[a]))),i},sp=(e,t,s,n,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { + var original_indices: array<${e.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${Tt("uniforms.scales","i",n)}; + var roi_low = ${Tt("uniforms.roi","i",i)}; + var roi_hi = ${Tt("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${Tt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Tt("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; + }`,rp=(e,t,s,n,i,o,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 = ${Tt("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Tt("uniforms.roi","i",o)}; + var roi_hi = ${Tt("uniforms.roi",`i + ${s.length}`,o)}; + var input_shape_i = ${Tt("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Tt("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; + }`,np=(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 >= ${Tt("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,qd=(e,t,s,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",s,"batch")}; +`:"",ip=(e,t,s,n,i)=>{let[o,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))`)}; + ${qd(e,p,o,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 ${i}; + }`:""}; + 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[${o}])`:"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); + }`},op=(e,t,s,n,i,o,a,c,p,h)=>{let C=s.length===2,[u,k]=C?[0,1]:[2,3],B=e.type.value,R=z=>{let ne=z===u?"row":"col";return` + fn ${ne}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { + var output_index = ${t.indicesGet("output_indices",z)}; + var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[z]}, + ${n[z]}, ${s[z]}, ${o[z]}, ${o[z]} + ${s.length}); + var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${c} && (originalIdx < 0 || originalIdx > (${s[z]} - 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 ${ne}: ${B} = originalIdx + ${B}(i); + if (${ne} < 0 || ${ne} >= ${s[z]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:c?`return ${p};`:`${ne} = max(0, min(${ne}, ${s[z]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",z,`u32(${ne})`)}; + data[i + 1] = ${z===u?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${R(u)}; + ${R(k)}; + 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); + } + `},ap=(e,t,s,n,i)=>{let[o,a,c,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],C=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${C} { + 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))`)}; + ${qd(e,h,o,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${C} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${C} = originalIndices[${a}]; + var height:${C} = originalIndices[${c}]; + var width:${C} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${s[a]} - 1) || height < 0 || height > (${s[c]} - 1) || width < 0 || (width > ${s[p]} - 1)) { + return ${i}; + }`:""}; + + 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[${o}])`:"0"}; + + var x111: ${C} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${C} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${C} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${C} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${C} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${C} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${C} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${C} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${C} = abs(depth - ${C}(depth1)); + var dx2: ${C} = abs(${C}(depth2) - depth); + var dy1: ${C} = abs(height - ${C}(height1)); + var dy2: ${C} = abs(${C}(height2) - height); + var dz1: ${C} = abs(width - ${C}(width1)); + var dz2: ${C} = abs(${C}(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); + }`},lp=(e,t,s,n,i,o)=>{let a=e.dims,c=Zc(o,t.axes,a.length),p=ep(a,n,i,t.axes),h=n.slice();n.length===0&&(h=a.map((W,ue)=>W===0?1:p[ue]/W),t.keepAspectRatioPolicy!=="stretch"&&(p=tp(a,h,t)));let C=Ct("output",e.dataType,p.length),u=He("input",e.dataType,a.length),k=De.size(p),B=a.length===p.length&&a.every((W,ue)=>W===p[ue]),R=t.coordinateTransformMode==="tf_crop_and_resize",z=t.extrapolationValue,ne=u.type.value,J=W=>` + ${B?"":` + ${Yc(t.coordinateTransformMode,ne)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${np(u,a)}; + ${Jc(t.nearestMode,s,ne)}; + ${rp(u,C,a,p,h.length,c.length,R)}; + `;case"linear":return` + ${sp(C,a,p,h.length,c.length)}; + ${(()=>{if(a.length===2||a.length===4)return`${ip(u,C,a,R,z)}`;if(a.length===3||a.length===5)return`${ap(u,C,a,R,z)}`;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`${op(u,C,a,p,h,c,t.cubicCoeffA,R,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${W.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",c.length).declareVariables(u,C)} + ${W.mainStart()} + ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${B?"output[global_idx] = input[global_idx];":` + let output_indices = ${C.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:""}|${i.length>0?i:""}|${c.length>0?c:""}|${B}|${a}`,inputDependencies:["rank"]},getShaderSource:J,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},{type:1,data:h},{type:1,data:c},...Mt(a,p)]})}},up=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},dp=(e,t)=>{let s=[],n=[],i=[],o=up(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Xc(e.inputs,t,o,s,n,i),e.compute(lp(e.inputs[0],t,o,s,n,i),{inputs:[0]})},cp=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,o=e.excludeOutside!==0,a=e.extrapolationValue,c=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return jt({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:o,extrapolationValue:a,keepAspectRatioPolicy:c,mode:p,nearestMode:h})}}),pp,hp,Kt,mp=y(()=>{Ot(),$t(),is(),qt(),pp=(e,t)=>{let[s,n,i,o]=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(!De.areEqual(n.dims,[])&&!De.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!De.areEqual(i.dims,o.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],C=i.dims[0],u=De.sizeFromDimension(s.dims,1)/h,k=c===0?i.dims[1]*2:u/a;if(c>k)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(k/2!==i.dims[1]&&c/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>C)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},hp=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:i,scale:o}=t,a=e[0].dims[0],c=De.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=c/p,C=e[2].dims[1],u=i===0?C*2:h/n,k=new Array(a,p,h/u,u-C),B=De.computeStrides(k),R=[{type:1,data:o},{type:12,data:k},{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]}):[],...Mt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],z=ne=>{let J=He("input",e[0].dataType,e[0].dims.length),W=He("position_ids",e[1].dataType,e[1].dims.length),ue=He("cos_cache",e[2].dataType,e[2].dims.length),he=He("sin_cache",e[3].dataType,e[3].dims.length),be=Ct("output",e[0].dataType,e[0].dims.length);return ne.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:k.length},{name:"global_strides",type:"u32",length:B.length},{name:"input_output_strides",type:"u32",length:B.length}]),` + ${ne.declareVariables(J,W,ue,he,be)} + + ${ne.mainStart(sr)} + let half_rotary_emb_dim = uniforms.${ue.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${ne.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${W.broadcastedIndicesToOffset("bsnh.xy",Ct("",W.type.tensor,2))}; + let position_id = + u32(${W.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 = ${J.getByOffset("i")} * ${ue.get("position_id","bsnh[3]")} - + ${J.getByOffset("j")} * ${he.get("position_id","bsnh[3]")}; + ${be.setByOffset("i","re")} + let im = ${J.getByOffset("i")} * ${he.get("position_id","bsnh[3]")} + + ${J.getByOffset("j")} * ${ue.get("position_id","bsnh[3]")}; + ${be.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${be.setByOffset("k",J.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:jt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(De.size(k)/sr)},programUniforms:R})}},Kt=(e,t)=>{pp(e.inputs,t),e.compute(hp(e.inputs,t))}}),Vs,Qs,Zs,yn=y(()=>{Ot(),$t(),qt(),Vs=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],o=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==i)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]!==i)throw new Error("Bias must have the same hidden size as input")}},Qs=(e,t,s,n)=>{let i=t.simplified,o=e[0].dims,a=De.size(o),c=o,p=a,h=o.slice(-1)[0],C=n?o.slice(0,-1).concat(1):[],u=!i&&e.length>3,k=e.length>4,B=n&&s>1,R=n&&s>2,z=s>3,ne=64,J=Gt(h),W=[{type:12,data:p},{type:12,data:J},{type:12,data:h},{type:1,data:t.epsilon}],ue=be=>{let Be=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ie=[He("x",e[0].dataType,e[0].dims,J),He("skip",e[1].dataType,e[1].dims,J),He("gamma",e[2].dataType,e[2].dims,J)];u&&Ie.push(He("beta",e[3].dataType,e[3].dims,J)),k&&Ie.push(He("bias",e[4].dataType,e[4].dims,J)),Ie.push(Ct("output",e[0].dataType,c,J)),B&&Ie.push(Ct("mean_output",1,C)),R&&Ie.push(Ct("inv_std_output",1,C)),z&&Ie.push(Ct("input_skip_bias_sum",e[0].dataType,c,J));let nt=ds(e[0].dataType),dt=ds(1,J);return` + + ${be.registerUniforms(Be).declareVariables(...Ie)} + var sum_shared : array<${dt}, ${ne}>; + var sum_squared_shared : array<${dt}, ${ne}>; + + ${be.mainStart([ne,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${ne}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${ne}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${ne-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${k?"bias[offset1d + i]":nt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${z?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${ks(nt,J,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${ne}; + 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 = ${js("sum",J)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${js("square_sum",J)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${B?"mean_output[global_idx] = mean;":""} + ${R?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${nt}(mean)`}) * + ${nt}(inv_std_dev) * gamma[offset1d + i] + ${u?"+ beta[offset1d + i]":""}; + } + }`},he=[{dims:c,dataType:e[0].dataType}];return s>1&&he.push({dims:C,dataType:1}),s>2&&he.push({dims:C,dataType:1}),s>3&&he.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${J};${B};${R};${z}`,inputDependencies:e.map((be,Be)=>"type")},getShaderSource:ue,getRunData:()=>({outputs:he,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:W})}},Zs=(e,t)=>{Vs(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(Qs(e.inputs,t,e.outputCount,!1),{outputs:s})}}),fp,Wn,Qd,_,f,q,xe,$e,Le=y(()=>{Ot(),$t(),is(),qt(),fp=(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`)})},Wn=(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},Qd=(e,t)=>{if(e.length>1){let s=Wn(e,1),n=Wn(e,2),i=Wn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),jt({starts:s,ends:n,axes:i})}else return t},_=(e,t,s,n,i)=>{let o=e;return e<0&&(o+=s[n[t]]),i[t]<0?Math.max(0,Math.min(o,s[n[t]]-1)):Math.max(0,Math.min(o,s[n[t]]))},f=(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 = ${Tt("uniforms.input_shape","i",s.length)}; + let steps_i = ${Tt("uniforms.steps","i",s.length)}; + let signs_i = ${Tt("uniforms.signs","i",s.length)}; + let starts_i = ${Tt("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; + }`,q=(e,t)=>{let s=e[0].dims,n=De.size(s),i=t.axes.length>0?De.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],o=Wn(e,4);o.forEach(J=>J!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(i.length).fill(1));let a=t.starts.map((J,W)=>_(J,W,s,i,o)),c=t.ends.map((J,W)=>_(J,W,s,i,o));if(i.length!==a.length||i.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==s.length)for(let J=0;JMath.sign(J));o.forEach((J,W,ue)=>{if(J<0){let he=(c[W]-a[W])/J,be=a[W],Be=be+he*o[W];a[W]=Be,c[W]=be,ue[W]=-J}});let h=s.slice(0);i.forEach((J,W)=>{h[J]=Math.ceil((c[J]-a[J])/o[J])});let C={dims:h,dataType:e[0].dataType},u=Ct("output",e[0].dataType,h.length),k=He("input",e[0].dataType,e[0].dims.length),B=De.size(h),R=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:o.length}],z=[{type:12,data:B},{type:12,data:a},{type:6,data:p},{type:12,data:o},...Mt(e[0].dims,h)],ne=J=>` + ${J.registerUniforms(R).declareVariables(k,u)} + ${f(k,u,s)} + ${J.mainStart()} + ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${u.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${u.setByOffset("global_idx",k.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${a.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:ne,getRunData:()=>({outputs:[C],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:z})}},xe=(e,t)=>{fp(e.inputs,t);let s=Qd(e.inputs,t);e.compute(q(e.inputs,s),{inputs:[0]})},$e=e=>{let t=e.starts,s=e.ends,n=e.axes;return jt({starts:t,ends:s,axes:n})}}),rt,ot,_t,kt,Zt=y(()=>{Ot(),$t(),is(),jr(),qt(),rt=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ot=(e,t)=>{let s=e.inputs[0],n=s.dims,i=De.size(n),o=n.length,a=De.normalizeAxis(t.axis,o),c=ant),h[a]=o-1,h[o-1]=a,p=e.compute(cr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let C=p.dims,u=C[o-1],k=i/u,B=Gt(u),R=u/B,z=64;k===1&&(z=256);let ne=(Ie,nt)=>nt===4?`max(max(${Ie}.x, ${Ie}.y), max(${Ie}.z, ${Ie}.w))`:nt===2?`max(${Ie}.x, ${Ie}.y)`:nt===3?`max(max(${Ie}.x, ${Ie}.y), ${Ie}.z)`:Ie,J=He("x",p.dataType,p.dims,B),W=Ct("result",p.dataType,p.dims,B),ue=J.type.value,he=ds(p.dataType)==="f32"?`var threadMax = ${ue}(-3.402823e+38f);`:`var threadMax = ${ue}(-65504.0h);`,be=Ie=>` + var rowMaxShared : ${ue}; + var rowSumShared : ${ue}; + var threadShared : array<${ue}, ${z}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${ue} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${ue}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Ie.registerUniform("packedCols","i32").declareVariables(J,W)} + ${Ie.mainStart(z)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${z}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${he} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${ue}(${ne("threadShared[0]",B)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${ue}(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 = ${ue}(${js("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};${z}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:C,dataType:p.dataType}],dispatchGroup:{x:k},programUniforms:[{type:6,data:R}]}),getShaderSource:be},{inputs:[p],outputs:[c?-1:0]})[0];c&&e.compute(cr(Be,h),{inputs:[Be]})},_t=(e,t)=>{rt(e.inputs),ot(e,t)},kt=e=>jt({axis:e.axis})}),Wt,Dt,At,bs,Ht,Qt=y(()=>{Ot(),$t(),qt(),Wt=e=>Array.from(e.getBigInt64Array(),Number),Dt=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Wt(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},At=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Wt(e[1]),i=At(s,n),o=De.size(i),a=e[0].dataType,c=He("input",a,s.length),p=Ct("output",a,i.length),h=C=>` + const inputShape = ${c.indices(...s)}; + ${C.registerUniform("output_size","u32").declareVariables(c,p)} + ${C.mainStart()} + ${C.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:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...Mt(e[0].dims,i)]}),getShaderSource:h}},Ht=e=>{Dt(e.inputs),e.compute(bs(e.inputs),{inputs:[0]})}}),ps,ys,es,Us=y(()=>{Ot(),$t(),qt(),ps=(e,t,s,n,i)=>{let o=Ct("output_data",i,s.length,4),a=He("a_data",t[1].dataType,t[1].dims.length,4),c=He("b_data",t[2].dataType,t[2].dims.length,4),p=He("c_data",t[0].dataType,t[0].dims.length,4),h,C=(u,k,B)=>`select(${k}, ${u}, ${B})`;if(!n)h=o.setByOffset("global_idx",C(a.getByOffset("global_idx"),c.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let u=(k,B,R="")=>{let z=`a_data[index_a${B}][component_a${B}]`,ne=`b_data[index_b${B}][component_b${B}]`,J=`bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`;return` + let output_indices${B} = ${o.offsetToIndices(`global_idx * 4u + ${B}u`)}; + let offset_a${B} = ${a.broadcastedIndicesToOffset(`output_indices${B}`,o)}; + let offset_b${B} = ${c.broadcastedIndicesToOffset(`output_indices${B}`,o)}; + let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`,o)}; + 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; + ${k}[${B}] = ${R}(${C(z,ne,J)}); + `};i===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,o)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},ys=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,i=e[1].dataType,o=!(De.areEqual(t,s)&&De.areEqual(s,n)),a=t,c=De.size(t);if(o){let h=Js.calcShape(Js.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");a=h,c=De.size(a)}let p=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>ps(h,e,a,o,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:p},...Mt(n,t,s,a)]})}},es=e=>{e.compute(ys(e.inputs))}}),zs,Fs=y(()=>{pc(),Zi(),hc(),mc(),fc(),_c(),su(),Mc(),Mu(),vc(),ku(),xc(),Tc(),Pc(),Bp(),Vn(),Ec(),kc(),sd(),Jo(),Ac(),Ic(),Fc(),Pd(),fs(),hd(),Od(),Rc(),Nc(),Rp(),Np(),ri(),jp(),mp(),yn(),Le(),Zt(),_d(),Qt(),jr(),wo(),Us(),zs=new Map([["Abs",[ml]],["Acos",[no]],["Acosh",[fl]],["Add",[Gl]],["ArgMax",[qi,Qi]],["ArgMin",[ol,Qi]],["Asin",[_l]],["Asinh",[io]],["Atan",[gl]],["Atanh",[wl]],["Attention",[ul]],["AveragePool",[Bd,zd]],["BatchNormalization",[to]],["BiasAdd",[hl]],["BiasSplitGelu",[Vl]],["Cast",[yl,oo]],["Ceil",[vl]],["Clip",[bl]],["Concat",[eu,tu]],["Conv",[Vo,Ro]],["ConvTranspose",[yu,Ko]],["Cos",[ao]],["Cosh",[xl]],["CumSum",[vu,xu]],["DepthToSpace",[Eu,Cu]],["DequantizeLinear",[Kd,Hd]],["Div",[Kl]],["Einsum",[Ou,Du]],["Elu",[lo,Bn]],["Equal",[Mo]],["Erf",[Tl]],["Exp",[uo]],["Expand",[jn]],["FastGelu",[Ru]],["Floor",[Pl]],["FusedConv",[Vo,Ro]],["Gather",[Vu,ju]],["GatherElements",[Cc,gi]],["GatherBlockQuantized",[qu,Qu]],["GatherND",[Wu,Gu]],["Gelu",[El]],["Gemm",[td,ed]],["GlobalAveragePool",[Nd,Rd]],["GlobalMaxPool",[Bc,Ud]],["Greater",[Ql]],["GreaterOrEqual",[vo]],["GridSample",[ud,Yo]],["GroupQueryAttention",[na]],["HardSigmoid",[Al,ho]],["InstanceNormalization",[yd]],["LayerNormalization",[vd]],["LeakyRelu",[co,Bn]],["Less",[Xl]],["LessOrEqual",[Yl]],["Log",[Bl]],["MatMul",[Td]],["MatMulNBits",[kd,Sd]],["MaxPool",[jd,Vd]],["Mul",[Hl]],["MultiHeadAttention",[Zo,cd]],["Neg",[kl]],["Not",[Cl]],["Pad",[ua]],["Pow",[ql]],["QuickGelu",[Nl,Bn]],["Range",[Uc]],["Reciprocal",[po]],["ReduceMin",[sl]],["ReduceMean",[Za]],["ReduceMax",[Gi]],["ReduceSum",[Ki]],["ReduceProd",[rl]],["ReduceL1",[Wi]],["ReduceL2",[el]],["ReduceLogSum",[il]],["ReduceLogSumExp",[tl]],["ReduceSumSquare",[nl]],["Relu",[Sl]],["Resize",[dp,cp]],["RotaryEmbedding",[Kt]],["ScatterND",[Hc,Kc]],["Sigmoid",[$l]],["Sin",[Il]],["Sinh",[mo]],["Slice",[xe,$e]],["SkipLayerNormalization",[Zs]],["Split",[ta,fd]],["Sqrt",[Fl]],["Softmax",[_t,kt]],["Sub",[bo]],["Tan",[Ol]],["Tanh",[Dl]],["ThresholdedRelu",[zl,Bn]],["Tile",[Ht]],["Transpose",[Ia,Li]],["Where",[es]]])}),Bs,nr=y(()=>{We(),Te(),qt(),Bs=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,n,i){Ue(e.programInfo.name);let o=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}});i&&c.push({binding:c.length,resource:i});let p=o.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){Ue(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let i=ka(t,this.backend.device.limits),o=e.getShaderSource(i),a=`${n.join(` +`)} +${i.additionalImplementations} +${o}`,c=s.createShaderModule({code:a,label:e.name});as("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:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&s<=i&&n<=i)return[t,s,n];let o=t*s*n,a=Math.ceil(Math.sqrt(o));if(a>i){if(a=Math.ceil(Math.cbrt(o)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),mr,_a,lr,Ar,Gn,Xd=y(()=>{We(),Ot(),Te(),Y(),Ms(),Fs(),nr(),mr=(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+`:${mr(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},lr=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ar=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]}},Gn=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let s=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},i=o=>t.features.has(o)&&s.push(o)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new Ar(this.device),this.adapterInfo=new lr(t.info||await t.requestAdapterInfo()),this.gpuDataManager=Yt(this),this.programManager=new Bs(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,gn(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.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;Ue(),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=k);let R=Number(k-this.queryTimeBase),z=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(R)||!Number.isSafeInteger(z))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:C.map(ne=>({dims:ne.dims,dataType:fr(ne.dataType)})),outputsMetadata:u.map(ne=>({dims:ne.dims,dataType:fr(ne.dataType)})),kernelId:o,kernelType:c,kernelName:p,programName:h,startTime:R,endTime:z});else{let ne="";C.forEach((W,ue)=>{ne+=`input[${ue}]: [${W.dims}] | ${fr(W.dataType)}, `});let J="";u.forEach((W,ue)=>{J+=`output[${ue}]: [${W.dims}] | ${fr(W.dataType)}, `}),console.log(`[profiling] kernel "${o}|${c}|${p}|${h}" ${ne}${J}execution time: ${z-R} ns`)}Ke("GPU",`${h}::${k}::${B}`)}e.unmap(),this.pendingQueries.delete(e)}),ze()}run(e,t,s,n,i,o){Ue(e.name);let a=[];for(let W=0;Wue):s;if(C.length!==c.length)throw new Error(`Output size ${C.length} must be equal to ${c.length}.`);let u=[],k=[];for(let W=0;W=o)throw new Error(`Invalid output index: ${C[W]}`);if(C[W]===-3)continue;let ue=C[W]===-1,he=C[W]===-2,be=ue||he?i(c[W].dataType,c[W].dims):n(C[W],c[W].dataType,c[W].dims);if(u.push(be),be.data===0)continue;let Be=this.gpuDataManager.get(be.data);if(!Be)throw new Error(`no GPU data for output: ${be.data}`);if(ue&&this.temporaryData.push(Be),he){let Ie=this.kernelPersistentData.get(this.currentKernelId);Ie||(Ie=[],this.kernelPersistentData.set(this.currentKernelId,Ie)),Ie.push(Be)}k.push(Be)}if(a.length!==t.length||k.length!==u.length){if(k.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 W=0,ue=[];h.forEach(Ie=>{let nt=typeof Ie.data=="number"?[Ie.data]:Ie.data;if(nt.length===0)return;let dt=Ie.type===10?2:4,Et,zt;Ie.type===10?(zt=nt.length>4?16:nt.length>2?8:nt.length*dt,Et=nt.length>4?16:dt*nt.length):(zt=nt.length<=2?nt.length*dt:16,Et=16),W=Math.ceil(W/zt)*zt,ue.push(W);let It=Ie.type===10?8:4;W+=nt.length>4?Math.ceil(nt.length/It)*Et:nt.length*dt});let he=16;W=Math.ceil(W/he)*he;let be=new ArrayBuffer(W);h.forEach((Ie,nt)=>{let dt=ue[nt],Et=typeof Ie.data=="number"?[Ie.data]:Ie.data;if(Ie.type===6)new Int32Array(be,dt,Et.length).set(Et);else if(Ie.type===12)new Uint32Array(be,dt,Et.length).set(Et);else if(Ie.type===10)new Uint16Array(be,dt,Et.length).set(Et);else if(Ie.type===1)new Float32Array(be,dt,Et.length).set(Et);else throw new Error(`Unsupported uniform type: ${fr(Ie.type)}`)});let Be=this.gpuDataManager.create(W,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Be.buffer,0,be,0,W),this.gpuDataManager.release(Be.id),B={offset:0,size:W,buffer:Be.buffer}}let R=this.programManager.normalizeDispatchGroupSize(p),z=R[1]===1&&R[2]===1,ne=_a(e,t,z),J=this.programManager.getArtifact(ne);if(J||(J=this.programManager.build(e,R),this.programManager.setArtifact(ne,J),as("info",()=>`[artifact] key: ${ne}, programName: ${e.name}`)),h&&J.uniformVariablesInfo){if(h.length!==J.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${J.uniformVariablesInfo.length}, got ${h.length} in program "${J.programInfo.name}".`);for(let W=0;W`[ProgramManager] run "${e.name}" (key=${ne}) with ${R[0]}x${R[1]}x${R[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let W={kernelId:this.currentKernelId,programName:J.programInfo.name,inputTensorViews:t,outputTensorViews:u};this.pendingKernels.push(W),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(W)}return this.programManager.run(J,a,k,R,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 i=zs.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],s]};this.kernels.set(t,o)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,o=n.kernelName,a=n.kernelEntry,c=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),as("info",()=>`[WebGPU] Start to run kernel "[${i}] ${o}"...`);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 "[${i}] ${o}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${i}] ${o}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let o=i.get(t),a=this.gpuDataManager.registerExternalBuffer(s,n,o);return i.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 pt(this,e,t);return M(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(){as("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(){as("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){as("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()}}}),xi,Mn,_p,ws,Os,Ir,sn,bn,ga=y(()=>{Te(),xi=1,Mn=()=>xi++,_p=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ws=(e,t)=>{let s=_p.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,i)=>n*i)*s/8):0},Os=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 ws(this.dataType,this.tensorShape)}destroy(){as("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((n,i)=>n===s[i])}},Ir=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,n){if(this.wrapper){if(this.wrapper.canReuseTensor(e,t,s))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==ws(t,s))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,s,i,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else as("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()}},sn=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Mn();return this.tensorTrackersById.set(e,new Ir(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){as("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(this.backend.currentContext,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){as("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 i=Mn(),o=new Os({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(i,new Ir(this,o)),this.externalTensors.add(o),i}async getCachedTensor(e,t,s,n,i){let o=this.backend.currentSessionId,a=this.backend.currentContext;for(let[p,h]of this.freeTensors.entries())if(h.canReuseTensor(a,e,t)){as("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let C=this.freeTensors.splice(p,1)[0];return C.sessionId=o,C}as("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let c=await a.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:i});return new Os({sessionId:o,context:a,tensor:c,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},bn=(...e)=>new sn(...e)}),Ti,wa,ya,Vp=y(()=>{Ot(),br(),Y(),ga(),Te(),Ti=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),wa=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((i,o)=>i===n[o]&&e[i]===t[i])},ya=class{constructor(e){this.tensorManager=bn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],gn(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=>wa(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(i=>i.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){as("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let i=Ti.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,s,n)}uploadTensor(e,t){if(!gs().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");as("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 M(s,t)}}registerMLTensor(e,t,s){let n=Ti.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,s);return as("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,s,n,i,o){if(!o)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let c=o.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(i.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return as("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,h)}flush(){}}}),Ma={};T(Ma,{init:()=>Yd});var vn,ba,Yd,Jd=y(()=>{Ot(),Xd(),Te(),$t(),Vp(),vn=class mf{constructor(t,s,n,i){this.module=t,this.dataType=s,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=De.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=De.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=De.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=De.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(De.size(t)!==De.size(this.dims))throw new Error("Invalid new shape");return new mf(this.module,this.dataType,this.data,t)}},ba=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,i=s/e.PTR_SIZE,o=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*i++,o));let a=Number(e.getValue(n*i++,o));this.outputCount=Number(e.getValue(n*i++,o)),this.customDataOffset=Number(e.getValue(n*i++,"*")),this.customDataSize=Number(e.getValue(n*i++,o));let c=[];for(let p=0;ptypeof a=="number"?this.inputs[a]:a)??this.inputs,n=t?.outputs??[],i=(a,c,p)=>new vn(this.module,c,this.output(a,p),p),o=(a,c)=>{let p=ar(a,c);if(!p)throw new Error(`Unsupported data type: ${a}`);let h=p>0?this.backend.gpuDataManager.create(p).id:0;return new vn(this.module,a,h,c)};return this.backend.run(e,s,n,i,o,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,i=n===4?"i32":"i64",o=this.module.stackAlloc((1+t.length)*n);this.module.setValue(o,t.length,i);for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=new Gn;await o.initialize(s,n),i("webgpu",[o,a=>o.alloc(Number(a)),a=>o.free(a),(a,c,p,h=!1)=>{if(h)as("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(c)}, size=${Number(p)}`),o.memcpy(Number(a),Number(c));else{as("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(c)}, size=${Number(p)}`);let C=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(p));o.upload(Number(c),C)}},async(a,c,p)=>{as("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${c}, size=${p}`),await o.download(Number(a),()=>t.HEAPU8.subarray(Number(c)>>>0,Number(c+p)>>>0))},(a,c,p)=>o.createKernel(a,Number(c),p,t.UTF8ToString(t._JsepGetNodeName(Number(c)))),a=>o.releaseKernel(a),(a,c,p,h)=>{as("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${c}`);let C=new ba(t,o,Number(c));return o.computeKernel(Number(a),C,h)},()=>o.captureBegin(),()=>o.captureEnd(),()=>o.replay()])}else{let o=new ya(s);i("webnn",[o,()=>o.reserveTensorId(),a=>o.releaseTensorId(a),async(a,c,p,h)=>o.ensureTensor(a,c,p,h),(a,c)=>{o.uploadTensor(a,c)},async(a,c)=>o.downloadTensor(a,c)])}}}),Pi,Zd,ec,rn,nn,ur,Up,Wp,Gp,Kp,Hp,qp,Ch=y(()=>{Jn(),Zn(),Ot(),br(),cn(),In(),Pi=(e,t)=>{gs()._OrtInit(e,t)!==0&&ns("Can't initialize onnxruntime.")},Zd=async e=>{Pi(e.wasm.numThreads,Xr(e.logLevel))},ec=async(e,t)=>{{let s=(Jd(),x(Ma)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!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",gs(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",gs(),e)}}},rn=new Map,nn=e=>{let t=gs(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,i,i+n)!==0&&ns("Can't get session input/output count.");let o=n===4?"i32":"i64";return[Number(t.getValue(i,o)),Number(t.getValue(i+n,o))]}finally{t.stackRestore(s)}},ur=e=>{let t=gs(),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]},Up=async(e,t)=>{let s,n,i=gs();Array.isArray(e)?[s,n]=e:e.buffer===i.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=ur(e);let o=0,a=0,c=0,p=[],h=[],C=[];try{if([a,p]=An(t),t?.externalData&&i.mountExternalData){let W=[];for(let ue of t.externalData){let he=typeof ue=="string"?ue:ue.path;W.push(_n(typeof ue=="string"?ue:ue.data).then(be=>{i.mountExternalData(he,be)}))}await Promise.all(W)}for(let W of t?.executionProviders??[])if((typeof W=="string"?W:W.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof W!="string"){let ue=W,he=ue?.context,be=ue?.gpuDevice,Be=ue?.deviceType,Ie=ue?.powerPreference;he?i.currentContext=he:be?i.currentContext=await i.jsepCreateMLContext(be):i.currentContext=await i.jsepCreateMLContext({deviceType:Be,powerPreference:Ie})}else i.currentContext=await i.jsepCreateMLContext();break}o=await i._OrtCreateSession(s,n,a),o===0&&ns("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.jsepRegisterMLContext(o,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[u,k]=nn(o),B=!!t?.enableGraphCapture,R=[],z=[],ne=[];for(let W=0;WW==="gpu-buffer"||W==="ml-tensor")&&(c=i._OrtCreateBinding(o),c===0&&ns("Can't create IO binding."),J={handle:c,outputPreferredLocations:ne,outputPreferredLocationsEncoded:ne.map(W=>fn(W))}),rn.set(o,[o,h,C,J,B,!1]),[o,R,z]}catch(u){throw h.forEach(k=>i._OrtFree(k)),C.forEach(k=>i._OrtFree(k)),c!==0&&i._OrtReleaseBinding(c)!==0&&ns("Can't release IO binding."),o!==0&&i._OrtReleaseSession(o)!==0&&ns("Can't release session."),u}finally{i._free(s),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&ns("Can't release session options."),p.forEach(u=>i._free(u)),i.unmountExternalData?.()}},Wp=e=>{let t=gs(),s=rn.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,o,a,c]=s;a&&(c&&t._OrtClearBoundOutputs(a.handle)!==0&&ns("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&ns("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),i.forEach(p=>t._OrtFree(p)),o.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n)!==0&&ns("Can't release session."),rn.delete(e)},Gp=(e,t,s,n,i,o=!1)=>{if(!e){t.push(0);return}let a=gs(),c=a.PTR_SIZE,p=e[0],h=e[1],C=e[3],u,k;if(p==="string"&&(C==="gpu-buffer"||C==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&C!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(C==="gpu-buffer"){let z=e[2].gpuBuffer;k=ar(Rr(p),h);let ne=a.jsepRegisterBuffer;if(!ne)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');u=ne(n,i,z,k)}else if(C==="ml-tensor"){let z=e[2].mlTensor;k=ar(Rr(p),h);let ne=a.jsepRegisterMLTensor;if(!ne)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');u=ne(z,Rr(p),h)}else{let z=e[2];if(Array.isArray(z)){k=c*z.length,u=a._malloc(k),s.push(u);for(let ne=0;nea.setValue(R+J*c,ne,c===4?"i32":"i64"));let z=a._OrtCreateTensor(Rr(p),u,k,R,h.length,fn(C));z===0&&ns(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(z)}finally{a.stackRestore(B)}},Kp=async(e,t,s,n,i,o)=>{let a=gs(),c=a.PTR_SIZE,p=rn.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],C=p[1],u=p[2],k=p[3],B=p[4],R=p[5],z=t.length,ne=n.length,J=0,W=[],ue=[],he=[],be=[],Be=a.stackSave(),Ie=a.stackAlloc(z*c),nt=a.stackAlloc(z*c),dt=a.stackAlloc(ne*c),Et=a.stackAlloc(ne*c);try{a.jsepOnRunStart?.(h),[J,W]=zr(o);for(let ht=0;hter*Ss,1);Xt=fr(ut);let xn=k?.outputPreferredLocations[n[ht]];if(Xt==="string"){if(xn==="gpu-buffer"||xn==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let er=[];for(let Ss=0;Ss0){let er=a.jsepGetBuffer;if(!er)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ss=er(Ut),ir=ar(ut,xs);if(ir===void 0||!hn(Xt))throw new Error(`Unsupported data type: ${Xt}`);ts=!0,It.push([Xt,vs,{gpuBuffer:Ss,download:a.jsepCreateDownloader(Ss,ir,Xt),dispose:()=>{a._OrtReleaseTensor(Jt)!==0&&ns("Can't release tensor.")}},"gpu-buffer"])}else if(xn==="ml-tensor"&&xs>0){let er=a.jsepEnsureTensor;if(!er)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ar(ut,xs)===void 0||!mn(Xt))throw new Error(`Unsupported data type: ${Xt}`);let Ss=await er(Ut,ut,vs,!1);ts=!0,It.push([Xt,vs,{mlTensor:Ss,download:a.jsepCreateMLTensorDownloader(Ut,Xt),dispose:()=>{a.jsepReleaseTensorId(Ut),a._OrtReleaseTensor(Jt)}},"ml-tensor"])}else{let er=pn(Xt),Ss=new er(xs);new Uint8Array(Ss.buffer,Ss.byteOffset,Ss.byteLength).set(a.HEAPU8.subarray(Ut,Ut+Ss.byteLength)),It.push([Xt,vs,Ss,"cpu"])}}finally{a.stackRestore(Vt),Xt==="string"&&Ut&&a._free(Ut),ts||a._OrtReleaseTensor(Jt)}}return k&&!B&&(a._OrtClearBoundOutputs(k.handle)!==0&&ns("Can't clear bound outputs."),rn.set(e,[h,C,u,k,B,!1])),It}finally{a.stackRestore(Be),ue.forEach(zt=>a._OrtReleaseTensor(zt)),he.forEach(zt=>a._OrtReleaseTensor(zt)),be.forEach(zt=>a._free(zt)),J!==0&&a._OrtReleaseRunOptions(J),W.forEach(zt=>a._free(zt))}},Hp=e=>{let t=gs(),s=rn.get(e);if(!s)throw new Error("invalid session id");let n=s[0],i=t._OrtEndProfiling(n);i===0&&ns("Can't get an profile file name."),t._OrtFree(i)},qp=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Kn,Fr,va,tc,sc,gp,Qp,wp,Ei,Ci,kh,Sh,$h,Ah,Ih,Fh,Oh,Dh,Lh=y(()=>{We(),Ch(),br(),Lr(),Kn=()=>!!F.wasm.proxy&&typeof document<"u",va=!1,tc=!1,sc=!1,wp=new Map,Ei=(e,t)=>{let s=wp.get(e);s?s.push(t):wp.set(e,[t])},Ci=()=>{if(va||!tc||sc||!Fr)throw new Error("worker not ready")},kh=e=>{switch(e.data.type){case"init-wasm":va=!1,e.data.err?(sc=!0,Qp[1](e.data.err)):(tc=!0,Qp[0]()),gp&&(URL.revokeObjectURL(gp),gp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=wp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Sh=async()=>{if(!tc){if(va)throw new Error("multiple calls to 'initWasm()' detected.");if(sc)throw new Error("previous call to 'initWasm()' failed.");if(va=!0,Kn())return new Promise((e,t)=>{Fr?.terminate(),qr().then(([s,n])=>{try{Fr=n,Fr.onerror=o=>t(o),Fr.onmessage=kh,Qp=[e,t];let i={type:"init-wasm",in:F};!i.in.wasm.wasmPaths&&(s||import.meta.url?.startsWith("file:"))&&(i.in.wasm.wasmPaths={wasm:new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href}),Fr.postMessage(i),gp=s}catch(i){t(i)}},t)});try{await dn(F.wasm),await Zd(F),tc=!0}catch(e){throw sc=!0,e}finally{va=!1}}},$h=async e=>{if(Kn())return Ci(),new Promise((t,s)=>{Ei("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:F}};Fr.postMessage(n)});await ec(F,e)},Ah=async e=>Kn()?(Ci(),new Promise((t,s)=>{Ei("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};Fr.postMessage(n,[e.buffer])})):ur(e),Ih=async(e,t)=>{if(Kn()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ci(),new Promise((s,n)=>{Ei("create",[s,n]);let i={type:"create",in:{model:e,options:{...t}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),Fr.postMessage(i,o)})}else return Up(e,t)},Fh=async e=>{if(Kn())return Ci(),new Promise((t,s)=>{Ei("release",[t,s]);let n={type:"release",in:e};Fr.postMessage(n)});Wp(e)},Oh=async(e,t,s,n,i,o)=>{if(Kn()){if(s.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ci(),new Promise((a,c)=>{Ei("run",[a,c]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:o}};Fr.postMessage(h,qp(p))})}else return Kp(e,t,s,n,i,o)},Dh=async e=>{if(Kn())return Ci(),new Promise((t,s)=>{Ei("end-profiling",[t,s]);let n={type:"end-profiling",in:e};Fr.postMessage(n)});Hp(e)}}),Xp,zh,Bh,Mf=y(()=>{We(),Lh(),Ot(),qe(),In(),Xp=(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()}`)}},zh=e=>{switch(e[3]){case"cpu":return new te(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!hn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:i}=e[2];return te.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!mn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:i}=e[2];return te.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Bh=class{async fetchModelAndCopyToWasmMemory(e){return Ah(await _n(e))}async loadModel(e,t){Ue();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Ih(s,t),ze()}async dispose(){return Fh(this.sessionId)}async run(e,t,s){Ue();let n=[],i=[];Object.entries(e).forEach(u=>{let k=u[0],B=u[1],R=this.inputNames.indexOf(k);if(R===-1)throw new Error(`invalid input '${k}'`);n.push(B),i.push(R)});let o=[],a=[];Object.entries(t).forEach(u=>{let k=u[0],B=u[1],R=this.outputNames.indexOf(k);if(R===-1)throw new Error(`invalid output '${k}'`);o.push(B),a.push(R)});let c=n.map((u,k)=>Xp(u,()=>`input "${this.inputNames[i[k]]}"`)),p=o.map((u,k)=>u?Xp(u,()=>`output "${this.outputNames[a[k]]}"`):null),h=await Oh(this.sessionId,i,c,a,p,s),C={};for(let u=0;uJp,initializeFlags:()=>Yp,wasmBackend:()=>Nh});var Yp,Jp,Nh,bf=y(()=>{We(),Lh(),Mf(),Yp=()=>{if((typeof F.wasm.initTimeout!="number"||F.wasm.initTimeout<0)&&(F.wasm.initTimeout=0),F.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 F.wasm.proxy!="boolean"&&(F.wasm.proxy=!1),typeof F.wasm.trace!="boolean"&&(F.wasm.trace=!1),typeof F.wasm.numThreads!="number"||!Number.isInteger(F.wasm.numThreads)||F.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)F.wasm.numThreads=1;else{let e=typeof navigator>"u"?j("node:os").cpus().length:navigator.hardwareConcurrency;F.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jp=class{async init(e){Yp(),await Sh(),await $h(e)}async createInferenceSessionHandler(e,t){let s=new Bh;return await s.loadModel(e,t),Promise.resolve(s)}},Nh=new Jp});We(),We(),We();var vf="1.21.0-dev.20250114-228dd16893",xf=Se;{let e=(bf(),x(Rh)).wasmBackend;K("webgpu",e,5),K("webnn",e,5),K("cpu",e,10),K("wasm",e,10)}Object.defineProperty(F.versions,"web",{value:vf,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":(ke,A,r)=>{var g;r.r(A),r.d(A,{Tensor:()=>j.Tensor,createInferenceSession:()=>oe,deviceToExecutionProviders:()=>K,isONNXProxy:()=>H,isONNXTensor:()=>V});var $=r("./src/env.js"),N=r("?2ce3"),Z=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),j=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"}}),T=[];let b,x;const v=Symbol.for("onnxruntime");if(v in globalThis)x=globalThis[v];else if($.apis.IS_NODE_ENV){switch(x=N??(g||(g=r.t(N,2))),process.platform){case"win32":T.push("dml");break;case"linux":process.arch==="x64"&&T.push("cuda");break}T.push("cpu"),b=["cpu"]}else x=Z,$.apis.IS_WEBNN_AVAILABLE&&T.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),$.apis.IS_WEBGPU_AVAILABLE&&T.push("webgpu"),T.push("wasm"),b=["wasm"];const L=x.InferenceSession;function K(I=null){if(!I)return b;switch(I){case"auto":return T;case"gpu":return T.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(T.includes(I))return[y[I]??I];throw new Error(`Unsupported device: "${I}". Should be one of: ${T.join(", ")}.`)}let se=null;async function oe(I,S,w){se&&await se;const P=L.create(I,S);se??=P;const F=await P;return F.config=w,F}function V(I){return I instanceof x.Tensor}const U=x?.env;U?.wasm&&(U.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${$.env.version}/dist/`,U.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(U.wasm.numThreads=1)),U?.webgpu&&(U.webgpu.powerPreference="high-performance");function H(){return U?.wasm?.proxy}$.env.backends.onnx=U},"./src/base/feature_extraction_utils.js":(ke,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>Z,validate_audio_inputs:()=>j});var g=r("./src/utils/constants.js"),$=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class Z extends $.Callable{constructor(T){super(),this.config=T}static async from_pretrained(T,b){const x=await(0,N.getModelJSON)(T,g.FEATURE_EXTRACTOR_NAME,!0,b);return new this(x)}}function j(y,T){if(!(y instanceof Float32Array||y instanceof Float64Array))throw new Error(`${T} 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":(ke,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>I,center_to_corners_format:()=>x,post_process_instance_segmentation:()=>H,post_process_object_detection:()=>v,post_process_panoptic_segmentation:()=>U,post_process_semantic_segmentation:()=>L});var g=r("./src/utils/generic.js"),$=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/utils/image.js");var Z=r("./src/utils/core.js"),j=r("./src/utils/hub.js"),y=r("./src/utils/constants.js");function T(S,w,P=0,F=null){const ae=S/w;let ie=(0,N.bankers_round)(ae)*w;return F!==null&&ie>F&&(ie=Math.floor(ae)*w),iew&&X.push(Ee)}else{let Ee=(0,N.max)(_e.data)[1];if(Ee===re-1||(de=(0,N.softmax)(_e.data),de[Ee]Xe*Ce[(ee+1)%2])),Ae.boxes.push(Oe),Ae.classes.push(Ee),Ae.scores.push(de[Ee])}}Me.push(Ae)}return Me}function L(S,w=null){const P=S.logits,F=P.dims[0];if(w!==null&&w.length!==F)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ae=[];for(let ie=0;ieCe[X]&&(Ce[X]=_e[X],Ae[X]=je)}const Pe=new Array(ge.dims[0]);for(let je=0;jeje!==void 0);ae.push({segmentation:pe,labels:Je})}return ae}function K(S,w,P,F){const ae=[],ie=[],ye=[];for(let ge=0;geP&&(ae.push(Me),ie.push(Ae),ye.push(pe))}return[ae,ie,ye]}function se(S,w,P,F=.5,ae=.8){const ie=[];let ye=0,ge=0;const re=w[P].data;for(let pe=0;pe=F&&++ge;let Me=ye>0&&ge>0;return Me&&(Me=ye/ge>ae),[Me,ie]}function oe(S,w,P,F,ae,ie=null,ye=null){const[ge,re]=ye??S[0].dims,Me=new $.Tensor("int32",new Int32Array(ge*re),[ge,re]),pe=[];if(ye!==null)for(let je=0;jeAe[de]&&(Ce[de]=je,Ae[de]=X[de])}let Pe=0;const Je=Me.data;for(let je=0;je200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(S,w)/Math.min(S,w)}`);let ie=Math.round(S/P)*P,ye=Math.round(w/P)*P;if(ie*ye>ae){const ge=Math.sqrt(S*w/ae);ie=Math.floor(S/ge/P)*P,ye=Math.floor(w/ge/P)*P}else if(ie*yeie?Me=Math.floor(ie*re/ae):ie>ae&&(re=Math.floor(ae*Me/ie)),await w.resize(Me,re,{resample:F}))}async crop_margin(w,P=200){const F=w.clone().grayscale(),ae=(0,N.min)(F.data)[0],ye=(0,N.max)(F.data)[0]-ae;if(ye===0)return w;const ge=P/255;let re=F.width,Me=F.height,pe=0,Ce=0;const Ae=F.data;for(let Pe=0;Pethis.preprocess(ie)));return{pixel_values:(0,$.stack)(F.map(ie=>ie.pixel_values),0),original_sizes:F.map(ie=>ie.original_size),reshaped_input_sizes:F.map(ie=>ie.reshaped_input_size)}}static async from_pretrained(w,P){const F=await(0,j.getModelJSON)(w,y.IMAGE_PROCESSOR_NAME,!0,P);return new this(F)}}},"./src/base/processing_utils.js":(ke,A,r)=>{r.r(A),r.d(A,{Processor:()=>Z});var g=r("./src/utils/constants.js"),$=r("./src/utils/generic.js"),N=r("./src/utils/hub.js");class Z extends $.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(y,T){super(),this.config=y,this.components=T}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,T={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(y,{tokenize:!1,...T})}batch_decode(...y){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...y)}decode(...y){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...y)}async _call(y,...T){for(const b of[this.image_processor,this.feature_extractor,this.tokenizer])if(b)return b(y,...T);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(y,T){const[b,x]=await Promise.all([this.uses_processor_config?(0,N.getModelJSON)(y,g.PROCESSOR_NAME,!0,T):{},Promise.all(this.classes.filter(v=>v in this).map(async v=>{const L=await this[v].from_pretrained(y,T);return[v.replace(/_class$/,""),L]})).then(Object.fromEntries)]);return new this(b,x)}}},"./src/configs.js":(ke,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>T,PretrainedConfig:()=>y,getKeyValueShapes:()=>j});var g=r("./src/utils/core.js"),$=r("./src/utils/hub.js");async function N(b,x){return await(0,$.getModelJSON)(b,"config.json",!0,x)}function Z(b){const x={};let v={};switch(b.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":v=Z(b.text_config);break;case"moondream1":v=Z(b.phi_config);break;case"musicgen":v=Z(b.decoder);break;case"multi_modality":v=Z(b.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":x.num_heads="n_head",x.num_layers="n_layer",x.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":x.num_heads="num_attention_heads",x.num_layers="num_hidden_layers",x.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":x.num_heads="num_key_value_heads",x.num_layers="num_hidden_layers",x.hidden_size="hidden_size",x.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":x.num_heads="num_key_value_heads",x.num_layers="num_hidden_layers",x.dim_kv="head_dim";break;case"openelm":x.num_heads="num_kv_heads",x.num_layers="num_transformer_layers",x.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":x.num_heads="num_heads",x.num_layers="num_layers",x.hidden_size="hidden_size";break;case"bloom":x.num_heads="n_head",x.num_layers="n_layer",x.hidden_size="hidden_size";break;case"mpt":x.num_heads="n_heads",x.num_layers="n_layers",x.hidden_size="d_model";break;case"exaone":x.num_heads="num_key_value_heads",x.num_layers="num_layers",x.dim_kv="head_dim",x.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":x.num_decoder_layers="num_decoder_layers",x.num_decoder_heads="num_heads",x.decoder_dim_kv="d_kv",x.num_encoder_layers="num_layers",x.num_encoder_heads="num_heads",x.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":x.num_decoder_layers="decoder_layers",x.num_decoder_heads="decoder_attention_heads",x.decoder_hidden_size="d_model",x.num_encoder_layers="encoder_layers",x.num_encoder_heads="encoder_attention_heads",x.encoder_hidden_size="d_model";break;case"speecht5":x.num_decoder_layers="decoder_layers",x.num_decoder_heads="decoder_attention_heads",x.decoder_hidden_size="hidden_size",x.num_encoder_layers="encoder_layers",x.num_encoder_heads="encoder_attention_heads",x.encoder_hidden_size="hidden_size";break;case"trocr":x.num_encoder_layers=x.num_decoder_layers="decoder_layers",x.num_encoder_heads=x.num_decoder_heads="decoder_attention_heads",x.encoder_hidden_size=x.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":x.num_encoder_layers=x.num_decoder_layers="num_hidden_layers",x.num_encoder_heads=x.num_decoder_heads="num_attention_heads",x.encoder_hidden_size=x.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const K=Z(b.decoder),se="num_decoder_layers"in K,oe=(0,g.pick)(b,["model_type","is_encoder_decoder"]);return se?(oe.num_decoder_layers=K.num_decoder_layers,oe.num_decoder_heads=K.num_decoder_heads,oe.decoder_hidden_size=K.decoder_hidden_size,oe.num_encoder_layers=K.num_encoder_layers,oe.num_encoder_heads=K.num_encoder_heads,oe.encoder_hidden_size=K.encoder_hidden_size):(oe.num_layers=K.num_layers,oe.num_heads=K.num_heads,oe.hidden_size=K.hidden_size),oe}const L={...v,...(0,g.pick)(b,["model_type","multi_query","is_encoder_decoder"])};for(const K in x)L[K]=b[x[K]];return L}function j(b,{prefix:x="past_key_values",batch_size:v=1}={}){const L={},K=b.normalized_config;if(K.is_encoder_decoder&&"num_encoder_heads"in K&&"num_decoder_heads"in K){const se=K.encoder_dim_kv??K.encoder_hidden_size/K.num_encoder_heads,oe=K.decoder_dim_kv??K.decoder_hidden_size/K.num_decoder_heads,V=[v,K.num_encoder_heads,0,se],U=[v,K.num_decoder_heads,0,oe];for(let H=0;H{r.r(A),r.d(A,{apis:()=>oe,env:()=>w});var g=r("?569f"),$=r("?3f59"),N=r("?154a");const Z="3.3.1",j=typeof window<"u"&&typeof window.document<"u",y=typeof self<"u"&&self.constructor?.name==="DedicatedWorkerGlobalScope",T=typeof self<"u"&&"caches"in self,b=typeof navigator<"u"&&"gpu"in navigator,x=typeof navigator<"u"&&"ml"in navigator,v=typeof process<"u",L=v&&process?.release?.name==="node",K=!P(g),se=!P($),oe=Object.freeze({IS_BROWSER_ENV:j,IS_WEBWORKER_ENV:y,IS_WEB_CACHE_AVAILABLE:T,IS_WEBGPU_AVAILABLE:b,IS_WEBNN_AVAILABLE:x,IS_PROCESS_AVAILABLE:v,IS_NODE_ENV:L,IS_FS_AVAILABLE:K,IS_PATH_AVAILABLE:se}),V=K&&se;let U="./";if(V){const F=Object(import.meta).url;F?U=$.dirname($.dirname(N.fileURLToPath(F))):typeof __dirname<"u"&&(U=$.dirname(__dirname))}const H=V?$.join(U,"/.cache/"):null,I="/models/",S=V?$.join(U,I):I,w={version:Z,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(j||y),localModelPath:S,useFS:K,useBrowserCache:T,useFSCache:K,cacheDir:H,useCustomCache:!1,customCache:null};function P(F){return Object.keys(F).length===0}},"./src/generation/configuration_utils.js":(ke,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>$});var g=r("./src/utils/core.js");class ${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(Z){Object.assign(this,(0,g.pick)(Z,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(ke,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>V,ForcedBOSTokenLogitsProcessor:()=>y,ForcedEOSTokenLogitsProcessor:()=>T,LogitsProcessor:()=>N,LogitsProcessorList:()=>j,LogitsWarper:()=>Z,MinLengthLogitsProcessor:()=>K,MinNewTokensLengthLogitsProcessor:()=>se,NoBadWordsLogitsProcessor:()=>oe,NoRepeatNGramLogitsProcessor:()=>v,RepetitionPenaltyLogitsProcessor:()=>L,SuppressTokensAtBeginLogitsProcessor:()=>b,TemperatureLogitsWarper:()=>U,TopKLogitsWarper:()=>I,TopPLogitsWarper:()=>H,WhisperTimeStampLogitsProcessor:()=>x});var g=r("./src/utils/generic.js");r("./src/utils/tensor.js");var $=r("./src/utils/maths.js");class N extends g.Callable{_call(w,P){throw Error("`_call` should be implemented in a subclass")}}class Z extends g.Callable{_call(w,P){throw Error("`_call` should be implemented in a subclass")}}class j extends g.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,P){let F=P;for(const ae of this.processors)F=ae(w,F);return F}[Symbol.iterator](){return this.processors.values()}}class y extends N{constructor(w){super(),this.bos_token_id=w}_call(w,P){for(let F=0;F=1&&ie[ie.length-1]>=this.timestamp_begin,ge=ie.length<2||ie[ie.length-2]>=this.timestamp_begin;if(ye&&(ge?ae.subarray(this.timestamp_begin).fill(-1/0):ae.subarray(0,this.eos_token_id).fill(-1/0)),w[F].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Ce=this.timestamp_begin+this.max_initial_timestamp_index;ae.subarray(Ce+1).fill(-1/0)}const re=(0,$.log_softmax)(ae),Me=Math.log(re.subarray(this.timestamp_begin).map(Math.exp).reduce((Ce,Ae)=>Ce+Ae)),pe=(0,$.max)(re.subarray(0,this.timestamp_begin))[0];Me>pe&&ae.subarray(0,this.timestamp_begin).fill(-1/0)}return P}}class v extends N{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const P=w.length,F=[];for(let ie=0;ie1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,P){if(P.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 ${P.dims[0]} for the logits and ${w.length} for the input ids.`);const F=w.length,ae=P.slice([0,F],null),ie=P.slice([F,P.dims[0]],null);for(let ye=0;ye1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(F)||F<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${F}`);this.top_p=w,this.filter_value=P,this.min_tokens_to_keep=F}}class I extends Z{constructor(w,{filter_value:P=-1/0,min_tokens_to_keep:F=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,F),this.filter_value=P}}},"./src/generation/logits_sampler.js":(ke,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>Z});var g=r("./src/utils/generic.js"),$=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class Z extends g.Callable{constructor(x){super(),this.generation_config=x}async _call(x){return this.sample(x)}async sample(x){throw Error("sample should be implemented in subclasses.")}getLogits(x,v){let L=x.dims.at(-1),K=x.data;if(v===-1)K=K.slice(-L);else{let se=v*L;K=K.slice(se,se+L)}return K}randomSelect(x){let v=0;for(let K=0;K1)return new T(x);if(x.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${x.num_return_sequences}.`);return new j(x)}}class j extends Z{async sample(x){const v=(0,N.max)(x.data)[1];return[[BigInt(v),0]]}}class y extends Z{async sample(x){let v=x.dims.at(-1);this.generation_config.top_k>0&&(v=Math.min(this.generation_config.top_k,v));const[L,K]=await(0,$.topk)(x,v),se=(0,N.softmax)(L.data);return Array.from({length:this.generation_config.num_beams},()=>{const oe=this.randomSelect(se);return[K.data[oe],Math.log(se[oe])]})}}class T extends Z{async sample(x){let v=x.dims.at(-1);this.generation_config.top_k>0&&(v=Math.min(this.generation_config.top_k,v));const[L,K]=await(0,$.topk)(x,v),se=(0,N.softmax)(L.data);return Array.from({length:this.generation_config.num_beams},(oe,V)=>[K.data[V],Math.log(se[V])])}}},"./src/generation/stopping_criteria.js":(ke,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>j,InterruptableStoppingCriteria:()=>y,MaxLengthCriteria:()=>Z,StoppingCriteria:()=>$,StoppingCriteriaList:()=>N});var g=r("./src/utils/generic.js");class $ extends g.Callable{_call(b,x){throw Error("StoppingCriteria needs to be subclassed")}}class N extends g.Callable{constructor(){super(),this.criteria=[]}push(b){this.criteria.push(b)}extend(b){b instanceof N?b=b.criteria:b instanceof $&&(b=[b]),this.criteria.push(...b)}_call(b,x){const v=new Array(b.length).fill(!1);for(const L of this.criteria){const K=L(b,x);for(let se=0;sex.length>=this.max_length)}}class j extends ${constructor(b){super(),Array.isArray(b)||(b=[b]),this.eos_token_id=b}_call(b,x){return b.map(v=>{const L=v.at(-1);return this.eos_token_id.some(K=>L==K)})}}class y extends ${constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(b,x){return new Array(b.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(ke,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>Z,TextStreamer:()=>y,WhisperTextStreamer:()=>T});var g=r("./src/utils/core.js"),$=r("./src/tokenizers.js"),N=r("./src/env.js");class Z{put(x){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const j=N.apis.IS_PROCESS_AVAILABLE?b=>process.stdout.write(b):b=>console.log(b);class y extends Z{constructor(x,{skip_prompt:v=!1,callback_function:L=null,token_callback_function:K=null,skip_special_tokens:se=!0,decode_kwargs:oe={},...V}={}){super(),this.tokenizer=x,this.skip_prompt=v,this.callback_function=L??j,this.token_callback_function=K,this.decode_kwargs={skip_special_tokens:se,...oe,...V},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(x){if(x.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=x[0];this.token_callback_function?.(v),this.token_cache=(0,g.mergeArrays)(this.token_cache,v);const L=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let K;L.endsWith(` +`)?(K=L.slice(this.print_len),this.token_cache=[],this.print_len=0):L.length>0&&(0,$.is_chinese_char)(L.charCodeAt(L.length-1))?(K=L.slice(this.print_len),this.print_len+=K.length):(K=L.slice(this.print_len,L.lastIndexOf(" ")+1),this.print_len+=K.length),this.on_finalized_text(K,!1)}end(){let x;this.token_cache.length>0?(x=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):x="",this.next_tokens_are_prompt=!0,this.on_finalized_text(x,!0)}on_finalized_text(x,v){x.length>0&&this.callback_function?.(x),v&&this.callback_function===j&&N.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}}class T extends y{constructor(x,{skip_prompt:v=!1,callback_function:L=null,token_callback_function:K=null,on_chunk_start:se=null,on_chunk_end:oe=null,on_finalize:V=null,time_precision:U=.02,skip_special_tokens:H=!0,decode_kwargs:I={}}={}){super(x,{skip_prompt:v,skip_special_tokens:H,callback_function:L,token_callback_function:K,decode_kwargs:I}),this.timestamp_begin=x.timestamp_begin,this.on_chunk_start=se,this.on_chunk_end=oe,this.on_finalize=V,this.time_precision=U,this.waiting_for_timestamp=!1}put(x){if(x.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const v=x[0];if(v.length===1){const L=Number(v[0])-this.timestamp_begin;if(L>=0){const K=L*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,x=[[]]}}return super.put(x)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(ke,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>Fi,ASTModel:()=>Sa,ASTPreTrainedModel:()=>qt,AlbertForMaskedLM:()=>as,AlbertForQuestionAnswering:()=>Ln,AlbertForSequenceClassification:()=>gn,AlbertModel:()=>Dn,AlbertPreTrainedModel:()=>Nr,AutoModel:()=>Vc,AutoModelForAudioClassification:()=>qd,AutoModelForAudioFrameClassification:()=>op,AutoModelForCTC:()=>np,AutoModelForCausalLM:()=>Np,AutoModelForDepthEstimation:()=>dp,AutoModelForDocumentQuestionAnswering:()=>ap,AutoModelForImageClassification:()=>Yc,AutoModelForImageFeatureExtraction:()=>pp,AutoModelForImageMatting:()=>lp,AutoModelForImageSegmentation:()=>Jc,AutoModelForImageToImage:()=>up,AutoModelForMaskGeneration:()=>rp,AutoModelForMaskedLM:()=>qc,AutoModelForNormalEstimation:()=>cp,AutoModelForObjectDetection:()=>tp,AutoModelForPoseEstimation:()=>jp,AutoModelForQuestionAnswering:()=>Qc,AutoModelForSemanticSegmentation:()=>Zc,AutoModelForSeq2SeqLM:()=>Wc,AutoModelForSequenceClassification:()=>Uc,AutoModelForSpeechSeq2Seq:()=>Gc,AutoModelForTextToSpectrogram:()=>Kc,AutoModelForTextToWaveform:()=>Hc,AutoModelForTokenClassification:()=>Rp,AutoModelForUniversalSegmentation:()=>ep,AutoModelForVision2Seq:()=>Xc,AutoModelForXVector:()=>ip,AutoModelForZeroShotObjectDetection:()=>sp,BartForConditionalGeneration:()=>rs,BartForSequenceClassification:()=>Yt,BartModel:()=>pt,BartPretrainedModel:()=>yt,BaseModelOutput:()=>Re,BeitForImageClassification:()=>Zl,BeitModel:()=>Jl,BeitPreTrainedModel:()=>xo,BertForMaskedLM:()=>Ke,BertForQuestionAnswering:()=>ze,BertForSequenceClassification:()=>Ne,BertForTokenClassification:()=>Ue,BertModel:()=>ve,BertPreTrainedModel:()=>te,BlenderbotForConditionalGeneration:()=>Xs,BlenderbotModel:()=>De,BlenderbotPreTrainedModel:()=>Js,BlenderbotSmallForConditionalGeneration:()=>Hs,BlenderbotSmallModel:()=>Es,BlenderbotSmallPreTrainedModel:()=>kr,BloomForCausalLM:()=>El,BloomModel:()=>Pl,BloomPreTrainedModel:()=>uo,CLIPModel:()=>ja,CLIPPreTrainedModel:()=>Jr,CLIPSegForImageSegmentation:()=>qa,CLIPSegModel:()=>Ha,CLIPSegPreTrainedModel:()=>Ni,CLIPTextModel:()=>uc,CLIPTextModelWithProjection:()=>Va,CLIPVisionModel:()=>dc,CLIPVisionModelWithProjection:()=>Ua,CamembertForMaskedLM:()=>Kr,CamembertForQuestionAnswering:()=>Hr,CamembertForSequenceClassification:()=>Pr,CamembertForTokenClassification:()=>Er,CamembertModel:()=>Lt,CamembertPreTrainedModel:()=>Mr,CausalLMOutput:()=>yn,CausalLMOutputWithPast:()=>fp,ChineseCLIPModel:()=>gr,ChineseCLIPPreTrainedModel:()=>cc,ClapAudioModelWithProjection:()=>ld,ClapModel:()=>od,ClapPreTrainedModel:()=>wi,ClapTextModelWithProjection:()=>ad,CodeGenForCausalLM:()=>ol,CodeGenModel:()=>Hi,CodeGenPreTrainedModel:()=>ri,CohereForCausalLM:()=>mc,CohereModel:()=>hl,CoherePreTrainedModel:()=>so,ConvBertForMaskedLM:()=>Nt,ConvBertForQuestionAnswering:()=>ms,ConvBertForSequenceClassification:()=>ss,ConvBertForTokenClassification:()=>Ts,ConvBertModel:()=>ft,ConvBertPreTrainedModel:()=>st,ConvNextForImageClassification:()=>Mc,ConvNextModel:()=>Vo,ConvNextPreTrainedModel:()=>jo,ConvNextV2ForImageClassification:()=>fu,ConvNextV2Model:()=>bc,ConvNextV2PreTrainedModel:()=>Uo,DPTForDepthEstimation:()=>Rn,DPTModel:()=>Lo,DPTPreTrainedModel:()=>Do,DebertaForMaskedLM:()=>Cr,DebertaForQuestionAnswering:()=>or,DebertaForSequenceClassification:()=>Dr,DebertaForTokenClassification:()=>Lr,DebertaModel:()=>qr,DebertaPreTrainedModel:()=>dr,DebertaV2ForMaskedLM:()=>Ft,DebertaV2ForQuestionAnswering:()=>dn,DebertaV2ForSequenceClassification:()=>Ys,DebertaV2ForTokenClassification:()=>Cn,DebertaV2Model:()=>vt,DebertaV2PreTrainedModel:()=>it,DecisionTransformerModel:()=>Md,DecisionTransformerPreTrainedModel:()=>Ic,DeiTForImageClassification:()=>ko,DeiTModel:()=>Co,DeiTPreTrainedModel:()=>wn,DepthAnythingForDepthEstimation:()=>zo,DepthAnythingPreTrainedModel:()=>au,DepthProForDepthEstimation:()=>cu,DepthProPreTrainedModel:()=>du,DetrForObjectDetection:()=>tu,DetrForSegmentation:()=>su,DetrModel:()=>eu,DetrObjectDetectionOutput:()=>Vr,DetrPreTrainedModel:()=>ai,DetrSegmentationOutput:()=>Zr,Dinov2ForImageClassification:()=>Go,Dinov2Model:()=>_u,Dinov2PreTrainedModel:()=>Wo,Dinov2WithRegistersForImageClassification:()=>Ho,Dinov2WithRegistersModel:()=>gu,Dinov2WithRegistersPreTrainedModel:()=>Ko,DistilBertForMaskedLM:()=>cn,DistilBertForQuestionAnswering:()=>ns,DistilBertForSequenceClassification:()=>Ls,DistilBertForTokenClassification:()=>Qr,DistilBertModel:()=>br,DistilBertPreTrainedModel:()=>gs,DonutSwinModel:()=>mu,DonutSwinPreTrainedModel:()=>No,EfficientNetForImageClassification:()=>md,EfficientNetModel:()=>hd,EfficientNetPreTrainedModel:()=>Zo,ElectraForMaskedLM:()=>tr,ElectraForQuestionAnswering:()=>Ns,ElectraForSequenceClassification:()=>Tr,ElectraForTokenClassification:()=>Gr,ElectraModel:()=>As,ElectraPreTrainedModel:()=>Ps,EsmForMaskedLM:()=>kn,EsmForSequenceClassification:()=>Sn,EsmForTokenClassification:()=>$n,EsmModel:()=>Jn,EsmPreTrainedModel:()=>zr,ExaoneForCausalLM:()=>al,ExaoneModel:()=>ni,ExaonePreTrainedModel:()=>Xi,FalconForCausalLM:()=>id,FalconModel:()=>nd,FalconPreTrainedModel:()=>Xo,FastViTForImageClassification:()=>fc,FastViTModel:()=>Vl,FastViTPreTrainedModel:()=>yo,Florence2ForConditionalGeneration:()=>La,Florence2PreTrainedModel:()=>Da,GLPNForDepthEstimation:()=>Ro,GLPNModel:()=>pi,GLPNPreTrainedModel:()=>Bo,GPT2LMHeadModel:()=>Xa,GPT2Model:()=>Qa,GPT2PreTrainedModel:()=>ji,GPTBigCodeForCausalLM:()=>il,GPTBigCodeModel:()=>nl,GPTBigCodePreTrainedModel:()=>Ki,GPTJForCausalLM:()=>rl,GPTJModel:()=>sl,GPTJPreTrainedModel:()=>Gi,GPTNeoForCausalLM:()=>Za,GPTNeoModel:()=>yr,GPTNeoPreTrainedModel:()=>Ui,GPTNeoXForCausalLM:()=>tl,GPTNeoXModel:()=>el,GPTNeoXPreTrainedModel:()=>Wi,Gemma2ForCausalLM:()=>_l,Gemma2Model:()=>fl,Gemma2PreTrainedModel:()=>no,GemmaForCausalLM:()=>ml,GemmaModel:()=>ls,GemmaPreTrainedModel:()=>ro,GraniteForCausalLM:()=>pl,GraniteModel:()=>hc,GranitePreTrainedModel:()=>to,GroundingDinoForObjectDetection:()=>yu,GroundingDinoPreTrainedModel:()=>wu,GroupViTModel:()=>jl,GroupViTPreTrainedModel:()=>wo,HieraForImageClassification:()=>$o,HieraModel:()=>nu,HieraPreTrainedModel:()=>So,HubertForCTC:()=>Wu,HubertForSequenceClassification:()=>Gu,HubertModel:()=>Uu,HubertPreTrainedModel:()=>Bp,IJepaForImageClassification:()=>Ol,IJepaModel:()=>Fl,IJepaPreTrainedModel:()=>mo,Idefics3ForConditionalGeneration:()=>zi,Idefics3PreTrainedModel:()=>Ra,ImageMattingOutput:()=>Wn,JAISLMHeadModel:()=>Ja,JAISModel:()=>Ya,JAISPreTrainedModel:()=>Vi,JinaCLIPModel:()=>si,JinaCLIPPreTrainedModel:()=>ti,JinaCLIPTextModel:()=>Ri,JinaCLIPVisionModel:()=>wr,LlamaForCausalLM:()=>pc,LlamaModel:()=>Qi,LlamaPreTrainedModel:()=>qi,LlavaForConditionalGeneration:()=>ei,LlavaOnevisionForConditionalGeneration:()=>Fa,LlavaPreTrainedModel:()=>jr,LongT5ForConditionalGeneration:()=>Fe,LongT5Model:()=>me,LongT5PreTrainedModel:()=>ce,M2M100ForConditionalGeneration:()=>Nn,M2M100Model:()=>hi,M2M100PreTrainedModel:()=>ku,MBartForCausalLM:()=>Ks,MBartForConditionalGeneration:()=>jt,MBartForSequenceClassification:()=>is,MBartModel:()=>Gs,MBartPreTrainedModel:()=>Ms,MPNetForMaskedLM:()=>Xr,MPNetForQuestionAnswering:()=>fn,MPNetForSequenceClassification:()=>hn,MPNetForTokenClassification:()=>mn,MPNetModel:()=>pn,MPNetPreTrainedModel:()=>ar,MT5ForConditionalGeneration:()=>wt,MT5Model:()=>gt,MT5PreTrainedModel:()=>Ye,MarianMTModel:()=>Cu,MarianModel:()=>Eu,MarianPreTrainedModel:()=>qo,MaskFormerForInstanceSegmentation:()=>ci,MaskFormerModel:()=>hu,MaskFormerPreTrainedModel:()=>pu,MaskedLMOutput:()=>Qs,MgpstrForSceneTextRecognition:()=>Td,MgpstrModelOutput:()=>Fc,MgpstrPreTrainedModel:()=>xd,MistralForCausalLM:()=>$r,MistralModel:()=>vr,MistralPreTrainedModel:()=>sd,MobileBertForMaskedLM:()=>Zn,MobileBertForQuestionAnswering:()=>fr,MobileBertForSequenceClassification:()=>Rr,MobileBertModel:()=>An,MobileBertPreTrainedModel:()=>Br,MobileLLMForCausalLM:()=>zn,MobileLLMModel:()=>ll,MobileLLMPreTrainedModel:()=>Yi,MobileNetV1ForImageClassification:()=>_d,MobileNetV1Model:()=>fd,MobileNetV1PreTrainedModel:()=>ta,MobileNetV2ForImageClassification:()=>ra,MobileNetV2Model:()=>gd,MobileNetV2PreTrainedModel:()=>sa,MobileNetV3ForImageClassification:()=>ia,MobileNetV3Model:()=>Ac,MobileNetV3PreTrainedModel:()=>na,MobileNetV4ForImageClassification:()=>yd,MobileNetV4Model:()=>wd,MobileNetV4PreTrainedModel:()=>oa,MobileViTForImageClassification:()=>Kl,MobileViTModel:()=>Gl,MobileViTPreTrainedModel:()=>hr,MobileViTV2ForImageClassification:()=>ql,MobileViTV2Model:()=>Hl,MobileViTV2PreTrainedModel:()=>Mo,ModelOutput:()=>Ve,ModernBertForMaskedLM:()=>mt,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>ct,ModernBertModel:()=>at,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>Oa,MoonshineForConditionalGeneration:()=>Ia,MoonshineModel:()=>cr,MoonshinePreTrainedModel:()=>Di,MptForCausalLM:()=>kl,MptModel:()=>Cl,MptPreTrainedModel:()=>co,MultiModalityCausalLM:()=>vd,MultiModalityPreTrainedModel:()=>bd,MusicgenForCausalLM:()=>$c,MusicgenForConditionalGeneration:()=>Mi,MusicgenModel:()=>Sc,MusicgenPreTrainedModel:()=>ea,NomicBertModel:()=>le,NomicBertPreTrainedModel:()=>O,OPTForCausalLM:()=>$l,OPTModel:()=>Sl,OPTPreTrainedModel:()=>po,Olmo2ForCausalLM:()=>cl,Olmo2Model:()=>dl,Olmo2PreTrainedModel:()=>eo,OlmoForCausalLM:()=>Zi,OlmoModel:()=>ul,OlmoPreTrainedModel:()=>Ji,OpenELMForCausalLM:()=>wl,OpenELMModel:()=>gl,OpenELMPreTrainedModel:()=>io,OwlViTForObjectDetection:()=>Xl,OwlViTModel:()=>Ql,OwlViTPreTrainedModel:()=>bo,Owlv2ForObjectDetection:()=>_c,Owlv2Model:()=>Yl,Owlv2PreTrainedModel:()=>vo,PaliGemmaForConditionalGeneration:()=>Ba,PaliGemmaPreTrainedModel:()=>za,PatchTSMixerForPrediction:()=>Sd,PatchTSMixerModel:()=>kd,PatchTSMixerPreTrainedModel:()=>aa,PatchTSTForPrediction:()=>Cd,PatchTSTModel:()=>Ed,PatchTSTPreTrainedModel:()=>Pd,Phi3ForCausalLM:()=>Tl,Phi3Model:()=>ii,Phi3PreTrainedModel:()=>lo,Phi3VForCausalLM:()=>pr,Phi3VPreTrainedModel:()=>Na,PhiForCausalLM:()=>Bn,PhiModel:()=>xl,PhiPreTrainedModel:()=>ao,PreTrainedModel:()=>ee,PretrainedMixin:()=>fs,PvtForImageClassification:()=>Ll,PvtModel:()=>_o,PvtPreTrainedModel:()=>oi,PyAnnoteForAudioFrameClassification:()=>Ou,PyAnnoteModel:()=>Fu,PyAnnotePreTrainedModel:()=>mi,QuestionAnsweringModelOutput:()=>Zs,Qwen2ForCausalLM:()=>Ml,Qwen2Model:()=>yl,Qwen2PreTrainedModel:()=>oo,Qwen2VLForConditionalGeneration:()=>vl,Qwen2VLPreTrainedModel:()=>bl,RTDetrForObjectDetection:()=>en,RTDetrModel:()=>To,RTDetrObjectDetectionOutput:()=>qs,RTDetrPreTrainedModel:()=>Ur,ResNetForImageClassification:()=>Ao,ResNetModel:()=>iu,ResNetPreTrainedModel:()=>li,RoFormerForMaskedLM:()=>Se,RoFormerForQuestionAnswering:()=>tt,RoFormerForSequenceClassification:()=>We,RoFormerForTokenClassification:()=>qe,RoFormerModel:()=>we,RoFormerPreTrainedModel:()=>Q,RobertaForMaskedLM:()=>_r,RobertaForQuestionAnswering:()=>Mt,RobertaForSequenceClassification:()=>ds,RobertaForTokenClassification:()=>Cs,RobertaModel:()=>sr,RobertaPreTrainedModel:()=>$t,SamImageSegmentationOutput:()=>Pu,SamModel:()=>Tu,SamPreTrainedModel:()=>vc,SapiensForDepthEstimation:()=>uu,SapiensForNormalEstimation:()=>yc,SapiensForSemanticSegmentation:()=>lu,SapiensPreTrainedModel:()=>di,SegformerForImageClassification:()=>dd,SegformerForSemanticSegmentation:()=>cd,SegformerModel:()=>rr,SegformerPreTrainedModel:()=>Jo,Seq2SeqLMOutput:()=>hp,SequenceClassifierOutput:()=>Kt,SiglipModel:()=>Wa,SiglipPreTrainedModel:()=>Bi,SiglipTextModel:()=>Ga,SiglipVisionModel:()=>Ka,SpeechT5ForSpeechToText:()=>kc,SpeechT5ForTextToSpeech:()=>Ju,SpeechT5HifiGan:()=>Zu,SpeechT5Model:()=>Cc,SpeechT5PreTrainedModel:()=>gi,SqueezeBertForMaskedLM:()=>In,SqueezeBertForQuestionAnswering:()=>On,SqueezeBertForSequenceClassification:()=>Fn,SqueezeBertModel:()=>_n,SqueezeBertPreTrainedModel:()=>Ot,StableLmForCausalLM:()=>Un,StableLmModel:()=>pd,StableLmPreTrainedModel:()=>yi,Starcoder2ForCausalLM:()=>rd,Starcoder2Model:()=>tn,Starcoder2PreTrainedModel:()=>Wr,StyleTextToSpeech2Model:()=>Yu,StyleTextToSpeech2PreTrainedModel:()=>Xu,Swin2SRForImageSuperResolution:()=>wc,Swin2SRModel:()=>ou,Swin2SRPreTrainedModel:()=>Oo,SwinForImageClassification:()=>Fo,SwinModel:()=>ui,SwinPreTrainedModel:()=>Io,T5ForConditionalGeneration:()=>Y,T5Model:()=>M,T5PreTrainedModel:()=>Te,TableTransformerForObjectDetection:()=>ru,TableTransformerModel:()=>Eo,TableTransformerObjectDetectionOutput:()=>gc,TableTransformerPreTrainedModel:()=>Po,TokenClassifierOutput:()=>Vs,TrOCRForCausalLM:()=>td,TrOCRPreTrainedModel:()=>ed,UniSpeechForCTC:()=>Lu,UniSpeechForSequenceClassification:()=>zu,UniSpeechModel:()=>Qo,UniSpeechPreTrainedModel:()=>fi,UniSpeechSatForAudioFrameClassification:()=>Pc,UniSpeechSatForCTC:()=>Bu,UniSpeechSatForSequenceClassification:()=>Ru,UniSpeechSatModel:()=>Tc,UniSpeechSatPreTrainedModel:()=>jn,ViTForImageClassification:()=>Il,ViTMAEModel:()=>Bl,ViTMAEPreTrainedModel:()=>zl,ViTMSNForImageClassification:()=>Nl,ViTMSNModel:()=>Rl,ViTMSNPreTrainedModel:()=>go,ViTModel:()=>Al,ViTPreTrainedModel:()=>ho,VisionEncoderDecoderModel:()=>Li,VitMatteForImageMatting:()=>Wl,VitMattePreTrainedModel:()=>Ul,VitPoseForPoseEstimation:()=>Dl,VitPosePreTrainedModel:()=>fo,VitsModel:()=>Yo,VitsModelOutput:()=>Qd,VitsPreTrainedModel:()=>ud,Wav2Vec2BertForCTC:()=>ju,Wav2Vec2BertForSequenceClassification:()=>Vu,Wav2Vec2BertModel:()=>Nu,Wav2Vec2BertPreTrainedModel:()=>_i,Wav2Vec2ForAudioFrameClassification:()=>Iu,Wav2Vec2ForCTC:()=>$u,Wav2Vec2ForSequenceClassification:()=>Au,Wav2Vec2Model:()=>Su,Wav2Vec2PreTrainedModel:()=>Sr,WavLMForAudioFrameClassification:()=>Ec,WavLMForCTC:()=>Hu,WavLMForSequenceClassification:()=>qu,WavLMForXVector:()=>Qu,WavLMModel:()=>Ku,WavLMPreTrainedModel:()=>Vn,WeSpeakerResNetModel:()=>xc,WeSpeakerResNetPreTrainedModel:()=>Du,WhisperForConditionalGeneration:()=>Aa,WhisperModel:()=>$a,WhisperPreTrainedModel:()=>Oi,XLMForQuestionAnswering:()=>Yr,XLMForSequenceClassification:()=>js,XLMForTokenClassification:()=>Tt,XLMModel:()=>Is,XLMPreTrainedModel:()=>Gt,XLMRobertaForMaskedLM:()=>Ea,XLMRobertaForQuestionAnswering:()=>ka,XLMRobertaForSequenceClassification:()=>Ii,XLMRobertaForTokenClassification:()=>Ca,XLMRobertaModel:()=>Ct,XLMRobertaPreTrainedModel:()=>He,XLMWithLMHeadModel:()=>ks,XVectorOutput:()=>mp,YolosForObjectDetection:()=>vu,YolosModel:()=>bu,YolosObjectDetectionOutput:()=>xu,YolosPreTrainedModel:()=>Mu});var g=r("./src/configs.js"),$=r("./src/backends/onnx.js"),N=r("./src/utils/dtypes.js"),Z=r("./src/utils/generic.js"),j=r("./src/utils/core.js"),y=r("./src/utils/hub.js"),T=r("./src/utils/constants.js"),b=r("./src/generation/logits_process.js"),x=r("./src/generation/configuration_utils.js"),v=r("./src/utils/tensor.js"),L=r("./src/utils/image.js"),K=r("./src/utils/maths.js"),se=r("./src/generation/stopping_criteria.js"),oe=r("./src/generation/logits_sampler.js"),V=r("./src/env.js"),U=r("./src/models/whisper/generation_whisper.js"),H=r("./src/models/whisper/common_whisper.js");const I={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},S=new Map,w=new Map,P=new Map;async function F(_,f,q){const xe=q.config?.["transformers.js_config"]??{};let $e=q.device??xe.device;$e&&typeof $e!="string"&&($e.hasOwnProperty(f)?$e=$e[f]:(console.warn(`device not specified for "${f}". Using the default device.`),$e=null));const Le=$e??(V.apis.IS_NODE_ENV?"cpu":"wasm"),rt=(0,$.deviceToExecutionProviders)(Le);let ot=q.dtype??xe.dtype;if(typeof ot!="string"&&(ot&&ot.hasOwnProperty(f)?ot=ot[f]:(ot=N.DEFAULT_DEVICE_DTYPE_MAPPING[Le]??N.DATA_TYPES.fp32,console.warn(`dtype not specified for "${f}". Using the default dtype (${ot}) for this device (${Le}).`))),ot===N.DATA_TYPES.auto){let es=xe.dtype;typeof es!="string"&&(es=es[f]),es&&es!==N.DATA_TYPES.auto&&N.DATA_TYPES.hasOwnProperty(es)?ot=es:ot=N.DEFAULT_DEVICE_DTYPE_MAPPING[Le]??N.DATA_TYPES.fp32}const _t=ot;if(N.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(_t)){if(_t===N.DATA_TYPES.fp16&&Le==="webgpu"&&!await(0,N.isWebGpuFp16Supported)())throw new Error(`The device (${Le}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_t}. Should be one of: ${Object.keys(N.DATA_TYPES).join(", ")}`);const kt=xe.kv_cache_dtype?typeof xe.kv_cache_dtype=="string"?xe.kv_cache_dtype:xe.kv_cache_dtype[_t]??"float32":void 0;if(kt&&!["float32","float16"].includes(kt))throw new Error(`Invalid kv_cache_dtype: ${kt}. Should be one of: float32, float16`);const Zt={dtype:_t,kv_cache_dtype:kt},Wt=N.DEFAULT_DTYPE_SUFFIX_MAPPING[_t],Dt=`${q.subfolder??""}/${f}${Wt}.onnx`,At={...q.session_options};At.executionProviders??=rt;const bs=xe.free_dimension_overrides;bs?At.freeDimensionOverrides??=bs:Le.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 Ht=(0,y.getModelFile)(_,Dt,!0,q),Qt=q.use_external_data_format??xe.use_external_data_format;let ps=[];if(Qt&&(Qt===!0||typeof Qt=="object"&&Qt.hasOwnProperty(f)&&Qt[f]===!0)){if(V.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const es=`${f}${Wt}.onnx_data`,Us=`${q.subfolder??""}/${es}`;ps.push(new Promise(async(zs,Fs)=>{const Bs=await(0,y.getModelFile)(_,Us,!0,q);zs({path:es,data:Bs})}))}else At.externalData!==void 0&&(ps=At.externalData.map(async es=>{if(typeof es.data=="string"){const Us=await(0,y.getModelFile)(_,es.data,!0,q);return{...es,data:Us}}return es}));if(ps.length>0&&(At.externalData=await Promise.all(ps)),Le==="webgpu"){const es=(0,g.getKeyValueShapes)(q.config,{prefix:"present"});if(Object.keys(es).length>0&&!(0,$.isONNXProxy)()){const Us={};for(const zs in es)Us[zs]="gpu-buffer";At.preferredOutputLocation=Us}}return{buffer:await Ht,session_options:At,session_config:Zt}}async function ae(_,f,q){return Object.fromEntries(await Promise.all(Object.keys(f).map(async xe=>{const{buffer:$e,session_options:Le,session_config:rt}=await F(_,f[xe],q),ot=await(0,$.createInferenceSession)($e,Le,rt);return[xe,ot]})))}async function ie(_,f,q){return Object.fromEntries(await Promise.all(Object.keys(f).map(async xe=>{const $e=await(0,y.getModelJSON)(_,f[xe],!1,q);return[xe,$e]})))}function ye(_,f){const q=Object.create(null),xe=[];for(const rt of _.inputNames){const ot=f[rt];if(!(ot instanceof v.Tensor)){xe.push(rt);continue}q[rt]=(0,$.isONNXProxy)()?ot.clone():ot}if(xe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${xe.join(", ")}.`);const $e=Object.keys(f).length,Le=_.inputNames.length;if($e>Le){let rt=Object.keys(f).filter(ot=>!_.inputNames.includes(ot));console.warn(`WARNING: Too many inputs were provided (${$e} > ${Le}). The following inputs will be ignored: "${rt.join(", ")}".`)}return q}async function ge(_,f){const q=ye(_,f);try{const xe=Object.fromEntries(Object.entries(q).map(([Le,rt])=>[Le,rt.ort_tensor]));let $e=await _.run(xe);return $e=re($e),$e}catch(xe){const $e=Object.fromEntries(Object.entries(q).map(([Le,{type:rt,dims:ot,data:_t}])=>[Le,{type:rt,dims:ot,data:_t}]));throw console.error(`An error occurred during model execution: "${xe}".`),console.error("Inputs given to model:",$e),xe}}function re(_){for(let f in _)(0,$.isONNXTensor)(_[f])?_[f]=new v.Tensor(_[f]):typeof _[f]=="object"&&re(_[f]);return _}function Me(_){if(_ instanceof v.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(f=>f.length!==_[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new v.Tensor("int64",BigInt64Array.from(_.flat().map(f=>BigInt(f))),[_.length,_[0].length])}else return new v.Tensor("int64",BigInt64Array.from(_.map(f=>BigInt(f))),[1,_.length])}function pe(_){return new v.Tensor("bool",[_],[1])}async function Ce(_,f){let{encoder_outputs:q,input_ids:xe,decoder_input_ids:$e,...Le}=f;if(!q){const ot=(0,j.pick)(f,_.sessions.model.inputNames);q=(await Ae(_,ot)).last_hidden_state}return Le.input_ids=$e,Le.encoder_hidden_states=q,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Le.encoder_attention_mask=f.attention_mask),await Pe(_,Le,!0)}async function Ae(_,f){const q=_.sessions.model,xe=(0,j.pick)(f,q.inputNames);if(q.inputNames.includes("inputs_embeds")&&!xe.inputs_embeds){if(!f.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");xe.inputs_embeds=await _.encode_text({input_ids:f.input_ids})}if(q.inputNames.includes("token_type_ids")&&!xe.token_type_ids){if(!xe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");xe.token_type_ids=(0,v.zeros_like)(xe.input_ids)}if(q.inputNames.includes("pixel_mask")&&!xe.pixel_mask){if(!xe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const $e=xe.pixel_values.dims;xe.pixel_mask=(0,v.ones)([$e[0],$e[2],$e[3]])}return await ge(q,xe)}async function Pe(_,f,q=!1){const xe=_.sessions[q?"decoder_model_merged":"model"],{past_key_values:$e,...Le}=f;if(xe.inputNames.includes("use_cache_branch")&&(Le.use_cache_branch=pe(!!$e)),xe.inputNames.includes("position_ids")&&Le.attention_mask&&!Le.position_ids){const ot=_.config.model_type==="paligemma"?1:0;Le.position_ids=X(Le,$e,ot)}_.addPastKeyValues(Le,$e);const rt=(0,j.pick)(Le,xe.inputNames);return await ge(xe,rt)}function Je({image_token_id:_,inputs_embeds:f,image_features:q,input_ids:xe,attention_mask:$e}){const Le=xe.tolist().map(kt=>kt.reduce((Zt,Wt,Dt)=>(Wt==_&&Zt.push(Dt),Zt),[])),rt=Le.reduce((kt,Zt)=>kt+Zt.length,0),ot=q.dims[0];if(rt!==ot)throw new Error(`Image features and image tokens do not match: tokens: ${rt}, features ${ot}`);let _t=0;for(let kt=0;ktLe.dims[1])){if($eot==_.config.image_token_index)){const ot=_.config.num_image_tokens;if(!ot)throw new Error("`num_image_tokens` is missing in the model configuration.");const _t=Le.dims[1]-($e-ot);q.input_ids=Le.slice(null,[-_t,null]),q.attention_mask=(0,v.ones)([1,$e+_t])}}}return q}function Ee(_,f,q,xe){return q.past_key_values&&(f=f.map($e=>[$e.at(-1)])),{...q,decoder_input_ids:Me(f)}}function Oe(_,...f){return _.config.is_encoder_decoder?Ee(_,...f):de(_,...f)}function Xe(_,f,q,xe){const $e=!!q.past_key_values;return xe.guidance_scale!==null&&xe.guidance_scale>1&&($e?q.input_ids=(0,v.cat)([q.input_ids,q.input_ids],0):(q.input_ids=(0,v.cat)([q.input_ids,(0,v.full_like)(q.input_ids,BigInt(xe.pad_token_id))],0),q.attention_mask=(0,v.cat)([q.attention_mask,(0,v.full_like)(q.attention_mask,0n)],0))),($e||!q.pixel_values)&&(q.pixel_values=(0,v.full)([0,0,3,384,384],1)),$e&&(q.images_seq_mask=new v.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),q.images_emb_mask=new v.Tensor("bool",new Array(0).fill(!1),[1,1,0])),q}class ee extends Z.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(f,q,xe){super(),this.config=f,this.sessions=q,this.configs=xe;const $e=P.get(this.constructor),Le=S.get($e);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Le){case I.DecoderOnly:this.can_generate=!0,this._forward=Pe,this._prepare_inputs_for_generation=de;break;case I.Seq2Seq:case I.Vision2Seq:case I.Musicgen:this.can_generate=!0,this._forward=Ce,this._prepare_inputs_for_generation=Ee;break;case I.EncoderDecoder:this._forward=Ce;break;case I.ImageTextToText:this.can_generate=!0,this._forward=je,this._prepare_inputs_for_generation=Oe;break;case I.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Oe;break;case I.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Xe;break;default:this._forward=Ae;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const f=[];for(const q of Object.values(this.sessions))q?.handler?.dispose&&f.push(q.handler.dispose());return await Promise.all(f)}static async from_pretrained(f,{progress_callback:q=null,config:xe=null,cache_dir:$e=null,local_files_only:Le=!1,revision:rt="main",model_file_name:ot=null,subfolder:_t="onnx",device:kt=null,dtype:Zt=null,use_external_data_format:Wt=null,session_options:Dt={}}={}){let At={progress_callback:q,config:xe,cache_dir:$e,local_files_only:Le,revision:rt,model_file_name:ot,subfolder:_t,device:kt,dtype:Zt,use_external_data_format:Wt,session_options:Dt};const bs=P.get(this),Ht=S.get(bs);xe=At.config=await g.AutoConfig.from_pretrained(f,At);let Qt;if(Ht===I.DecoderOnly)Qt=await Promise.all([ae(f,{model:At.model_file_name??"model"},At),ie(f,{generation_config:"generation_config.json"},At)]);else if(Ht===I.Seq2Seq||Ht===I.Vision2Seq)Qt=await Promise.all([ae(f,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},At),ie(f,{generation_config:"generation_config.json"},At)]);else if(Ht===I.MaskGeneration)Qt=await Promise.all([ae(f,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},At)]);else if(Ht===I.EncoderDecoder)Qt=await Promise.all([ae(f,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},At)]);else if(Ht===I.ImageTextToText){const ps={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};xe.is_encoder_decoder&&(ps.model="encoder_model"),Qt=await Promise.all([ae(f,ps,At),ie(f,{generation_config:"generation_config.json"},At)])}else if(Ht===I.Musicgen)Qt=await Promise.all([ae(f,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},At),ie(f,{generation_config:"generation_config.json"},At)]);else if(Ht===I.MultiModality)Qt=await Promise.all([ae(f,{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),ie(f,{generation_config:"generation_config.json"},At)]);else if(Ht===I.Phi3V)Qt=await Promise.all([ae(f,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},At),ie(f,{generation_config:"generation_config.json"},At)]);else{if(Ht!==I.EncoderOnly){const ps=bs??xe?.model_type;ps!=="custom"&&console.warn(`Model type for '${ps}' not found, assuming encoder-only architecture. Please report this at ${T.GITHUB_ISSUE_URL}.`)}Qt=await Promise.all([ae(f,{model:At.model_file_name??"model"},At)])}return new this(xe,...Qt)}async _call(f){return await this.forward(f)}async forward(f){return await this._forward(this,f)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(f){const q=new b.LogitsProcessorList;return f.temperature!==null&&f.temperature!==1&&q.push(new b.TemperatureLogitsWarper(f.temperature)),f.top_k!==null&&f.top_k!==0&&q.push(new b.TopKLogitsWarper(f.top_k)),f.top_p!==null&&f.top_p<1&&q.push(new b.TopPLogitsWarper(f.top_p)),q}_get_logits_processor(f,q,xe=null){const $e=new b.LogitsProcessorList;if(f.repetition_penalty!==null&&f.repetition_penalty!==1&&$e.push(new b.RepetitionPenaltyLogitsProcessor(f.repetition_penalty)),f.no_repeat_ngram_size!==null&&f.no_repeat_ngram_size>0&&$e.push(new b.NoRepeatNGramLogitsProcessor(f.no_repeat_ngram_size)),f.bad_words_ids!==null&&$e.push(new b.NoBadWordsLogitsProcessor(f.bad_words_ids,f.eos_token_id)),f.min_length!==null&&f.eos_token_id!==null&&f.min_length>0&&$e.push(new b.MinLengthLogitsProcessor(f.min_length,f.eos_token_id)),f.min_new_tokens!==null&&f.eos_token_id!==null&&f.min_new_tokens>0&&$e.push(new b.MinNewTokensLengthLogitsProcessor(q,f.min_new_tokens,f.eos_token_id)),f.forced_bos_token_id!==null&&$e.push(new b.ForcedBOSTokenLogitsProcessor(f.forced_bos_token_id)),f.forced_eos_token_id!==null&&$e.push(new b.ForcedEOSTokenLogitsProcessor(f.max_length,f.forced_eos_token_id)),f.begin_suppress_tokens!==null){const Le=q>1||f.forced_bos_token_id===null?q:q+1;$e.push(new b.SuppressTokensAtBeginLogitsProcessor(f.begin_suppress_tokens,Le))}return f.guidance_scale!==null&&f.guidance_scale>1&&$e.push(new b.ClassifierFreeGuidanceLogitsProcessor(f.guidance_scale)),xe!==null&&$e.extend(xe),$e}_prepare_generation_config(f,q,xe=x.GenerationConfig){const $e={...this.config};for(const rt of["decoder","generator","text_config"])rt in $e&&Object.assign($e,$e[rt]);const Le=new xe($e);return Object.assign(Le,this.generation_config??{}),f&&Object.assign(Le,f),q&&Object.assign(Le,(0,j.pick)(q,Object.getOwnPropertyNames(Le))),Le}_get_stopping_criteria(f,q=null){const xe=new se.StoppingCriteriaList;return f.max_length!==null&&xe.push(new se.MaxLengthCriteria(f.max_length,this.config.max_position_embeddings??null)),f.eos_token_id!==null&&xe.push(new se.EosTokenCriteria(f.eos_token_id)),q&&xe.extend(q),xe}_validate_model_class(){if(!this.can_generate){const f=[Od,vi,ua,la],q=P.get(this.constructor),xe=new Set,$e=this.config.model_type;for(const rt of f){const ot=rt.get($e);ot&&xe.add(ot[0])}let Le=`The current model class (${q}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw xe.size>0&&(Le+=` Please use the following class instead: ${[...xe].join(", ")}`),Error(Le)}}prepare_inputs_for_generation(...f){return this._prepare_inputs_for_generation(this,...f)}_update_model_kwargs_for_generation({generated_input_ids:f,outputs:q,model_inputs:xe,is_encoder_decoder:$e}){return xe.past_key_values=this.getPastKeyValues(q,xe.past_key_values),xe.input_ids=new v.Tensor("int64",f.flat(),[f.length,1]),$e||(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:f,bos_token_id:q,model_kwargs:xe}){const $e=(0,j.pick)(xe,this.forward_params),Le=this.main_input_name;if(Le in $e){if(f)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else $e[Le]=f;return{inputs_tensor:$e[Le],model_inputs:$e,model_input_name:Le}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:f,model_inputs:q,model_input_name:xe,generation_config:$e}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!q.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:ot,attention_mask:_t,...kt}=q,Zt=await this._prepare_inputs_embeds(q);q={...kt,...(0,j.pick)(Zt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Le}=await Ae(this,q);if($e.guidance_scale!==null&&$e.guidance_scale>1)Le=(0,v.cat)([Le,(0,v.full_like)(Le,0)],0),"attention_mask"in q&&(q.attention_mask=(0,v.cat)([q.attention_mask,(0,v.zeros_like)(q.attention_mask)],0));else if(q.decoder_input_ids){const rt=Me(q.decoder_input_ids).dims[0];if(rt!==Le.dims[0]){if(Le.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Le.dims[0]}) than the decoder inputs (${rt}).`);Le=(0,v.cat)(Array.from({length:rt},()=>Le),0)}}return q.encoder_outputs=Le,q}_prepare_decoder_input_ids_for_generation({batch_size:f,model_input_name:q,model_kwargs:xe,decoder_start_token_id:$e,bos_token_id:Le,generation_config:rt}){let{decoder_input_ids:ot,..._t}=xe;if(!(ot instanceof v.Tensor)){if(ot)Array.isArray(ot[0])||(ot=Array.from({length:f},()=>ot));else if($e??=Le,this.config.model_type==="musicgen")ot=Array.from({length:f*this.config.decoder.num_codebooks},()=>[$e]);else if(Array.isArray($e)){if($e.length!==f)throw new Error(`\`decoder_start_token_id\` expcted to have length ${f} but got ${$e.length}`);ot=$e}else ot=Array.from({length:f},()=>[$e]);ot=Me(ot)}return xe.decoder_attention_mask=(0,v.ones_like)(ot),{input_ids:ot,model_inputs:_t}}async generate({inputs:f=null,generation_config:q=null,logits_processor:xe=null,stopping_criteria:$e=null,streamer:Le=null,...rt}){this._validate_model_class(),q=this._prepare_generation_config(q,rt);let{inputs_tensor:ot,model_inputs:_t,model_input_name:kt}=this._prepare_model_inputs({inputs:f,model_kwargs:rt});const Zt=this.config.is_encoder_decoder;Zt&&("encoder_outputs"in _t||(_t=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ot,model_inputs:_t,model_input_name:kt,generation_config:q})));let Wt;Zt?{input_ids:Wt,model_inputs:_t}=this._prepare_decoder_input_ids_for_generation({batch_size:_t[kt].dims.at(0),model_input_name:kt,model_kwargs:_t,decoder_start_token_id:q.decoder_start_token_id,bos_token_id:q.bos_token_id,generation_config:q}):Wt=_t[kt];let Dt=Wt.dims.at(-1);q.max_new_tokens!==null&&(q.max_length=Dt+q.max_new_tokens);const At=this._get_logits_processor(q,Dt,xe),bs=this._get_stopping_criteria(q,$e),Ht=_t[kt].dims.at(0),Qt=oe.LogitsSampler.getSampler(q),ps=new Array(Ht).fill(0),ys=Wt.tolist();Le&&Le.put(ys);let es,Us={};for(;;){if(_t=this.prepare_inputs_for_generation(ys,_t,q),es=await this.forward(_t),q.output_attentions&&q.return_dict_in_generate){const lr=this.getAttentions(es);for(const Ar in lr)Ar in Us||(Us[Ar]=[]),Us[Ar].push(lr[Ar])}const Bs=es.logits.slice(null,-1,null),nr=At(ys,Bs),mr=[];for(let lr=0;lrlr))break;_t=this._update_model_kwargs_for_generation({generated_input_ids:mr,outputs:es,model_inputs:_t,is_encoder_decoder:Zt})}Le&&Le.end();const zs=this.getPastKeyValues(es,_t.past_key_values,!0),Fs=new v.Tensor("int64",ys.flat(),[ys.length,ys[0].length]);if(q.return_dict_in_generate)return{sequences:Fs,past_key_values:zs,...Us};for(const Bs of Object.values(es))Bs.location==="gpu-buffer"&&Bs.dispose();return Fs}getPastKeyValues(f,q,xe=!1){const $e=Object.create(null);for(const Le in f)if(Le.startsWith("present")){const rt=Le.replace("present","past_key_values"),ot=Le.includes("encoder");if(ot&&q?$e[rt]=q[rt]:$e[rt]=f[Le],q&&(!ot||xe)){const _t=q[rt];_t.location==="gpu-buffer"&&_t.dispose()}}return $e}getAttentions(f){const q={};for(const xe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const $e in f)$e.startsWith(xe)&&(xe in q||(q[xe]=[]),q[xe].push(f[$e]));return q}addPastKeyValues(f,q){if(q)Object.assign(f,q);else{const $e=(this.sessions.decoder_model_merged??this.sessions.model)?.config?.kv_cache_dtype??"float32",Le=$e==="float16"?new Uint16Array:[],rt=(f[this.main_input_name]??f.attention_mask)?.dims?.[0]??1,ot=(0,g.getKeyValueShapes)(this.config,{batch_size:rt});for(const _t in ot)f[_t]=new v.Tensor($e,Le,ot[_t])}}async encode_image({pixel_values:f}){const q=(await ge(this.sessions.vision_encoder,{pixel_values:f})).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 (${q.dims[1]}).`),this.config.num_image_tokens=q.dims[1]),q}async encode_text({input_ids:f}){return(await ge(this.sessions.embed_tokens,{input_ids:f})).inputs_embeds}}class Ve{}class Re extends Ve{constructor({last_hidden_state:f,hidden_states:q=null,attentions:xe=null}){super(),this.last_hidden_state=f,this.hidden_states=q,this.attentions=xe}}class te extends ee{}class ve extends te{}class Ke extends te{async _call(f){return new Qs(await super._call(f))}}class Ne extends te{async _call(f){return new Kt(await super._call(f))}}class Ue extends te{async _call(f){return new Vs(await super._call(f))}}class ze extends te{async _call(f){return new Zs(await super._call(f))}}class Ze extends ee{}class at extends Ze{}class mt extends Ze{async _call(f){return new Qs(await super._call(f))}}class lt extends Ze{async _call(f){return new Kt(await super._call(f))}}class ct extends Ze{async _call(f){return new Vs(await super._call(f))}}class O extends ee{}class le extends O{}class Q extends ee{}class we extends Q{}class Se extends Q{async _call(f){return new Qs(await super._call(f))}}class We extends Q{async _call(f){return new Kt(await super._call(f))}}class qe extends Q{async _call(f){return new Vs(await super._call(f))}}class tt extends Q{async _call(f){return new Zs(await super._call(f))}}class st extends ee{}class ft extends st{}class Nt extends st{async _call(f){return new Qs(await super._call(f))}}class ss extends st{async _call(f){return new Kt(await super._call(f))}}class Ts extends st{async _call(f){return new Vs(await super._call(f))}}class ms extends st{async _call(f){return new Zs(await super._call(f))}}class Ps extends ee{}class As extends Ps{}class tr extends Ps{async _call(f){return new Qs(await super._call(f))}}class Tr extends Ps{async _call(f){return new Kt(await super._call(f))}}class Gr extends Ps{async _call(f){return new Vs(await super._call(f))}}class Ns extends Ps{async _call(f){return new Zs(await super._call(f))}}class Mr extends ee{}class Lt extends Mr{}class Kr extends Mr{async _call(f){return new Qs(await super._call(f))}}class Pr extends Mr{async _call(f){return new Kt(await super._call(f))}}class Er extends Mr{async _call(f){return new Vs(await super._call(f))}}class Hr extends Mr{async _call(f){return new Zs(await super._call(f))}}class dr extends ee{}class qr extends dr{}class Cr extends dr{async _call(f){return new Qs(await super._call(f))}}class Dr extends dr{async _call(f){return new Kt(await super._call(f))}}class Lr extends dr{async _call(f){return new Vs(await super._call(f))}}class or extends dr{async _call(f){return new Zs(await super._call(f))}}class it extends ee{}class vt extends it{}class Ft extends it{async _call(f){return new Qs(await super._call(f))}}class Ys extends it{async _call(f){return new Kt(await super._call(f))}}class Cn extends it{async _call(f){return new Vs(await super._call(f))}}class dn extends it{async _call(f){return new Zs(await super._call(f))}}class gs extends ee{}class br extends gs{}class Ls extends gs{async _call(f){return new Kt(await super._call(f))}}class Qr extends gs{async _call(f){return new Vs(await super._call(f))}}class ns extends gs{async _call(f){return new Zs(await super._call(f))}}class cn extends gs{async _call(f){return new Qs(await super._call(f))}}class zr extends ee{}class Jn extends zr{}class kn extends zr{async _call(f){return new Qs(await super._call(f))}}class Sn extends zr{async _call(f){return new Kt(await super._call(f))}}class $n extends zr{async _call(f){return new Vs(await super._call(f))}}class Br extends ee{}class An extends Br{}class Zn extends Br{async _call(f){return new Qs(await super._call(f))}}class Rr extends Br{async _call(f){return new Kt(await super._call(f))}}class fr extends Br{async _call(f){return new Zs(await super._call(f))}}class ar extends ee{}class pn extends ar{}class Xr extends ar{async _call(f){return new Qs(await super._call(f))}}class hn extends ar{async _call(f){return new Kt(await super._call(f))}}class mn extends ar{async _call(f){return new Vs(await super._call(f))}}class fn extends ar{async _call(f){return new Zs(await super._call(f))}}class Ot extends ee{}class _n extends Ot{}class In extends Ot{async _call(f){return new Qs(await super._call(f))}}class Fn extends Ot{async _call(f){return new Kt(await super._call(f))}}class On extends Ot{async _call(f){return new Zs(await super._call(f))}}class Nr extends ee{}class Dn extends Nr{}class gn extends Nr{async _call(f){return new Kt(await super._call(f))}}class Ln extends Nr{async _call(f){return new Zs(await super._call(f))}}class as extends Nr{async _call(f){return new Qs(await super._call(f))}}class Te extends ee{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class M extends Te{}class Y extends Te{}class ce extends ee{}class me extends ce{}class Fe extends ce{}class Ye extends ee{}class gt extends Ye{}class wt extends Ye{}class yt extends ee{}class pt extends yt{}class rs extends yt{}class Yt extends yt{async _call(f){return new Kt(await super._call(f))}}class Ms extends ee{}class Gs extends Ms{}class jt extends Ms{}class is extends Ms{async _call(f){return new Kt(await super._call(f))}}class Ks extends Ms{}class Js extends ee{}class De extends Js{}class Xs extends Js{}class kr extends ee{}class Es extends kr{}class Hs extends kr{}class $t extends ee{}class sr extends $t{}class _r extends $t{async _call(f){return new Qs(await super._call(f))}}class ds extends $t{async _call(f){return new Kt(await super._call(f))}}class Cs extends $t{async _call(f){return new Vs(await super._call(f))}}class Mt extends $t{async _call(f){return new Zs(await super._call(f))}}class Gt extends ee{}class Is extends Gt{}class ks extends Gt{async _call(f){return new Qs(await super._call(f))}}class js extends Gt{async _call(f){return new Kt(await super._call(f))}}class Tt extends Gt{async _call(f){return new Vs(await super._call(f))}}class Yr extends Gt{async _call(f){return new Zs(await super._call(f))}}class He extends ee{}class Ct extends He{}class Ea extends He{async _call(f){return new Qs(await super._call(f))}}class Ii extends He{async _call(f){return new Kt(await super._call(f))}}class Ca extends He{async _call(f){return new Vs(await super._call(f))}}class ka extends He{async _call(f){return new Zs(await super._call(f))}}class qt extends ee{}class Sa extends qt{}class Fi extends qt{}class Oi extends ee{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 Oi{}class Aa extends Oi{_prepare_generation_config(f,q){return super._prepare_generation_config(f,q,U.WhisperGenerationConfig)}_retrieve_init_tokens(f){const q=[f.decoder_start_token_id];let xe=f.language;const $e=f.task;if(f.is_multilingual){xe||(console.warn("No language specified - defaulting to English (en)."),xe="en");const rt=`<|${(0,H.whisper_language_to_code)(xe)}|>`;q.push(f.lang_to_id[rt]),q.push(f.task_to_id[$e??"transcribe"])}else if(xe||$e)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!f.return_timestamps&&f.no_timestamps_token_id&&q.at(-1)!==f.no_timestamps_token_id?q.push(f.no_timestamps_token_id):f.return_timestamps&&q.at(-1)===f.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),q.pop()),q.filter(Le=>Le!=null)}async generate({inputs:f=null,generation_config:q=null,logits_processor:xe=null,stopping_criteria:$e=null,...Le}){q=this._prepare_generation_config(q,Le);const rt=Le.decoder_input_ids??this._retrieve_init_tokens(q);if(q.return_timestamps&&(xe??=new b.LogitsProcessorList,xe.push(new b.WhisperTimeStampLogitsProcessor(q,rt))),q.begin_suppress_tokens&&(xe??=new b.LogitsProcessorList,xe.push(new b.SuppressTokensAtBeginLogitsProcessor(q.begin_suppress_tokens,rt.length))),q.return_token_timestamps){if(!q.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.");q.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),q.output_attentions=!0,q.return_dict_in_generate=!0}const ot=await super.generate({inputs:f,generation_config:q,logits_processor:xe,decoder_input_ids:rt,...Le});return q.return_token_timestamps&&(ot.token_timestamps=this._extract_token_timestamps(ot,q.alignment_heads,q.num_frames)),ot}_extract_token_timestamps(f,q,xe=null,$e=.02){if(!f.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 Le=this.config.median_filter_width;Le===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Le=7);const rt=f.cross_attentions,ot=Array.from({length:this.config.decoder_layers},(Ht,Qt)=>(0,v.cat)(rt.map(ps=>ps[Qt]),2)),_t=(0,v.stack)(q.map(([Ht,Qt])=>{if(Ht>=ot.length)throw new Error(`Layer index ${Ht} is out of bounds for cross attentions (length ${ot.length}).`);return xe?ot[Ht].slice(null,Qt,null,[0,xe]):ot[Ht].slice(null,Qt)})).transpose(1,0,2,3),[kt,Zt]=(0,v.std_mean)(_t,-2,0,!0),Wt=_t.clone();for(let Ht=0;Htps[Bs+1]-ps[Bs]),Us=(0,j.mergeArrays)([1],es).map(Fs=>!!Fs),zs=[];for(let Fs=0;FsDt.findIndex(At=>At==Le)),_t=ot.every(Dt=>Dt===-1),kt=ot.every(Dt=>Dt!==-1);if(!_t&&!kt)throw new Error("Every input should contain either 0 or 1 image token.");if(_t)return{inputs_embeds:f,attention_mask:$e};const Zt=[],Wt=[];for(let Dt=0;DtArray.from({length:f.dims[0]},es=>Array.from({length:f.dims[1]},Us=>1))),bs=q?q.tolist():[],Ht=xe?xe.tolist():[];let Qt=0,ps=0;for(let ys=0;ysDt[ys][Os]==1),zs=es.reduce((ws,Os,Ir)=>(Os==_t&&ws.push(Ir),ws),[]).map(ws=>es[ws+1]),Fs=zs.filter(ws=>ws==rt).length,Bs=zs.filter(ws=>ws==ot).length;let nr=[],mr=0,_a=Fs,lr=Bs;for(let ws=0;wsur>mr&&nn==rt),Ir=es.findIndex((nn,ur)=>ur>mr&&nn==ot),sn=_a>0&&Os!==-1?Os:es.length+1,bn=lr>0&&Ir!==-1?Ir:es.length+1;let ga,Ti,wa,ya;sn0?(0,K.max)(nr.at(-1))[0]+1:0;nr.push(Array.from({length:3*ba},(nn,ur)=>Yd+ur%ba));const Jd=ba+Yd,Pi=Vp*Ma*vn,Zd=Array.from({length:Pi},(nn,ur)=>Jd+Math.floor(ur/(Ma*vn))),ec=Array.from({length:Pi},(nn,ur)=>Jd+Math.floor(ur/vn)%Ma),rn=Array.from({length:Pi},(nn,ur)=>Jd+ur%vn);nr.push([Zd,ec,rn].flat()),mr=ga+Pi}if(mr0?(0,K.max)(nr.at(-1))[0]+1:0,Os=es.length-mr;nr.push(Array.from({length:3*Os},(Ir,sn)=>ws+sn%Os))}const Ar=nr.reduce((ws,Os)=>ws+Os.length,0),Gn=new Array(Ar);let Xd=0;for(let ws=0;ws<3;++ws)for(let Os=0;OsWt[Qt%Wt.length]),bs=Array.from({length:Dt[0]},(Ht,Qt)=>(0,K.max)(Wt.subarray(Dt[1]*Qt,Dt[1]*(Qt+1)))[0]+1n+BigInt(Dt[1]));return[new v.Tensor("int64",At,[3,...Dt]),new v.Tensor("int64",bs,[bs.length,1])]}else{const[Wt,Dt]=f.dims,At=BigInt64Array.from({length:3*Wt*Dt},(bs,Ht)=>BigInt(Math.floor(Ht%Dt/Wt)));return[new v.Tensor("int64",At,[3,...f.dims]),(0,v.zeros)([Wt,1])]}}async encode_image({pixel_values:f,image_grid_thw:q}){return(await ge(this.sessions.vision_encoder,{pixel_values:f,grid_thw:q})).image_features}_merge_input_ids_with_image_features(f){return Je({image_token_id:this.config.image_token_id,...f})}prepare_inputs_for_generation(f,q,xe){if(q.attention_mask&&!q.position_ids)if(!q.past_key_values)[q.position_ids,q.rope_deltas]=this.get_rope_index(q.input_ids,q.image_grid_thw,q.video_grid_thw,q.attention_mask);else{q.pixel_values=null;const $e=BigInt(Object.values(q.past_key_values)[0].dims.at(-2)),Le=q.rope_deltas.map(rt=>$e+rt);q.position_ids=(0,v.stack)([Le,Le,Le],0)}return q}}class ao extends ee{}class xl extends ao{}class Bn extends ao{}class lo extends ee{}class ii extends lo{}class Tl extends lo{}class uo extends ee{}class Pl extends uo{}class El extends uo{}class co extends ee{}class Cl extends co{}class kl extends co{}class po extends ee{}class Sl extends po{}class $l extends po{}class ho extends ee{}class Al extends ho{}class Il extends ho{async _call(f){return new Kt(await super._call(f))}}class mo extends ee{}class Fl extends mo{}class Ol extends mo{async _call(f){return new Kt(await super._call(f))}}class fo extends ee{}class Dl extends fo{}class oi extends ee{}class _o extends oi{}class Ll extends oi{async _call(f){return new Kt(await super._call(f))}}class zl extends ee{}class Bl extends zl{}class go extends ee{}class Rl extends go{}class Nl extends go{async _call(f){return new Kt(await super._call(f))}}class wo extends ee{}class jl extends wo{}class yo extends ee{}class Vl extends yo{}class fc extends yo{async _call(f){return new Kt(await super._call(f))}}class Ul extends ee{}class Wl extends Ul{async _call(f){return new Wn(await super._call(f))}}class hr extends ee{}class Gl extends hr{}class Kl extends hr{async _call(f){return new Kt(await super._call(f))}}class Mo extends ee{}class Hl extends Mo{}class ql extends Mo{async _call(f){return new Kt(await super._call(f))}}class bo extends ee{}class Ql extends bo{}class Xl extends bo{}class vo extends ee{}class Yl extends vo{}class _c extends vo{}class xo extends ee{}class Jl extends xo{}class Zl extends xo{async _call(f){return new Kt(await super._call(f))}}class ai extends ee{}class eu extends ai{}class tu extends ai{async _call(f){return new Vr(await super._call(f))}}class su extends ai{async _call(f){return new Zr(await super._call(f))}}class Vr extends Ve{constructor({logits:f,pred_boxes:q}){super(),this.logits=f,this.pred_boxes=q}}class Zr extends Ve{constructor({logits:f,pred_boxes:q,pred_masks:xe}){super(),this.logits=f,this.pred_boxes=q,this.pred_masks=xe}}class Ur extends ee{}class To extends Ur{}class en extends Ur{async _call(f){return new qs(await super._call(f))}}class qs extends Ve{constructor({logits:f,pred_boxes:q}){super(),this.logits=f,this.pred_boxes=q}}class Po extends ee{}class Eo extends Po{}class ru extends Po{async _call(f){return new gc(await super._call(f))}}class gc extends Vr{}class wn extends ee{}class Co extends wn{}class ko extends wn{async _call(f){return new Kt(await super._call(f))}}class So extends ee{}class nu extends So{}class $o extends So{async _call(f){return new Kt(await super._call(f))}}class li extends ee{}class iu extends li{}class Ao extends li{async _call(f){return new Kt(await super._call(f))}}class Io extends ee{}class ui extends Io{}class Fo extends Io{async _call(f){return new Kt(await super._call(f))}}class Oo extends ee{}class ou extends Oo{}class wc extends Oo{}class Do extends ee{}class Lo extends Do{}class Rn extends Do{}class au extends ee{}class zo extends au{}class di extends ee{}class lu extends di{}class uu extends di{}class yc extends di{}class du extends ee{}class cu extends du{}class pu extends ee{}class hu extends pu{}class ci extends pu{}class Bo extends ee{}class pi extends Bo{}class Ro extends Bo{}class No extends ee{}class mu extends No{}class jo extends ee{}class Vo extends jo{}class Mc extends jo{async _call(f){return new Kt(await super._call(f))}}class Uo extends ee{}class bc extends Uo{}class fu extends Uo{async _call(f){return new Kt(await super._call(f))}}class Wo extends ee{}class _u extends Wo{}class Go extends Wo{async _call(f){return new Kt(await super._call(f))}}class Ko extends ee{}class gu extends Ko{}class Ho extends Ko{async _call(f){return new Kt(await super._call(f))}}class wu extends ee{}class yu extends wu{}class Mu extends ee{}class bu extends Mu{}class vu extends Mu{async _call(f){return new xu(await super._call(f))}}class xu extends Ve{constructor({logits:f,pred_boxes:q}){super(),this.logits=f,this.pred_boxes=q}}class vc extends ee{}class Tu extends vc{async get_image_embeddings({pixel_values:f}){return await Ae(this,{pixel_values:f})}async forward(f){if((!f.image_embeddings||!f.image_positional_embeddings)&&(f={...f,...await this.get_image_embeddings(f)}),!f.input_labels&&f.input_points){const xe=f.input_points.dims.slice(0,-1),$e=xe.reduce((Le,rt)=>Le*rt,1);f.input_labels=new v.Tensor("int64",new BigInt64Array($e).fill(1n),xe)}const q={image_embeddings:f.image_embeddings,image_positional_embeddings:f.image_positional_embeddings};return f.input_points&&(q.input_points=f.input_points),f.input_labels&&(q.input_labels=f.input_labels),f.input_boxes&&(q.input_boxes=f.input_boxes),await ge(this.sessions.prompt_encoder_mask_decoder,q)}async _call(f){return new Pu(await super._call(f))}}class Pu extends Ve{constructor({iou_scores:f,pred_masks:q}){super(),this.iou_scores=f,this.pred_masks=q}}class qo extends ee{}class Eu extends qo{}class Cu extends qo{}class ku extends ee{}class hi extends ku{}class Nn extends ku{}class Sr extends ee{}class Su extends Sr{}class $u extends Sr{async _call(f){return new yn(await super._call(f))}}class Au extends Sr{async _call(f){return new Kt(await super._call(f))}}class Iu extends Sr{async _call(f){return new Vs(await super._call(f))}}class mi extends ee{}class Fu extends mi{}class Ou extends mi{async _call(f){return new Vs(await super._call(f))}}class Du extends ee{}class xc extends Du{}class fi extends ee{}class Qo extends fi{}class Lu extends fi{async _call(f){return new yn(await super._call(f))}}class zu extends fi{async _call(f){return new Kt(await super._call(f))}}class jn extends ee{}class Tc extends jn{}class Bu extends jn{async _call(f){return new yn(await super._call(f))}}class Ru extends jn{async _call(f){return new Kt(await super._call(f))}}class Pc extends jn{async _call(f){return new Vs(await super._call(f))}}class _i extends ee{}class Nu extends _i{}class ju extends _i{async _call(f){return new yn(await super._call(f))}}class Vu extends _i{async _call(f){return new Kt(await super._call(f))}}class Bp extends ee{}class Uu extends Sr{}class Wu extends Sr{async _call(f){return new yn(await super._call(f))}}class Gu extends Sr{async _call(f){return new Kt(await super._call(f))}}class Vn extends ee{}class Ku extends Vn{}class Hu extends Vn{async _call(f){return new yn(await super._call(f))}}class qu extends Vn{async _call(f){return new Kt(await super._call(f))}}class Qu extends Vn{async _call(f){return new mp(await super._call(f))}}class Ec extends Vn{async _call(f){return new Vs(await super._call(f))}}class Xu extends ee{}class Yu extends Xu{}class gi extends ee{}class Cc extends gi{}class kc extends gi{}class Ju extends gi{async generate_speech(f,q,{threshold:xe=.5,minlenratio:$e=0,maxlenratio:Le=20,vocoder:rt=null}={}){const ot={input_ids:f},{encoder_outputs:_t,encoder_attention_mask:kt}=await Ae(this,ot),Zt=_t.dims[1]/this.config.reduction_factor,Wt=Math.floor(Zt*Le),Dt=Math.floor(Zt*$e),At=this.config.num_mel_bins;let bs=[],Ht=null,Qt=null,ps=0;for(;;){++ps;const Us=pe(!!Qt);let zs;Qt?zs=Qt.output_sequence_out:zs=new v.Tensor("float32",new Float32Array(At),[1,1,At]);let Fs={use_cache_branch:Us,output_sequence:zs,encoder_attention_mask:kt,speaker_embeddings:q,encoder_hidden_states:_t};this.addPastKeyValues(Fs,Ht),Qt=await ge(this.sessions.decoder_model_merged,Fs),Ht=this.getPastKeyValues(Qt,Ht);const{prob:Bs,spectrum:nr}=Qt;if(bs.push(nr),ps>=Dt&&(Array.from(Bs.data).filter(mr=>mr>=xe).length>0||ps>=Wt))break}const ys=(0,v.cat)(bs),{waveform:es}=await ge(rt.sessions.model,{spectrogram:ys});return{spectrogram:ys,waveform:es}}}class Zu extends ee{main_input_name="spectrogram"}class ed extends ee{}class td extends ed{}class sd extends ee{}class vr extends sd{}class $r extends sd{}class Wr extends ee{}class tn extends Wr{}class rd extends Wr{}class Xo extends ee{}class nd extends Xo{}class id extends Xo{}class wi extends ee{}class od extends wi{}class ad extends wi{static async from_pretrained(f,q={}){return super.from_pretrained(f,{...q,model_file_name:q.model_file_name??"text_model"})}}class ld extends wi{static async from_pretrained(f,q={}){return super.from_pretrained(f,{...q,model_file_name:q.model_file_name??"audio_model"})}}class ud extends ee{}class Yo extends ud{async _call(f){return new Qd(await super._call(f))}}class Jo extends ee{}class rr extends Jo{}class dd extends Jo{}class cd extends Jo{}class yi extends ee{}class pd extends yi{}class Un extends yi{}class Zo extends ee{}class hd extends Zo{}class md extends Zo{async _call(f){return new Kt(await super._call(f))}}class ea extends ee{}class Sc extends ea{}class $c extends ea{}class Mi extends ee{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(f){const[q,xe]=f.dims,$e=this.config.decoder.num_codebooks,Le=xe-$e;let rt=0;for(let kt=0;kt0&&Dt<=Le&&(f.data[rt++]=f.data[kt])}const ot=Math.floor(q/$e),_t=rt/(ot*$e);return new v.Tensor(f.type,f.data.slice(0,rt),[ot,$e,_t])}prepare_inputs_for_generation(f,q,xe){let $e=structuredClone(f);for(let rt=0;rt<$e.length;++rt)for(let ot=0;ot<$e[rt].length;++ot)rt%this.config.decoder.num_codebooks>=ot&&($e[rt][ot]=BigInt(this.config.decoder.pad_token_id));return xe.guidance_scale!==null&&xe.guidance_scale>1&&($e=$e.concat($e)),super.prepare_inputs_for_generation($e,q,xe)}async generate(f){const q=await super.generate(f),xe=this._apply_and_filter_by_delay_pattern_mask(q).unsqueeze_(0),{audio_values:$e}=await ge(this.sessions.encodec_decode,{audio_codes:xe});return $e}}class ta extends ee{}class fd extends ta{}class _d extends ta{async _call(f){return new Kt(await super._call(f))}}class sa extends ee{}class gd extends sa{}class ra extends sa{async _call(f){return new Kt(await super._call(f))}}class na extends ee{}class Ac extends na{}class ia extends na{async _call(f){return new Kt(await super._call(f))}}class oa extends ee{}class wd extends oa{}class yd extends oa{async _call(f){return new Kt(await super._call(f))}}class Ic extends ee{}class Md extends Ic{}class bd extends ee{}class vd extends bd{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...f){super(...f),this._generation_mode="text"}async forward(f){const q=this._generation_mode??"text";let xe;if(q==="text"||!f.past_key_values){const _t=this.sessions.prepare_inputs_embeds,kt=(0,j.pick)(f,_t.inputNames);xe=await ge(_t,kt)}else{const _t=this.sessions.gen_img_embeds,kt=(0,j.pick)({image_ids:f.input_ids},_t.inputNames);xe=await ge(_t,kt)}const $e={...f,...xe},Le=await Pe(this,$e),rt=this.sessions[q==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const ot=await ge(rt,(0,j.pick)(Le,rt.inputNames));return{...xe,...Le,...ot}}async generate(f){return this._generation_mode="text",super.generate(f)}async generate_images(f){this._generation_mode="image";const q=(f.inputs??f[this.main_input_name]).dims[1],$e=(await super.generate(f)).slice(null,[q,null]),Le=this.sessions.image_decode,{decoded_image:rt}=await ge(Le,{generated_tokens:$e}),ot=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),_t=[];for(const kt of ot){const Zt=L.RawImage.fromTensor(kt);_t.push(Zt)}return _t}}class Fc extends Ve{constructor({char_logits:f,bpe_logits:q,wp_logits:xe}){super(),this.char_logits=f,this.bpe_logits=q,this.wp_logits=xe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class xd extends ee{}class Td extends xd{async _call(f){return new Fc(await super._call(f))}}class Pd extends ee{}class Ed extends Pd{}class Cd extends Pd{}class aa extends ee{}class kd extends aa{}class Sd extends aa{}class fs{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(f,{progress_callback:q=null,config:xe=null,cache_dir:$e=null,local_files_only:Le=!1,revision:rt="main",model_file_name:ot=null,subfolder:_t="onnx",device:kt=null,dtype:Zt=null,use_external_data_format:Wt=null,session_options:Dt={}}={}){const At={progress_callback:q,config:xe,cache_dir:$e,local_files_only:Le,revision:rt,model_file_name:ot,subfolder:_t,device:kt,dtype:Zt,use_external_data_format:Wt,session_options:Dt};if(At.config=await g.AutoConfig.from_pretrained(f,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 Ht=bs.get(At.config.model_type);if(Ht)return await Ht[1].from_pretrained(f,At)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${At.config.model_type}", attempting to construct from base class.`),await ee.from_pretrained(f,At);throw Error(`Unsupported model type: ${At.config.model_type}`)}}const Oc=new Map([["bert",["BertModel",ve]],["modernbert",["ModernBertModel",at]],["nomic_bert",["NomicBertModel",le]],["roformer",["RoFormerModel",we]],["electra",["ElectraModel",As]],["esm",["EsmModel",Jn]],["convbert",["ConvBertModel",ft]],["camembert",["CamembertModel",Lt]],["deberta",["DebertaModel",qr]],["deberta-v2",["DebertaV2Model",vt]],["mpnet",["MPNetModel",pn]],["albert",["AlbertModel",Dn]],["distilbert",["DistilBertModel",br]],["roberta",["RobertaModel",sr]],["xlm",["XLMModel",Is]],["xlm-roberta",["XLMRobertaModel",Ct]],["clap",["ClapModel",od]],["clip",["CLIPModel",ja]],["clipseg",["CLIPSegModel",Ha]],["chinese_clip",["ChineseCLIPModel",gr]],["siglip",["SiglipModel",Wa]],["jina_clip",["JinaCLIPModel",si]],["mobilebert",["MobileBertModel",An]],["squeezebert",["SqueezeBertModel",_n]],["wav2vec2",["Wav2Vec2Model",Su]],["wav2vec2-bert",["Wav2Vec2BertModel",Nu]],["unispeech",["UniSpeechModel",Qo]],["unispeech-sat",["UniSpeechSatModel",Tc]],["hubert",["HubertModel",Uu]],["wavlm",["WavLMModel",Ku]],["audio-spectrogram-transformer",["ASTModel",Sa]],["vits",["VitsModel",Yo]],["pyannote",["PyAnnoteModel",Fu]],["wespeaker-resnet",["WeSpeakerResNetModel",xc]],["detr",["DetrModel",eu]],["rt_detr",["RTDetrModel",To]],["table-transformer",["TableTransformerModel",Eo]],["vit",["ViTModel",Al]],["ijepa",["IJepaModel",Fl]],["pvt",["PvtModel",_o]],["vit_msn",["ViTMSNModel",Rl]],["vit_mae",["ViTMAEModel",Bl]],["groupvit",["GroupViTModel",jl]],["fastvit",["FastViTModel",Vl]],["mobilevit",["MobileViTModel",Gl]],["mobilevitv2",["MobileViTV2Model",Hl]],["owlvit",["OwlViTModel",Ql]],["owlv2",["Owlv2Model",Yl]],["beit",["BeitModel",Jl]],["deit",["DeiTModel",Co]],["hiera",["HieraModel",nu]],["convnext",["ConvNextModel",Vo]],["convnextv2",["ConvNextV2Model",bc]],["dinov2",["Dinov2Model",_u]],["dinov2_with_registers",["Dinov2WithRegistersModel",gu]],["resnet",["ResNetModel",iu]],["swin",["SwinModel",ui]],["swin2sr",["Swin2SRModel",ou]],["donut-swin",["DonutSwinModel",mu]],["yolos",["YolosModel",bu]],["dpt",["DPTModel",Lo]],["glpn",["GLPNModel",pi]],["hifigan",["SpeechT5HifiGan",Zu]],["efficientnet",["EfficientNetModel",hd]],["decision_transformer",["DecisionTransformerModel",Md]],["patchtst",["PatchTSTForPrediction",Ed]],["patchtsmixer",["PatchTSMixerForPrediction",kd]],["mobilenet_v1",["MobileNetV1Model",fd]],["mobilenet_v2",["MobileNetV2Model",gd]],["mobilenet_v3",["MobileNetV3Model",Ac]],["mobilenet_v4",["MobileNetV4Model",wd]],["maskformer",["MaskFormerModel",hu]],["mgp-str",["MgpstrForSceneTextRecognition",Td]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Yu]]]),Dc=new Map([["t5",["T5Model",M]],["longt5",["LongT5Model",me]],["mt5",["MT5Model",gt]],["bart",["BartModel",pt]],["mbart",["MBartModel",Gs]],["marian",["MarianModel",Eu]],["whisper",["WhisperModel",$a]],["m2m_100",["M2M100Model",hi]],["blenderbot",["BlenderbotModel",De]],["blenderbot-small",["BlenderbotSmallModel",Es]]]),Lc=new Map([["bloom",["BloomModel",Pl]],["jais",["JAISModel",Ya]],["gpt2",["GPT2Model",Qa]],["gptj",["GPTJModel",sl]],["gpt_bigcode",["GPTBigCodeModel",nl]],["gpt_neo",["GPTNeoModel",yr]],["gpt_neox",["GPTNeoXModel",el]],["codegen",["CodeGenModel",Hi]],["llama",["LlamaModel",Qi]],["exaone",["ExaoneModel",ni]],["olmo",["OlmoModel",ul]],["olmo2",["Olmo2Model",dl]],["mobilellm",["MobileLLMModel",ll]],["granite",["GraniteModel",hc]],["cohere",["CohereModel",hl]],["gemma",["GemmaModel",ls]],["gemma2",["Gemma2Model",fl]],["openelm",["OpenELMModel",gl]],["qwen2",["Qwen2Model",yl]],["phi",["PhiModel",xl]],["phi3",["Phi3Model",ii]],["mpt",["MptModel",Cl]],["opt",["OPTModel",Sl]],["mistral",["MistralModel",vr]],["starcoder2",["Starcoder2Model",tn]],["falcon",["FalconModel",nd]],["stablelm",["StableLmModel",pd]]]),la=new Map([["speecht5",["SpeechT5ForSpeechToText",kc]],["whisper",["WhisperForConditionalGeneration",Aa]],["moonshine",["MoonshineForConditionalGeneration",Ia]]]),$d=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ju]]]),Ad=new Map([["vits",["VitsModel",Yo]],["musicgen",["MusicgenForConditionalGeneration",Mi]]]),Id=new Map([["bert",["BertForSequenceClassification",Ne]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",We]],["electra",["ElectraForSequenceClassification",Tr]],["esm",["EsmForSequenceClassification",Sn]],["convbert",["ConvBertForSequenceClassification",ss]],["camembert",["CamembertForSequenceClassification",Pr]],["deberta",["DebertaForSequenceClassification",Dr]],["deberta-v2",["DebertaV2ForSequenceClassification",Ys]],["mpnet",["MPNetForSequenceClassification",hn]],["albert",["AlbertForSequenceClassification",gn]],["distilbert",["DistilBertForSequenceClassification",Ls]],["roberta",["RobertaForSequenceClassification",ds]],["xlm",["XLMForSequenceClassification",js]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ii]],["bart",["BartForSequenceClassification",Yt]],["mbart",["MBartForSequenceClassification",is]],["mobilebert",["MobileBertForSequenceClassification",Rr]],["squeezebert",["SqueezeBertForSequenceClassification",Fn]]]),Fd=new Map([["bert",["BertForTokenClassification",Ue]],["modernbert",["ModernBertForTokenClassification",ct]],["roformer",["RoFormerForTokenClassification",qe]],["electra",["ElectraForTokenClassification",Gr]],["esm",["EsmForTokenClassification",$n]],["convbert",["ConvBertForTokenClassification",Ts]],["camembert",["CamembertForTokenClassification",Er]],["deberta",["DebertaForTokenClassification",Lr]],["deberta-v2",["DebertaV2ForTokenClassification",Cn]],["mpnet",["MPNetForTokenClassification",mn]],["distilbert",["DistilBertForTokenClassification",Qr]],["roberta",["RobertaForTokenClassification",Cs]],["xlm",["XLMForTokenClassification",Tt]],["xlm-roberta",["XLMRobertaForTokenClassification",Ca]]]),ua=new Map([["t5",["T5ForConditionalGeneration",Y]],["longt5",["LongT5ForConditionalGeneration",Fe]],["mt5",["MT5ForConditionalGeneration",wt]],["bart",["BartForConditionalGeneration",rs]],["mbart",["MBartForConditionalGeneration",jt]],["marian",["MarianMTModel",Cu]],["m2m_100",["M2M100ForConditionalGeneration",Nn]],["blenderbot",["BlenderbotForConditionalGeneration",Xs]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Hs]]]),Od=new Map([["bloom",["BloomForCausalLM",El]],["gpt2",["GPT2LMHeadModel",Xa]],["jais",["JAISLMHeadModel",Ja]],["gptj",["GPTJForCausalLM",rl]],["gpt_bigcode",["GPTBigCodeForCausalLM",il]],["gpt_neo",["GPTNeoForCausalLM",Za]],["gpt_neox",["GPTNeoXForCausalLM",tl]],["codegen",["CodeGenForCausalLM",ol]],["llama",["LlamaForCausalLM",pc]],["exaone",["ExaoneForCausalLM",al]],["olmo",["OlmoForCausalLM",Zi]],["olmo2",["Olmo2ForCausalLM",cl]],["mobilellm",["MobileLLMForCausalLM",zn]],["granite",["GraniteForCausalLM",pl]],["cohere",["CohereForCausalLM",mc]],["gemma",["GemmaForCausalLM",ml]],["gemma2",["Gemma2ForCausalLM",_l]],["openelm",["OpenELMForCausalLM",wl]],["qwen2",["Qwen2ForCausalLM",Ml]],["phi",["PhiForCausalLM",Bn]],["phi3",["Phi3ForCausalLM",Tl]],["mpt",["MptForCausalLM",kl]],["opt",["OPTForCausalLM",$l]],["mbart",["MBartForCausalLM",Ks]],["mistral",["MistralForCausalLM",$r]],["starcoder2",["Starcoder2ForCausalLM",rd]],["falcon",["FalconForCausalLM",id]],["trocr",["TrOCRForCausalLM",td]],["stablelm",["StableLmForCausalLM",Un]],["phi3_v",["Phi3VForCausalLM",pr]]]),bi=new Map([["multi_modality",["MultiModalityCausalLM",vd]]]),da=new Map([["bert",["BertForMaskedLM",Ke]],["modernbert",["ModernBertForMaskedLM",mt]],["roformer",["RoFormerForMaskedLM",Se]],["electra",["ElectraForMaskedLM",tr]],["esm",["EsmForMaskedLM",kn]],["convbert",["ConvBertForMaskedLM",Nt]],["camembert",["CamembertForMaskedLM",Kr]],["deberta",["DebertaForMaskedLM",Cr]],["deberta-v2",["DebertaV2ForMaskedLM",Ft]],["mpnet",["MPNetForMaskedLM",Xr]],["albert",["AlbertForMaskedLM",as]],["distilbert",["DistilBertForMaskedLM",cn]],["roberta",["RobertaForMaskedLM",_r]],["xlm",["XLMWithLMHeadModel",ks]],["xlm-roberta",["XLMRobertaForMaskedLM",Ea]],["mobilebert",["MobileBertForMaskedLM",Zn]],["squeezebert",["SqueezeBertForMaskedLM",In]]]),ca=new Map([["bert",["BertForQuestionAnswering",ze]],["roformer",["RoFormerForQuestionAnswering",tt]],["electra",["ElectraForQuestionAnswering",Ns]],["convbert",["ConvBertForQuestionAnswering",ms]],["camembert",["CamembertForQuestionAnswering",Hr]],["deberta",["DebertaForQuestionAnswering",or]],["deberta-v2",["DebertaV2ForQuestionAnswering",dn]],["mpnet",["MPNetForQuestionAnswering",fn]],["albert",["AlbertForQuestionAnswering",Ln]],["distilbert",["DistilBertForQuestionAnswering",ns]],["roberta",["RobertaForQuestionAnswering",Mt]],["xlm",["XLMForQuestionAnswering",Yr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ka]],["mobilebert",["MobileBertForQuestionAnswering",fr]],["squeezebert",["SqueezeBertForQuestionAnswering",On]]]),vi=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Li]],["idefics3",["Idefics3ForConditionalGeneration",zi]]]),Dd=new Map([["llava",["LlavaForConditionalGeneration",ei]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Fa]],["moondream1",["Moondream1ForConditionalGeneration",Oa]],["florence2",["Florence2ForConditionalGeneration",La]],["qwen2-vl",["Qwen2VLForConditionalGeneration",vl]],["idefics3",["Idefics3ForConditionalGeneration",zi]],["paligemma",["PaliGemmaForConditionalGeneration",Ba]]]),zc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Li]]]),Ld=new Map([["vit",["ViTForImageClassification",Il]],["ijepa",["IJepaForImageClassification",Ol]],["pvt",["PvtForImageClassification",Ll]],["vit_msn",["ViTMSNForImageClassification",Nl]],["fastvit",["FastViTForImageClassification",fc]],["mobilevit",["MobileViTForImageClassification",Kl]],["mobilevitv2",["MobileViTV2ForImageClassification",ql]],["beit",["BeitForImageClassification",Zl]],["deit",["DeiTForImageClassification",ko]],["hiera",["HieraForImageClassification",$o]],["convnext",["ConvNextForImageClassification",Mc]],["convnextv2",["ConvNextV2ForImageClassification",fu]],["dinov2",["Dinov2ForImageClassification",Go]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Ho]],["resnet",["ResNetForImageClassification",Ao]],["swin",["SwinForImageClassification",Fo]],["segformer",["SegformerForImageClassification",dd]],["efficientnet",["EfficientNetForImageClassification",md]],["mobilenet_v1",["MobileNetV1ForImageClassification",_d]],["mobilenet_v2",["MobileNetV2ForImageClassification",ra]],["mobilenet_v3",["MobileNetV3ForImageClassification",ia]],["mobilenet_v4",["MobileNetV4ForImageClassification",yd]]]),pa=new Map([["detr",["DetrForObjectDetection",tu]],["rt_detr",["RTDetrForObjectDetection",en]],["table-transformer",["TableTransformerForObjectDetection",ru]],["yolos",["YolosForObjectDetection",vu]]]),ha=new Map([["owlvit",["OwlViTForObjectDetection",Xl]],["owlv2",["Owlv2ForObjectDetection",_c]],["grounding-dino",["GroundingDinoForObjectDetection",yu]]]),zd=new Map([["detr",["DetrForSegmentation",su]],["clipseg",["CLIPSegForImageSegmentation",qa]]]),Bd=new Map([["segformer",["SegformerForSemanticSegmentation",cd]],["sapiens",["SapiensForSemanticSegmentation",lu]]]),ma=new Map([["detr",["DetrForSegmentation",su]],["maskformer",["MaskFormerForInstanceSegmentation",ci]]]),Rd=new Map([["sam",["SamModel",Tu]]]),Nd=new Map([["wav2vec2",["Wav2Vec2ForCTC",$u]],["wav2vec2-bert",["Wav2Vec2BertForCTC",ju]],["unispeech",["UniSpeechForCTC",Lu]],["unispeech-sat",["UniSpeechSatForCTC",Bu]],["wavlm",["WavLMForCTC",Hu]],["hubert",["HubertForCTC",Wu]]]),fa=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Au]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Vu]],["unispeech",["UniSpeechForSequenceClassification",zu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ru]],["wavlm",["WavLMForSequenceClassification",qu]],["hubert",["HubertForSequenceClassification",Gu]],["audio-spectrogram-transformer",["ASTForAudioClassification",Fi]]]),jd=new Map([["wavlm",["WavLMForXVector",Qu]]]),Vd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Pc]],["wavlm",["WavLMForAudioFrameClassification",Ec]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Iu]],["pyannote",["PyAnnoteForAudioFrameClassification",Ou]]]),Ud=new Map([["vitmatte",["VitMatteForImageMatting",Wl]]]),Bc=new Map([["patchtst",["PatchTSTForPrediction",Cd]],["patchtsmixer",["PatchTSMixerForPrediction",Sd]]]),Rc=new Map([["swin2sr",["Swin2SRForImageSuperResolution",wc]]]),Wd=new Map([["dpt",["DPTForDepthEstimation",Rn]],["depth_anything",["DepthAnythingForDepthEstimation",zo]],["glpn",["GLPNForDepthEstimation",Ro]],["sapiens",["SapiensForDepthEstimation",uu]],["depth_pro",["DepthProForDepthEstimation",cu]]]),Gd=new Map([["sapiens",["SapiensForNormalEstimation",yc]]]),Kd=new Map([["vitpose",["VitPoseForPoseEstimation",Dl]]]),Hd=new Map([["clip",["CLIPVisionModelWithProjection",Ua]],["siglip",["SiglipVisionModel",Ka]],["jina_clip",["JinaCLIPVisionModel",wr]]]),Nc=[[Oc,I.EncoderOnly],[Dc,I.EncoderDecoder],[Lc,I.DecoderOnly],[Id,I.EncoderOnly],[Fd,I.EncoderOnly],[ua,I.Seq2Seq],[la,I.Seq2Seq],[Od,I.DecoderOnly],[bi,I.MultiModality],[da,I.EncoderOnly],[ca,I.EncoderOnly],[vi,I.Vision2Seq],[Dd,I.ImageTextToText],[Ld,I.EncoderOnly],[zd,I.EncoderOnly],[ma,I.EncoderOnly],[Bd,I.EncoderOnly],[Ud,I.EncoderOnly],[Bc,I.EncoderOnly],[Rc,I.EncoderOnly],[Wd,I.EncoderOnly],[Gd,I.EncoderOnly],[Kd,I.EncoderOnly],[pa,I.EncoderOnly],[ha,I.EncoderOnly],[Rd,I.MaskGeneration],[Nd,I.EncoderOnly],[fa,I.EncoderOnly],[$d,I.Seq2Seq],[Ad,I.EncoderOnly],[jd,I.EncoderOnly],[Vd,I.EncoderOnly],[Hd,I.EncoderOnly]];for(const[_,f]of Nc)for(const[q,xe]of _.values())S.set(q,f),P.set(xe,q),w.set(q,xe);const jc=[["MusicgenForConditionalGeneration",Mi,I.Musicgen],["Phi3VForCausalLM",pr,I.Phi3V],["CLIPTextModelWithProjection",Va,I.EncoderOnly],["SiglipTextModel",Ga,I.EncoderOnly],["JinaCLIPTextModel",Ri,I.EncoderOnly],["ClapTextModelWithProjection",ad,I.EncoderOnly],["ClapAudioModelWithProjection",ld,I.EncoderOnly]];for(const[_,f,q]of jc)S.set(_,q),P.set(f,_),w.set(_,f);class Vc extends fs{static MODEL_CLASS_MAPPINGS=Nc.map(f=>f[0]);static BASE_IF_FAIL=!0}class Uc extends fs{static MODEL_CLASS_MAPPINGS=[Id]}class Rp extends fs{static MODEL_CLASS_MAPPINGS=[Fd]}class Wc extends fs{static MODEL_CLASS_MAPPINGS=[ua]}class Gc extends fs{static MODEL_CLASS_MAPPINGS=[la]}class Kc extends fs{static MODEL_CLASS_MAPPINGS=[$d]}class Hc extends fs{static MODEL_CLASS_MAPPINGS=[Ad]}class Np extends fs{static MODEL_CLASS_MAPPINGS=[Od]}class qc extends fs{static MODEL_CLASS_MAPPINGS=[da]}class Qc extends fs{static MODEL_CLASS_MAPPINGS=[ca]}class Xc extends fs{static MODEL_CLASS_MAPPINGS=[vi]}class Yc extends fs{static MODEL_CLASS_MAPPINGS=[Ld]}class Jc extends fs{static MODEL_CLASS_MAPPINGS=[zd]}class Zc extends fs{static MODEL_CLASS_MAPPINGS=[Bd]}class ep extends fs{static MODEL_CLASS_MAPPINGS=[ma]}class tp extends fs{static MODEL_CLASS_MAPPINGS=[pa]}class sp extends fs{static MODEL_CLASS_MAPPINGS=[ha]}class rp extends fs{static MODEL_CLASS_MAPPINGS=[Rd]}class np extends fs{static MODEL_CLASS_MAPPINGS=[Nd]}class qd extends fs{static MODEL_CLASS_MAPPINGS=[fa]}class ip extends fs{static MODEL_CLASS_MAPPINGS=[jd]}class op extends fs{static MODEL_CLASS_MAPPINGS=[Vd]}class ap extends fs{static MODEL_CLASS_MAPPINGS=[zc]}class lp extends fs{static MODEL_CLASS_MAPPINGS=[Ud]}class up extends fs{static MODEL_CLASS_MAPPINGS=[Rc]}class dp extends fs{static MODEL_CLASS_MAPPINGS=[Wd]}class cp extends fs{static MODEL_CLASS_MAPPINGS=[Gd]}class jp extends fs{static MODEL_CLASS_MAPPINGS=[Kd]}class pp extends fs{static MODEL_CLASS_MAPPINGS=[Hd]}class hp extends Ve{constructor({logits:f,past_key_values:q,encoder_outputs:xe,decoder_attentions:$e=null,cross_attentions:Le=null}){super(),this.logits=f,this.past_key_values=q,this.encoder_outputs=xe,this.decoder_attentions=$e,this.cross_attentions=Le}}class Kt extends Ve{constructor({logits:f,...q}){super(),this.logits=f;const xe=Object.values(q);xe.length>0&&(this.attentions=xe)}}class mp extends Ve{constructor({logits:f,embeddings:q}){super(),this.logits=f,this.embeddings=q}}class Vs extends Ve{constructor({logits:f}){super(),this.logits=f}}class Qs extends Ve{constructor({logits:f}){super(),this.logits=f}}class Zs extends Ve{constructor({start_logits:f,end_logits:q}){super(),this.start_logits=f,this.end_logits=q}}class yn extends Ve{constructor({logits:f}){super(),this.logits=f}}class fp extends Ve{constructor({logits:f,past_key_values:q}){super(),this.logits=f,this.past_key_values=q}}class Wn extends Ve{constructor({alphas:f}){super(),this.alphas=f}}class Qd extends Ve{constructor({waveform:f,spectrogram:q}){super(),this.waveform=f,this.spectrogram=q}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(ke,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>N});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var $=r("./src/utils/audio.js");class N extends g.FeatureExtractor{constructor(j){super(j);const y=this.config.sampling_rate,T=(0,$.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:()=>Z});var g=r("./src/utils/constants.js"),$=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var N=r("./src/models/feature_extractors.js");class Z{static async from_pretrained(y,T={}){const b=await(0,$.getModelJSON)(y,g.FEATURE_EXTRACTOR_NAME,!0,T),x=b.feature_extractor_type,v=N[x];if(!v)throw new Error(`Unknown feature_extractor_type: '${x}'. Please report this at ${g.GITHUB_ISSUE_URL}.`);return new v(b)}}},"./src/models/auto/image_processing_auto.js":(ke,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>j});var g=r("./src/utils/constants.js"),$=r("./src/utils/hub.js"),N=r("./src/base/image_processors_utils.js"),Z=r("./src/models/image_processors.js");class j{static async from_pretrained(T,b={}){const x=await(0,$.getModelJSON)(T,g.IMAGE_PROCESSOR_NAME,!0,b),v=x.image_processor_type??x.feature_extractor_type;let L=Z[v];return L||(v!==void 0&&console.warn(`Image processor type '${v}' not found, assuming base ImageProcessor. Please report this at ${g.GITHUB_ISSUE_URL}.`),L=N.ImageProcessor),new L(x)}}},"./src/models/auto/processing_auto.js":(ke,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>T});var g=r("./src/utils/constants.js"),$=r("./src/utils/hub.js"),N=r("./src/base/processing_utils.js"),Z=r("./src/models/processors.js"),j=r("./src/models/image_processors.js"),y=r("./src/models/feature_extractors.js");class T{static async from_pretrained(x,v={}){const L=await(0,$.getModelJSON)(x,g.IMAGE_PROCESSOR_NAME,!0,v),{image_processor_type:K,feature_extractor_type:se,processor_class:oe}=L;if(oe&&Z[oe])return Z[oe].from_pretrained(x,v);if(!K&&!se)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const V={};if(K){const H=j[K];if(!H)throw new Error(`Unknown image_processor_type: '${K}'.`);V.image_processor=new H(L)}if(se){const H=j[se];if(H)V.image_processor=new H(L);else{const I=y[se];if(!I)throw new Error(`Unknown feature_extractor_type: '${se}'.`);V.feature_extractor=new I(L)}}const U={};return new N.Processor(U,V)}}},"./src/models/beit/image_processing_beit.js":(ke,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(ke,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(ke,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(ke,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>N});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var $=r("./src/utils/audio.js");class N extends g.FeatureExtractor{constructor(j){super(j),this.mel_filters=(0,$.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,$.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,$.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(j,y,T,b){let x;const v=j.length-y;if(v>0)if(T==="rand_trunc"){const L=Math.floor(Math.random()*(v+1));j=j.subarray(L,L+y),x=await this._extract_fbank_features(j,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${T}" not implemented`);else{if(v<0){let L=new Float64Array(y);if(L.set(j),b==="repeat")for(let K=j.length;K{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/convnext/image_processing_convnext.js":(ke,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>N,ConvNextImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{constructor(j){super(j),this.crop_pct=this.config.crop_pct??224/256}async resize(j){const y=this.size?.shortest_edge;if(y===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(y<384){const T=Math.floor(y/this.crop_pct),[b,x]=this.get_resize_output_image_size(j,{shortest_edge:T});j=await j.resize(b,x,{resample:this.resample}),j=await j.center_crop(y,y)}else j=await j.resize(y,y,{resample:this.resample});return j}}class N extends ${}},"./src/models/deit/image_processing_deit.js":(ke,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>N,DeiTImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/detr/image_processing_detr.js":(ke,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>Z,DetrImageProcessor:()=>N});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/tensor.js");class N extends g.ImageProcessor{async _call(y){const T=await super._call(y),b=[T.pixel_values.dims[0],64,64],x=(0,$.full)(b,1n);return{...T,pixel_mask:x}}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 Z extends N{}},"./src/models/donut/image_processing_donut.js":(ke,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>N,DonutImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{pad_image(j,y,T,b={}){const[x,v,L]=y;let K=this.image_mean;Array.isArray(this.image_mean)||(K=new Array(L).fill(K));let se=this.image_std;Array.isArray(se)||(se=new Array(L).fill(K));const oe=K.map((V,U)=>-V/se[U]);return super.pad_image(j,y,T,{center:!0,constant_values:oe,...b})}}class N extends ${}},"./src/models/dpt/image_processing_dpt.js":(ke,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>N,DPTImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/efficientnet/image_processing_efficientnet.js":(ke,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{constructor(Z){super(Z),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(j=>j*j))}}},"./src/models/feature_extractors.js":(ke,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>g.ASTFeatureExtractor,ClapFeatureExtractor:()=>$.ClapFeatureExtractor,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>N.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>Z.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>j.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>T.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>b.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>x.WhisperFeatureExtractor});var g=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),$=r("./src/models/clap/feature_extraction_clap.js"),N=r("./src/models/moonshine/feature_extraction_moonshine.js"),Z=r("./src/models/pyannote/feature_extraction_pyannote.js"),j=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),y=r("./src/models/speecht5/feature_extraction_speecht5.js"),T=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),b=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),x=r("./src/models/whisper/feature_extraction_whisper.js"),v=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(ke,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>Z});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class Z extends g.Processor{static tokenizer_class=N.AutoTokenizer;static image_processor_class=$.AutoImageProcessor;constructor(y,T){super(y,T);const{tasks_answer_post_processing_type:b,task_prompts_without_inputs:x,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(x??{})),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 T=[];for(const b of y)if(this.task_prompts_without_inputs.has(b))T.push(this.task_prompts_without_inputs.get(b));else{for(const[x,v]of this.task_prompts_with_input)if(b.includes(x)){T.push(v.replaceAll("{input}",b).replaceAll(x,""));break}T.length!==y.length&&T.push(b)}return T}post_process_generation(y,T,b){const x=this.tasks_answer_post_processing_type.get(T)??"pure_text";y=y.replaceAll("","").replaceAll("","");let v;switch(x){case"pure_text":v=y;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const L=x==="ocr"?"quad_boxes":"bboxes",K=y.matchAll(this.regexes[L]),se=[],oe=[];for(const[V,U,...H]of K)se.push(U?U.trim():se.at(-1)??""),oe.push(H.map((I,S)=>(Number(I)+.5)/this.size_per_bin*b[S%2]));v={labels:se,[L]:oe};break;default:throw new Error(`Task "${T}" (of type "${x}") not yet implemented.`)}return{[T]:v}}async _call(y,T=null,b={}){if(!y&&!T)throw new Error("Either text or images must be provided");const x=await this.image_processor(y,b),v=T?this.tokenizer(T,b):{};return{...x,...v}}}},"./src/models/glpn/image_processing_glpn.js":(ke,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(ke,A,r)=>{r.r(A),r.d(A,{GroundingDinoImageProcessor:()=>N});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/tensor.js");class N extends g.ImageProcessor{async _call(j){const y=await super._call(j),T=y.pixel_values.dims,b=(0,$.ones)([T[0],T[2],T[3]]);return{...y,pixel_mask:b}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(ke,A,r)=>{r.r(A),r.d(A,{GroundingDinoProcessor:()=>y});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),Z=r("./src/base/image_processors_utils.js");function j(T,b){const v=T.dims.at(-1)-1,L=T.tolist();L.fill(!1,0,1),L.fill(!1,v);const K=b.tolist();return L.map((se,oe)=>se?oe:null).filter(se=>se!==null).map(se=>K[se])}class y extends g.Processor{static tokenizer_class=N.AutoTokenizer;static image_processor_class=$.AutoImageProcessor;async _call(b,x,v={}){const L=b?await this.image_processor(b,v):{};return{...x?this.tokenizer(x,v):{},...L}}post_process_grounded_object_detection(b,x,{box_threshold:v=.25,text_threshold:L=.25,target_sizes:K=null}={}){const{logits:se,pred_boxes:oe}=b,V=se.dims[0];if(K!==null&&K.length!==V)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const U=se.dims.at(1),H=se.sigmoid(),I=H.max(-1).tolist(),S=oe.tolist().map(P=>P.map(F=>(0,Z.center_to_corners_format)(F))),w=[];for(let P=0;Pre.map((Me,pe)=>Me*F[(pe+1)%2])));const ae=I[P],ie=[],ye=[],ge=[];for(let re=0;re{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>N});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/tensor.js");class N extends g.ImageProcessor{constructor(j){super(j),this.do_image_splitting=j.do_image_splitting??!0,this.max_image_size=j.max_image_size}get_resize_for_vision_encoder(j,y){let[T,b]=j.dims.slice(-2);const x=b/T;return b>=T?(b=Math.ceil(b/y)*y,T=Math.floor(b/x),T=Math.ceil(T/y)*y):(T=Math.ceil(T/y)*y,b=Math.floor(T*x),b=Math.ceil(b/y)*y),{height:T,width:b}}async _call(j,{do_image_splitting:y=null,return_row_col_info:T=!1}={}){let b;if(!Array.isArray(j))b=[[j]];else{if(j.length===0||!j[0])throw new Error("No images provided.");Array.isArray(j[0])?b=j:b=[j]}let x=[],v=[],L=[];const K=[],se=[];for(const P of b){let F=await Promise.all(P.map(ye=>this.preprocess(ye)));K.push(...F.map(ye=>ye.original_size)),se.push(...F.map(ye=>ye.reshaped_input_size)),F.forEach(ye=>ye.pixel_values.unsqueeze_(0));const{longest_edge:ae}=this.max_image_size;let ie;if(y??this.do_image_splitting){let ye=new Array(F.length),ge=new Array(F.length);ie=await Promise.all(F.map(async(re,Me)=>{const pe=this.get_resize_for_vision_encoder(re.pixel_values,ae),Ce=await(0,$.interpolate_4d)(re.pixel_values,{size:[pe.height,pe.width]}),{frames:Ae,num_splits_h:Pe,num_splits_w:Je}=await this.split_image(Ce,this.max_image_size);return ye[Me]=Pe,ge[Me]=Je,(0,$.cat)(Ae,0)})),v.push(ye),L.push(ge)}else{const ye=[ae,ae];ie=await Promise.all(F.map(ge=>(0,$.interpolate_4d)(ge.pixel_values,{size:ye}))),v.push(new Array(F.length).fill(0)),L.push(new Array(F.length).fill(0))}x.push((0,$.cat)(ie,0))}const oe=x.length,[V,U,H,I]=x[0].dims;let S,w;if(oe===1)S=x[0].unsqueeze_(0),w=(0,$.full)([oe,V,H,I],!0);else{const P=Math.max(...x.map(ie=>ie.dims.at(0)));w=(0,$.full)([oe,P,H,I],!0);const F=w.data,ae=P*H*I;for(let ie=0;ieT||L>b){K=Math.ceil(v/T),se=Math.ceil(L/b);const oe=Math.ceil(v/K),V=Math.ceil(L/se);for(let I=0;I{r.r(A),r.d(A,{Idefics3Processor:()=>b});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");var Z=r("./src/utils/core.js");function j(x,v,L,K,se,oe){let V="";for(let U=0;U`+se.repeat(x);V+=` +`}return V+=` +${K}${oe}`+se.repeat(x)+`${K}`,V}function y(x,v,L,K){return`${v}${K}`+L.repeat(x)+`${v}`}function T(x,v,L,K,se,oe){return x===0&&v===0?y(L,K,se,oe):j(L,x,v,K,se,oe)}class b extends g.Processor{static image_processor_class=$.AutoImageProcessor;static tokenizer_class=N.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(v,L=null,K={}){K.return_row_col_info??=!0;let se;L&&(se=await this.image_processor(L,K)),Array.isArray(v)||(v=[v]);const oe=se.rows??[new Array(v.length).fill(0)],V=se.cols??[new Array(v.length).fill(0)],U=this.config.image_seq_len,H=[],I=[];for(let w=0;wT(re,ae[Me],U,this.fake_image_token,this.image_token,this.global_img_token)),ye=P.split(this.image_token);if(ye.length===0)throw new Error("The image token should be present in the text.");let ge=ye[0];for(let re=0;re{r.r(A),r.d(A,{BeitFeatureExtractor:()=>g.BeitFeatureExtractor,BitImageProcessor:()=>$.BitImageProcessor,CLIPFeatureExtractor:()=>Z.CLIPFeatureExtractor,CLIPImageProcessor:()=>Z.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>N.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>j.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>j.ConvNextImageProcessor,DPTFeatureExtractor:()=>x.DPTFeatureExtractor,DPTImageProcessor:()=>x.DPTImageProcessor,DeiTFeatureExtractor:()=>y.DeiTFeatureExtractor,DeiTImageProcessor:()=>y.DeiTImageProcessor,DetrFeatureExtractor:()=>T.DetrFeatureExtractor,DetrImageProcessor:()=>T.DetrImageProcessor,DonutFeatureExtractor:()=>b.DonutFeatureExtractor,DonutImageProcessor:()=>b.DonutImageProcessor,EfficientNetImageProcessor:()=>v.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>L.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>K.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>se.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>V.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>U.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>H.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>I.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>I.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>S.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>S.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>P.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>P.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>F.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>F.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>ae.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>ae.MobileViTImageProcessor,NougatImageProcessor:()=>ie.NougatImageProcessor,OwlViTFeatureExtractor:()=>ge.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>ge.OwlViTImageProcessor,Owlv2ImageProcessor:()=>ye.Owlv2ImageProcessor,Phi3VImageProcessor:()=>re.Phi3VImageProcessor,PvtImageProcessor:()=>Me.PvtImageProcessor,Qwen2VLImageProcessor:()=>pe.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Ce.RTDetrImageProcessor,SamImageProcessor:()=>Ae.SamImageProcessor,SegformerFeatureExtractor:()=>Pe.SegformerFeatureExtractor,SegformerImageProcessor:()=>Pe.SegformerImageProcessor,SiglipImageProcessor:()=>Je.SiglipImageProcessor,Swin2SRImageProcessor:()=>je.Swin2SRImageProcessor,VLMImageProcessor:()=>oe.VLMImageProcessor,ViTFeatureExtractor:()=>_e.ViTFeatureExtractor,ViTImageProcessor:()=>_e.ViTImageProcessor,VitMatteImageProcessor:()=>X.VitMatteImageProcessor,VitPoseImageProcessor:()=>de.VitPoseImageProcessor,YolosFeatureExtractor:()=>Ee.YolosFeatureExtractor,YolosImageProcessor:()=>Ee.YolosImageProcessor});var g=r("./src/models/beit/image_processing_beit.js"),$=r("./src/models/bit/image_processing_bit.js"),N=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),Z=r("./src/models/clip/image_processing_clip.js"),j=r("./src/models/convnext/image_processing_convnext.js"),y=r("./src/models/deit/image_processing_deit.js"),T=r("./src/models/detr/image_processing_detr.js"),b=r("./src/models/donut/image_processing_donut.js"),x=r("./src/models/dpt/image_processing_dpt.js"),v=r("./src/models/efficientnet/image_processing_efficientnet.js"),L=r("./src/models/glpn/image_processing_glpn.js"),K=r("./src/models/grounding_dino/image_processing_grounding_dino.js"),se=r("./src/models/idefics3/image_processing_idefics3.js"),oe=r("./src/models/janus/image_processing_janus.js"),V=r("./src/models/jina_clip/image_processing_jina_clip.js"),U=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),H=r("./src/models/mask2former/image_processing_mask2former.js"),I=r("./src/models/maskformer/image_processing_maskformer.js"),S=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),P=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),F=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),ae=r("./src/models/mobilevit/image_processing_mobilevit.js"),ie=r("./src/models/nougat/image_processing_nougat.js"),ye=r("./src/models/owlv2/image_processing_owlv2.js"),ge=r("./src/models/owlvit/image_processing_owlvit.js"),re=r("./src/models/phi3_v/image_processing_phi3_v.js"),Me=r("./src/models/pvt/image_processing_pvt.js"),pe=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Ce=r("./src/models/rt_detr/image_processing_rt_detr.js"),Ae=r("./src/models/sam/image_processing_sam.js"),Pe=r("./src/models/segformer/image_processing_segformer.js"),Je=r("./src/models/siglip/image_processing_siglip.js"),je=r("./src/models/swin2sr/image_processing_swin2sr.js"),_e=r("./src/models/vit/image_processing_vit.js"),X=r("./src/models/vitmatte/image_processing_vitmatte.js"),de=r("./src/models/vitpose/image_processing_vitpose.js"),Ee=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(ke,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{constructor(Z){super({do_pad:!0,pad_size:{width:Z.image_size,height:Z.image_size},...Z}),this.constant_values=this.config.background_color.map(j=>j*this.rescale_factor)}pad_image(Z,j,y,T){return super.pad_image(Z,j,y,{constant_values:this.constant_values,center:!0,...T})}}},"./src/models/janus/processing_janus.js":(ke,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>T});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),Z=r("./src/utils/core.js"),j=r("./src/utils/tensor.js"),y=r("./src/utils/image.js");class T extends g.Processor{static image_processor_class=$.AutoImageProcessor;static tokenizer_class=N.AutoTokenizer;static uses_processor_config=!0;constructor(x,v){super(x,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(x,{images:v=null,chat_template:L="default"}={}){v?Array.isArray(v)||(v=[v]):v=await Promise.all(x.filter(ie=>ie.images).flatMap(ie=>ie.images).map(ie=>y.RawImage.read(ie)));const K=this.tokenizer,se=K.apply_chat_template(x,{tokenize:!1,add_generation_prompt:!0,chat_template:L}),oe=ie=>K.encode(ie,{add_special_tokens:!1}),V=se.split(this.image_tag),U=V.length-1;if(v.length!==U)throw new Error(`Number of images provided (${v.length}) does not match number of "${this.image_tag}" image tags (${U})`);const[H,I,S]=K.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=oe(V[0]),P=new Array(w.length).fill(!1);for(let ie=1;ie0){const ie=await this.image_processor(v);return ie.pixel_values.unsqueeze_(0),{...ae,...ie}}return ae}}},"./src/models/jina_clip/image_processing_jina_clip.js":(ke,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{constructor(Z){const{resize_mode:j,fill_color:y,interpolation:T,size:b,...x}=Z,v=j==="squash"?{width:b,height:b}:j==="shortest"?{shortest_edge:b}:{longest_edge:b},L=T==="bicubic"?3:2;super({...x,size:v,resample:L,do_center_crop:!0,crop_size:b,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(ke,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>Z});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class Z extends g.Processor{static tokenizer_class=N.AutoTokenizer;static image_processor_class=$.AutoImageProcessor;async _call(y=null,T=null,b={}){if(!y&&!T)throw new Error("Either text or images must be provided");const x=y?this.tokenizer(y,b):{},v=T?await this.image_processor(T,b):{};return{...x,...v}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":(ke,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(ke,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>$});var g=r("./src/models/maskformer/image_processing_maskformer.js");class $ extends g.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(ke,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>N,MaskFormerImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{post_process_panoptic_segmentation(...j){return(0,g.post_process_panoptic_segmentation)(...j)}post_process_instance_segmentation(...j){return(0,g.post_process_instance_segmentation)(...j)}}class N extends ${}},"./src/models/mgp_str/processing_mgp_str.js":(ke,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>y});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js"),Z=r("./src/utils/maths.js");const j={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class y extends g.Processor{static tokenizer_class=N.AutoTokenizer;static image_processor_class=$.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,x){if(!j.hasOwnProperty(x))throw new Error(`Format ${x} is not supported.`);const[v,L]=j[x],K=this[v].bind(this),[se,oe]=b.dims,V=[],U=[],H=b.tolist();for(let S=0;S0?F.reduce((ie,ye)=>ie*ye,1):0;U.push(P),V.push(ae)}return[K(U),V]}char_decode(b){return this.char_tokenizer.batch_decode(b).map(x=>x.replaceAll(" ",""))}bpe_decode(b){return this.bpe_tokenizer.batch_decode(b)}wp_decode(b){return this.wp_tokenizer.batch_decode(b).map(x=>x.replaceAll(" ",""))}batch_decode([b,x,v]){const[L,K]=this._decode_helper(b,"char"),[se,oe]=this._decode_helper(x,"bpe"),[V,U]=this._decode_helper(v,"wp"),H=[],I=[];for(let S=0;S{r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>N,MobileNetV1ImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(ke,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>N,MobileNetV2ImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(ke,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>N,MobileNetV3ImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(ke,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>N,MobileNetV4ImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/mobilevit/image_processing_mobilevit.js":(ke,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>N,MobileViTImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/moonshine/feature_extraction_moonshine.js":(ke,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>N});var g=r("./src/base/feature_extraction_utils.js"),$=r("./src/utils/tensor.js");class N extends g.FeatureExtractor{async _call(j){(0,g.validate_audio_inputs)(j,"MoonshineFeatureExtractor"),j instanceof Float64Array&&(j=new Float32Array(j));const y=[1,j.length];return{input_values:new $.Tensor("float32",j,y)}}}},"./src/models/moonshine/processing_moonshine.js":(ke,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>Z});var g=r("./src/models/auto/feature_extraction_auto.js"),$=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class Z extends N.Processor{static tokenizer_class=$.AutoTokenizer;static feature_extractor_class=g.AutoFeatureExtractor;async _call(y){return await this.feature_extractor(y)}}},"./src/models/nougat/image_processing_nougat.js":(ke,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>$});var g=r("./src/models/donut/image_processing_donut.js");class $ extends g.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(ke,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>$});var g=r("./src/models/owlvit/image_processing_owlvit.js");class $ extends g.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(ke,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>N,OwlViTImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{post_process_object_detection(...j){return(0,g.post_process_object_detection)(...j)}}class N extends ${}},"./src/models/owlvit/processing_owlvit.js":(ke,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>Z});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");class Z extends g.Processor{static tokenizer_class=N.AutoTokenizer;static image_processor_class=$.AutoImageProcessor}},"./src/models/paligemma/processing_paligemma.js":(ke,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>y});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");const Z="";function j(T,b,x,v,L){return`${v.repeat(x*L)}${b}${T} +`}class y extends g.Processor{static tokenizer_class=N.AutoTokenizer;static image_processor_class=$.AutoImageProcessor;static uses_processor_config=!1;async _call(b,x=null,v={}){x||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),x=""),Array.isArray(b)||(b=[b]),Array.isArray(x)||(x=[x]);const L=this.tokenizer.bos_token,K=this.image_processor.config.image_seq_length;let se;x.some(U=>U.includes(Z))?se=x.map(U=>{const H=U.replaceAll(Z,Z.repeat(K)),I=H.lastIndexOf(Z),S=I===-1?0:I+Z.length;return H.slice(0,S)+L+H.slice(S)+` +`}):(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."),se=x.map(U=>j(U,L,K,Z,b.length)));const oe=this.tokenizer(se,v);return{...await this.image_processor(b,v),...oe}}}},"./src/models/phi3_v/image_processing_phi3_v.js":(ke,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>b});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/tensor.js");const N=336,Z=[2,3],{ceil:j,floor:y,sqrt:T}=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,L){const{num_img_tokens:K}=this.config;return y((y(L/N)*y(v/N)+1)*K+1+(y(L/N)+1)*T(K))}get_resize_output_image_size(v,L){const K=this._num_crops,[se,oe]=v.size;let V=se/oe,U=1;for(;U*Math.ceil(U/V)<=K;)U+=1;U-=1;const H=Math.floor(U*336),I=Math.floor(H/V);return[H,I]}pad_image(v,L,K,se={}){const[oe,V]=L,U=N*j(oe/N),H=N*j(V/N),I=[1,1,1].map((S,w)=>(S-this.image_mean[w])/this.image_std[w]);return super.pad_image(v,L,{width:H,height:U},{center:!0,constant_values:I,...se})}async _call(v,{num_crops:L=null}={}){if(this._num_crops=L??=this.config.num_crops,L<4||T(L)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(v)||(v=[v]);const K=v.length,se=await Promise.all(v.map(P=>this.preprocess(P))),oe=se.map(P=>P.original_size),V=se.map(P=>P.reshaped_input_size),U=[];for(const{pixel_values:P}of se){P.unsqueeze_(0);const[F,ae]=P.dims.slice(-2),ie=await(0,$.interpolate_4d)(P,{size:[N,N],mode:"bicubic"});if(L>0){const ye=[],ge=T(L),re=y(ae/ge),Me=y(F/ge);for(let Ce=0;CeP.map(F=>N*j(F/N))),S=new $.Tensor("int64",I.flat(),[K,2]),w=I.map(([P,F])=>this.calc_num_image_tokens_from_image_size(F,P));return{pixel_values:H,original_sizes:oe,reshaped_input_sizes:V,image_sizes:S,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(ke,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>y});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");const Z="<|image|>",j=/<\|image_\d+\|>/g;class y extends g.Processor{static image_processor_class=$.AutoImageProcessor;static tokenizer_class=N.AutoTokenizer;async _call(b,x=null,{padding:v=!0,truncation:L=!0,num_crops:K=null}={}){Array.isArray(b)||(b=[b]);let se,oe;if(x){oe=await this.image_processor(x,{num_crops:K});const{num_img_tokens:V}=oe,U=b.map((I,S)=>I.split(j).join(Z.repeat(V[S])));se=this.tokenizer(U,{padding:v,truncation:L});const H=this.tokenizer.model.convert_tokens_to_ids([Z])[0];se.input_ids.map_(I=>I==H?-I:I)}else se=this.tokenizer(b);return{...se,...oe}}}},"./src/models/processors.js":(ke,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>g.Florence2Processor,GroundingDinoProcessor:()=>$.GroundingDinoProcessor,Idefics3Processor:()=>N.Idefics3Processor,JinaCLIPProcessor:()=>j.JinaCLIPProcessor,MgpstrProcessor:()=>y.MgpstrProcessor,MoonshineProcessor:()=>T.MoonshineProcessor,OwlViTProcessor:()=>b.OwlViTProcessor,PaliGemmaProcessor:()=>v.PaliGemmaProcessor,Phi3VProcessor:()=>x.Phi3VProcessor,PyAnnoteProcessor:()=>L.PyAnnoteProcessor,Qwen2VLProcessor:()=>K.Qwen2VLProcessor,SamProcessor:()=>se.SamProcessor,SpeechT5Processor:()=>oe.SpeechT5Processor,VLChatProcessor:()=>Z.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>V.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>U.WhisperProcessor});var g=r("./src/models/florence2/processing_florence2.js"),$=r("./src/models/grounding_dino/processing_grounding_dino.js"),N=r("./src/models/idefics3/processing_idefics3.js"),Z=r("./src/models/janus/processing_janus.js"),j=r("./src/models/jina_clip/processing_jina_clip.js"),y=r("./src/models/mgp_str/processing_mgp_str.js"),T=r("./src/models/moonshine/processing_moonshine.js"),b=r("./src/models/owlvit/processing_owlvit.js"),x=r("./src/models/phi3_v/processing_phi3_v.js"),v=r("./src/models/paligemma/processing_paligemma.js"),L=r("./src/models/pyannote/processing_pyannote.js"),K=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),se=r("./src/models/sam/processing_sam.js"),oe=r("./src/models/speecht5/processing_speecht5.js"),V=r("./src/models/wav2vec2/processing_wav2vec2.js"),U=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(ke,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(ke,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>Z});var g=r("./src/base/feature_extraction_utils.js"),$=r("./src/utils/tensor.js"),N=r("./src/utils/maths.js");class Z extends g.FeatureExtractor{async _call(y){(0,g.validate_audio_inputs)(y,"PyAnnoteFeatureExtractor"),y instanceof Float64Array&&(y=new Float32Array(y));const T=[1,1,y.length];return{input_values:new $.Tensor("float32",y,T)}}samples_to_frames(y){return(y-this.config.offset)/this.config.step}post_process_speaker_diarization(y,T){const b=T/this.samples_to_frames(T)/this.config.sampling_rate,x=[];for(const v of y.tolist()){const L=[];let K=-1;for(let se=0;se({id:se,start:oe*b,end:V*b,confidence:U/(V-oe)})))}return x}}},"./src/models/pyannote/processing_pyannote.js":(ke,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>N});var g=r("./src/base/processing_utils.js"),$=r("./src/models/pyannote/feature_extraction_pyannote.js");class N extends g.Processor{static feature_extractor_class=$.PyAnnoteFeatureExtractor;async _call(j){return await this.feature_extractor(j)}post_process_speaker_diarization(...j){return this.feature_extractor.post_process_speaker_diarization(...j)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(ke,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>N});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/tensor.js");class N extends g.ImageProcessor{async _call(j,...y){const{pixel_values:T,original_sizes:b,reshaped_input_sizes:x}=await super._call(j,...y);let v=T;const{temporal_patch_size:L,merge_size:K,patch_size:se}=this.config;v.dims[0]===1&&(v=(0,$.cat)(Array.from({length:L},()=>v),0));const oe=v.dims[0]/L,V=v.dims[1],U=Math.floor(v.dims[2]/se),H=Math.floor(v.dims[3]/se),I=v.view(oe,L,V,Math.floor(U/K),K,se,Math.floor(H/K),K,se).permute(0,3,6,4,7,2,1,5,8).view(oe*U*H,V*L*se*se),S=new $.Tensor("int64",[oe,U,H],[1,3]);return{pixel_values:I,image_grid_thw:S,original_sizes:b,reshaped_input_sizes:x}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(ke,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>Z});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js"),N=r("./src/tokenizers.js");r("./src/utils/image.js");class Z extends g.Processor{static image_processor_class=$.AutoImageProcessor;static tokenizer_class=N.AutoTokenizer;async _call(y,T=null,...b){Array.isArray(y)||(y=[y]);let x,v;if(T&&(x=await this.image_processor(T),v=x.image_grid_thw),v){let K=this.image_processor.config.merge_size**2,se=0;const oe=v.tolist();y=y.map(V=>{for(;V.includes("<|image_pad|>");){const U=Number(oe[se++].reduce((H,I)=>H*I,1n));V=V.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(U/K)))}return V.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(y),...x}}}},"./src/models/rt_detr/image_processing_rt_detr.js":(ke,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{post_process_object_detection(...Z){return(0,g.post_process_object_detection)(...Z)}}},"./src/models/sam/image_processing_sam.js":(ke,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>Z});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/core.js"),N=r("./src/utils/tensor.js");class Z extends g.ImageProcessor{reshape_input_points(y,T,b,x=!1){y=structuredClone(y);let v=(0,$.calculateDimensions)(y);if(v.length===3)x||(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 L=0;Lx!==T.dims[v]))throw Error(`The first ${b.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N.Tensor("int64",y.flat(1/0).map(BigInt),b)}async _call(y,{input_points:T=null,input_labels:b=null,input_boxes:x=null}={}){const v=await super._call(y);if(T&&(v.input_points=this.reshape_input_points(T,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 x&&(v.input_boxes=this.reshape_input_points(x,v.original_sizes,v.reshaped_input_sizes,!0)),v}async post_process_masks(y,T,b,{mask_threshold:x=0,binarize:v=!0,pad_size:L=null}={}){const K=[];L=L??this.pad_size;const se=[L.height,L.width];for(let oe=0;oex&&(S[w]=1);H=new N.Tensor("bool",S,H.dims)}K.push(H)}return K}generate_crop_boxes(y,T,{crop_n_layers:b=0,overlap_ratio:x=512/1500,points_per_crop:v=32,crop_n_points_downscale_factor:L=1}={}){}}},"./src/models/sam/processing_sam.js":(ke,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>N});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/image_processing_auto.js");class N extends g.Processor{static image_processor_class=$.AutoImageProcessor;async _call(...j){return await this.image_processor(...j)}post_process_masks(...j){return this.image_processor.post_process_masks(...j)}reshape_input_points(...j){return this.image_processor.reshape_input_points(...j)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(ke,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>Z});var g=r("./src/base/feature_extraction_utils.js"),$=r("./src/utils/tensor.js"),N=r("./src/utils/audio.js");class Z extends g.FeatureExtractor{constructor(y){super(y);const T=this.config.sampling_rate,b=(0,N.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(T/2),T,null,"kaldi",!0);for(let x=0;xb*32768),(0,N.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:T,transpose:!0})}async _call(y,{padding:T=!0,pad_to_multiple_of:b=2,do_normalize_per_mel_bins:x=!0,return_attention_mask:v=!0}={}){(0,g.validate_audio_inputs)(y,"SeamlessM4TFeatureExtractor");let L=await this._extract_fbank_features(y,this.config.max_length);if(x){const[S,w]=L.dims,P=L.data;for(let F=0;F0){const ae=new Float32Array(w*(S+F));ae.set(P),ae.fill(this.config.padding_value,P.length);const ie=S+F;L=new $.Tensor(L.type,ae,[ie,w]),v&&(K=new $.Tensor("int64",new BigInt64Array(ie),[1,ie]),K.data.fill(1n,0,S))}}const[se,oe]=L.dims,V=this.config.stride;if(se%V!==0)throw new Error(`The number of frames (${se}) must be a multiple of the stride (${V}).`);const H=L.view(1,Math.floor(se/V),oe*V),I={input_features:H};if(v){const S=H.dims[1],w=new BigInt64Array(S);if(K){const P=K.data;for(let F=1,ae=0;F{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>N,SegformerImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{post_process_semantic_segmentation(...j){return(0,g.post_process_semantic_segmentation)(...j)}}class N extends ${}},"./src/models/siglip/image_processing_siglip.js":(ke,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(ke,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>$});var g=r("./src/base/feature_extraction_utils.js");class $ extends g.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(ke,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>Z});var g=r("./src/base/processing_utils.js"),$=r("./src/tokenizers.js"),N=r("./src/models/auto/feature_extraction_auto.js");class Z extends g.Processor{static tokenizer_class=$.AutoTokenizer;static feature_extractor_class=N.AutoFeatureExtractor;async _call(y){return await this.feature_extractor(y)}}},"./src/models/swin2sr/image_processing_swin2sr.js":(ke,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{pad_image(Z,j,y,T={}){const[b,x,v]=j;return super.pad_image(Z,j,{width:x+(y-x%y)%y,height:b+(y-b%y)%y},{mode:"symmetric",center:!1,constant_values:-1,...T})}}},"./src/models/vit/image_processing_vit.js":(ke,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>N,ViTImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{}class N extends ${}},"./src/models/vitmatte/image_processing_vitmatte.js":(ke,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>N});var g=r("./src/base/image_processors_utils.js"),$=r("./src/utils/tensor.js");class N extends g.ImageProcessor{async _call(j,y){Array.isArray(j)||(j=[j]),Array.isArray(y)||(y=[y]);const T=await Promise.all(j.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,$.stack)(T.map((v,L)=>(0,$.cat)([v.pixel_values,b[L].pixel_values],0)),0),original_sizes:T.map(v=>v.original_size),reshaped_input_sizes:T.map(v=>v.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(ke,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{post_process_pose_estimation(Z,j,{threshold:y=null}={}){const T=Z.tolist(),[b,x,v,L]=Z.dims,K=[];for(let se=0;se{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>N});var g=r("./src/base/feature_extraction_utils.js"),$=r("./src/utils/tensor.js");class N extends g.FeatureExtractor{_zero_mean_unit_var_norm(j){const T=j.reduce((x,v)=>x+v,0)/j.length,b=j.reduce((x,v)=>x+(v-T)**2,0)/j.length;return j.map(x=>(x-T)/Math.sqrt(b+1e-7))}async _call(j){(0,g.validate_audio_inputs)(j,"Wav2Vec2FeatureExtractor"),j instanceof Float64Array&&(j=new Float32Array(j));let y=j;this.config.do_normalize&&(y=this._zero_mean_unit_var_norm(y));const T=[1,y.length];return{input_values:new $.Tensor("float32",y,T),attention_mask:new $.Tensor("int64",new BigInt64Array(y.length).fill(1n),T)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(ke,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>N});var g=r("./src/base/processing_utils.js"),$=r("./src/models/auto/feature_extraction_auto.js");class N extends g.Processor{static feature_extractor_class=$.AutoFeatureExtractor;async _call(j){return await this.feature_extractor(j)}}},"./src/models/wespeaker/feature_extraction_wespeaker.js":(ke,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>N});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var $=r("./src/utils/audio.js");class N extends g.FeatureExtractor{constructor(j){super(j);const y=this.config.sampling_rate,T=(0,$.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,$.spectrogram)(j,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(j){(0,g.validate_audio_inputs)(j,"WeSpeakerFeatureExtractor");const y=(await this._extract_fbank_features(j)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const T=y.mean(1).data,b=y.data,[x,v,L]=y.dims;for(let K=0;K{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>$,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>N,whisper_language_to_code:()=>Z});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"]],$=new Map(g),N=new Map([...g.map(([j,y])=>[y,j]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Z(j){j=j.toLowerCase();let y=N.get(j);if(y===void 0)if($.has(j))y=j;else{const b=j.length===2?$.keys():$.values();throw new Error(`Language "${j}" is not supported. Must be one of: ${JSON.stringify(b)}`)}return y}},"./src/models/whisper/feature_extraction_whisper.js":(ke,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>Z});var g=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var $=r("./src/utils/audio.js"),N=r("./src/utils/maths.js");class Z extends g.FeatureExtractor{constructor(y){super(y),this.config.mel_filters??=(0,$.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,$.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(y){const T=await(0,$.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=T.data,x=(0,N.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`."),T=y.slice(0,this.config.n_samples)):(T=new Float32Array(this.config.n_samples),T.set(y)),{input_features:(await this._extract_fbank_features(T)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(ke,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>$});var g=r("./src/generation/configuration_utils.js");class $ 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":(ke,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>Z});var g=r("./src/models/auto/feature_extraction_auto.js"),$=r("./src/tokenizers.js"),N=r("./src/base/processing_utils.js");class Z extends N.Processor{static tokenizer_class=$.AutoTokenizer;static feature_extractor_class=g.AutoFeatureExtractor;async _call(y){return await this.feature_extractor(y)}}},"./src/models/yolos/image_processing_yolos.js":(ke,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>N,YolosImageProcessor:()=>$});var g=r("./src/base/image_processors_utils.js");class $ extends g.ImageProcessor{post_process_object_detection(...j){return(0,g.post_process_object_detection)(...j)}}class N extends ${}},"./src/ops/registry.js":(ke,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>Z});var g=r("./src/backends/onnx.js"),$=r("./src/utils/tensor.js");const N=async(j,y,T)=>{const b=await(0,g.createInferenceSession)(new Uint8Array(j),y);return async x=>{const v=(0,g.isONNXProxy)(),L=Object.fromEntries(Object.entries(x).map(([se,oe])=>[se,(v?oe.clone():oe).ort_tensor])),K=await b.run(L);return Array.isArray(T)?T.map(se=>new $.Tensor(K[se])):new $.Tensor(K[T])}};class Z{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=N([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=N([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=N([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=N([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=N([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=N([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=N([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=N([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}},"./src/pipelines.js":(ke,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>ge,AutomaticSpeechRecognitionPipeline:()=>Me,DepthEstimationPipeline:()=>Ee,DocumentQuestionAnsweringPipeline:()=>_e,FeatureExtractionPipeline:()=>ie,FillMaskPipeline:()=>H,ImageClassificationPipeline:()=>Ce,ImageFeatureExtractionPipeline:()=>ye,ImageSegmentationPipeline:()=>Ae,ImageToImagePipeline:()=>de,ImageToTextPipeline:()=>pe,ObjectDetectionPipeline:()=>Je,Pipeline:()=>se,QuestionAnsweringPipeline:()=>U,SummarizationPipeline:()=>S,Text2TextGenerationPipeline:()=>I,TextClassificationPipeline:()=>oe,TextGenerationPipeline:()=>F,TextToAudioPipeline:()=>X,TokenClassificationPipeline:()=>V,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>re,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>Pe,ZeroShotObjectDetectionPipeline:()=>je,pipeline:()=>ee});var g=r("./src/tokenizers.js"),$=r("./src/models.js"),N=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var Z=r("./src/utils/generic.js"),j=r("./src/utils/core.js"),y=r("./src/utils/maths.js"),T=r("./src/utils/audio.js"),b=r("./src/utils/tensor.js"),x=r("./src/utils/image.js");async function v(Re){return Array.isArray(Re)||(Re=[Re]),await Promise.all(Re.map(te=>x.RawImage.read(te)))}async function L(Re,te){return Array.isArray(Re)||(Re=[Re]),await Promise.all(Re.map(ve=>typeof ve=="string"||ve instanceof URL?(0,T.read_audio)(ve,te):ve instanceof Float64Array?new Float32Array(ve):ve))}function K(Re,te){te&&(Re=Re.map(ze=>ze|0));const[ve,Ke,Ne,Ue]=Re;return{xmin:ve,ymin:Ke,xmax:Ne,ymax:Ue}}class se extends Z.Callable{constructor({task:te,model:ve,tokenizer:Ke=null,processor:Ne=null}){super(),this.task=te,this.model=ve,this.tokenizer=Ke,this.processor=Ne}async dispose(){await this.model.dispose()}}class oe extends se{constructor(te){super(te)}async _call(te,{top_k:ve=1}={}){const Ke=this.tokenizer(te,{padding:!0,truncation:!0}),Ne=await this.model(Ke),Ue=this.model.config.problem_type==="multi_label_classification"?at=>at.sigmoid():at=>new b.Tensor("float32",(0,y.softmax)(at.data),at.dims),ze=this.model.config.id2label,Ze=[];for(const at of Ne.logits){const mt=Ue(at),lt=await(0,b.topk)(mt,ve),ct=lt[0].tolist(),le=lt[1].tolist().map((Q,we)=>({label:ze?ze[Q]:`LABEL_${Q}`,score:ct[we]}));ve===1?Ze.push(...le):Ze.push(le)}return Array.isArray(te)||ve===1?Ze:Ze[0]}}class V extends se{constructor(te){super(te)}async _call(te,{ignore_labels:ve=["O"]}={}){const Ke=Array.isArray(te),Ne=this.tokenizer(Ke?te:[te],{padding:!0,truncation:!0}),ze=(await this.model(Ne)).logits,Ze=this.model.config.id2label,at=[];for(let mt=0;mttt==this.tokenizer.sep_token_id);at[ct].map((tt,st)=>tt==1&&(st===0||st>le&&mt.findIndex(ft=>ft==O[st])===-1));const Q=Ue[ct].tolist(),we=ze[ct].tolist();for(let tt=1;ttst==O[tt])!==-1)&&(Q[tt]=-1/0,we[tt]=-1/0);const Se=(0,y.softmax)(Q).map((tt,st)=>[tt,st]),We=(0,y.softmax)(we).map((tt,st)=>[tt,st]);Se[0][0]=0,We[0][0]=0;const qe=(0,j.product)(Se,We).filter(tt=>tt[0][1]<=tt[1][1]).map(tt=>[tt[0][1],tt[1][1],tt[0][0]*tt[1][0]]).sort((tt,st)=>st[2]-tt[2]);for(let tt=0;ttQ==this.tokenizer.mask_token_id);if(mt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=Ne[Ze][mt],ct=await(0,b.topk)(new b.Tensor("float32",(0,y.softmax)(lt.data),lt.dims),ve),O=ct[0].tolist(),le=ct[1].tolist();Ue.push(le.map((Q,we)=>{const Se=at.slice();return Se[mt]=Q,{score:O[we],token:Number(Q),token_str:this.tokenizer.decode([Q]),sequence:this.tokenizer.decode(Se,{skip_special_tokens:!0})}}))}return Array.isArray(te)?Ue:Ue[0]}}class I extends se{_key="generated_text";constructor(te){super(te)}async _call(te,ve={}){Array.isArray(te)||(te=[te]),this.model.config.prefix&&(te=te.map(at=>this.model.config.prefix+at));const Ke=this.model.config.task_specific_params;Ke&&Ke[this.task]&&Ke[this.task].prefix&&(te=te.map(at=>Ke[this.task].prefix+at));const Ne=this.tokenizer,Ue={padding:!0,truncation:!0};let ze;this instanceof w&&"_build_translation_inputs"in Ne?ze=Ne._build_translation_inputs(te,Ue,ve):ze=Ne(te,Ue);const Ze=await this.model.generate({...ze,...ve});return Ne.batch_decode(Ze,{skip_special_tokens:!0}).map(at=>({[this._key]:at}))}}class S extends I{_key="summary_text";constructor(te){super(te)}}class w extends I{_key="translation_text";constructor(te){super(te)}}function P(Re){return Array.isArray(Re)&&Re.every(te=>"role"in te&&"content"in te)}class F extends se{constructor(te){super(te)}async _call(te,ve={}){let Ke=!1,Ne=!1,Ue;if(typeof te=="string")Ue=te=[te];else if(Array.isArray(te)&&te.every(le=>typeof le=="string"))Ke=!0,Ue=te;else{if(P(te))te=[te];else if(Array.isArray(te)&&te.every(P))Ke=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ne=!0,Ue=te.map(le=>this.tokenizer.apply_chat_template(le,{tokenize:!1,add_generation_prompt:!0}))}const ze=ve.add_special_tokens??!1,Ze=Ne?!1:ve.return_full_text??!0;this.tokenizer.padding_side="left";const at=this.tokenizer(Ue,{add_special_tokens:ze,padding:!0,truncation:!0}),mt=await this.model.generate({...at,...ve}),lt=this.tokenizer.batch_decode(mt,{skip_special_tokens:!0});let ct;!Ze&&at.input_ids.dims.at(-1)>0&&(ct=this.tokenizer.batch_decode(at.input_ids,{skip_special_tokens:!0}).map(le=>le.length));const O=Array.from({length:te.length},le=>[]);for(let le=0;le[ve.toLowerCase(),Ke])),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(te,ve,{hypothesis_template:Ke="This example is {}.",multi_label:Ne=!1}={}){const Ue=Array.isArray(te);Ue||(te=[te]),Array.isArray(ve)||(ve=[ve]);const ze=ve.map(mt=>Ke.replace("{}",mt)),Ze=Ne||ve.length===1,at=[];for(const mt of te){const lt=[];for(const le of ze){const Q=this.tokenizer(mt,{text_pair:le,padding:!0,truncation:!0}),we=await this.model(Q);Ze?lt.push([we.logits.data[this.contradiction_id],we.logits.data[this.entailment_id]]):lt.push(we.logits.data[this.entailment_id])}const O=(Ze?lt.map(le=>(0,y.softmax)(le)[1]):(0,y.softmax)(lt)).map((le,Q)=>[le,Q]).sort((le,Q)=>Q[0]-le[0]);at.push({sequence:mt,labels:O.map(le=>ve[le[1]]),scores:O.map(le=>le[0])})}return Ue?at:at[0]}}class ie extends se{constructor(te){super(te)}async _call(te,{pooling:ve="none",normalize:Ke=!1,quantize:Ne=!1,precision:Ue="binary"}={}){const ze=this.tokenizer(te,{padding:!0,truncation:!0}),Ze=await this.model(ze);let at=Ze.last_hidden_state??Ze.logits??Ze.token_embeddings;if(ve!=="none")if(ve==="mean")at=(0,b.mean_pooling)(at,ze.attention_mask);else if(ve==="cls")at=at.slice(null,0);else throw Error(`Pooling method '${ve}' not supported.`);return Ke&&(at=at.normalize(2,-1)),Ne&&(at=(0,b.quantize_embeddings)(at,Ue)),at}}class ye extends se{constructor(te){super(te)}async _call(te,{pool:ve=null}={}){const Ke=await v(te),{pixel_values:Ne}=await this.processor(Ke),Ue=await this.model({pixel_values:Ne});let ze;if(ve){if(!("pooler_output"in Ue))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");ze=Ue.pooler_output}else ze=Ue.last_hidden_state??Ue.logits??Ue.image_embeds;return ze}}class ge extends se{constructor(te){super(te)}async _call(te,{top_k:ve=5}={}){const Ke=this.processor.feature_extractor.config.sampling_rate,Ne=await L(te,Ke),Ue=this.model.config.id2label,ze=[];for(const Ze of Ne){const at=await this.processor(Ze),lt=(await this.model(at)).logits[0],ct=await(0,b.topk)(new b.Tensor("float32",(0,y.softmax)(lt.data),lt.dims),ve),O=ct[0].tolist(),Q=ct[1].tolist().map((we,Se)=>({label:Ue?Ue[we]:`LABEL_${we}`,score:O[Se]}));ze.push(Q)}return Array.isArray(te)?ze:ze[0]}}class re extends se{constructor(te){super(te)}async _call(te,ve,{hypothesis_template:Ke="This is a sound of {}."}={}){const Ne=!Array.isArray(te);Ne&&(te=[te]);const Ue=ve.map(lt=>Ke.replace("{}",lt)),ze=this.tokenizer(Ue,{padding:!0,truncation:!0}),Ze=this.processor.feature_extractor.config.sampling_rate,at=await L(te,Ze),mt=[];for(const lt of at){const ct=await this.processor(lt),O=await this.model({...ze,...ct}),le=(0,y.softmax)(O.logits_per_audio.data);mt.push([...le].map((Q,we)=>({score:Q,label:ve[we]})))}return Ne?mt[0]:mt}}class Me extends se{constructor(te){super(te)}async _call(te,ve={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(te,ve);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(te,ve);case"moonshine":return this._call_moonshine(te,ve);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(te,ve){ve.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ve.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ke=!Array.isArray(te);Ke&&(te=[te]);const Ne=this.processor.feature_extractor.config.sampling_rate,Ue=await L(te,Ne),ze=[];for(const Ze of Ue){const at=await this.processor(Ze),lt=(await this.model(at)).logits[0],ct=[];for(const le of lt)ct.push((0,y.max)(le.data)[1]);const O=this.tokenizer.decode(ct);ze.push({text:O})}return Ke?ze[0]:ze}async _call_whisper(te,ve){const Ke=ve.return_timestamps??!1,Ne=ve.chunk_length_s??0,Ue=ve.force_full_sequences??!1;let ze=ve.stride_length_s??null;const Ze={...ve};Ke==="word"&&(Ze.return_token_timestamps=!0,Ze.return_timestamps=!1);const at=!Array.isArray(te);at&&(te=[te]);const mt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,lt=this.processor.feature_extractor.config.hop_length,ct=this.processor.feature_extractor.config.sampling_rate,O=await L(te,ct),le=[];for(const Q of O){let we=[];if(Ne>0){if(ze===null)ze=Ne/6;else if(Ne<=ze)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const qe=ct*Ne,tt=ct*ze,st=qe-2*tt;let ft=0;for(;;){const Nt=ft+qe,ss=Q.subarray(ft,Nt),Ts=await this.processor(ss),ms=ft===0,Ps=Nt>=Q.length;if(we.push({stride:[ss.length,ms?0:tt,Ps?0:tt],input_features:Ts.input_features,is_last:Ps}),Ps)break;ft+=st}}else we=[{stride:[Q.length,0,0],input_features:(await this.processor(Q)).input_features,is_last:!0}];for(const qe of we){Ze.num_frames=Math.floor(qe.stride[0]/lt);const tt=await this.model.generate({inputs:qe.input_features,...Ze});Ke==="word"?(qe.tokens=tt.sequences.tolist()[0],qe.token_timestamps=tt.token_timestamps.tolist()[0].map(st=>(0,y.round)(st,2))):qe.tokens=tt[0].tolist(),qe.stride=qe.stride.map(st=>st/ct)}const[Se,We]=this.tokenizer._decode_asr(we,{time_precision:mt,return_timestamps:Ke,force_full_sequences:Ue});le.push({text:Se,...We})}return at?le[0]:le}async _call_moonshine(te,ve){const Ke=!Array.isArray(te);Ke&&(te=[te]);const Ne=this.processor.feature_extractor.config.sampling_rate,Ue=await L(te,Ne),ze=[];for(const Ze of Ue){const at=await this.processor(Ze),mt=Math.floor(Ze.length/Ne)*6,lt=await this.model.generate({max_new_tokens:mt,...ve,...at}),ct=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];ze.push({text:ct})}return Ke?ze[0]:ze}}class pe extends se{constructor(te){super(te)}async _call(te,ve={}){const Ke=Array.isArray(te),Ne=await v(te),{pixel_values:Ue}=await this.processor(Ne),ze=[];for(const Ze of Ue){Ze.dims=[1,...Ze.dims];const at=await this.model.generate({inputs:Ze,...ve}),mt=this.tokenizer.batch_decode(at,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));ze.push(mt)}return Ke?ze:ze[0]}}class Ce extends se{constructor(te){super(te)}async _call(te,{top_k:ve=5}={}){const Ke=await v(te),{pixel_values:Ne}=await this.processor(Ke),Ue=await this.model({pixel_values:Ne}),ze=this.model.config.id2label,Ze=[];for(const at of Ue.logits){const mt=await(0,b.topk)(new b.Tensor("float32",(0,y.softmax)(at.data),at.dims),ve),lt=mt[0].tolist(),O=mt[1].tolist().map((le,Q)=>({label:ze?ze[le]:`LABEL_${le}`,score:lt[Q]}));Ze.push(O)}return Array.isArray(te)?Ze:Ze[0]}}class Ae extends se{constructor(te){super(te),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(te,{threshold:ve=.5,mask_threshold:Ke=.5,overlap_mask_area_threshold:Ne=.8,label_ids_to_fuse:Ue=null,target_sizes:ze=null,subtask:Ze=null}={}){if(Array.isArray(te)&&te.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const mt=await v(te),lt=mt.map(We=>[We.height,We.width]),{pixel_values:ct,pixel_mask:O}=await this.processor(mt),le=await this.model({pixel_values:ct,pixel_mask:O});let Q=null;if(Ze!==null)Q=this.subtasks_mapping[Ze];else for(let[We,qe]of Object.entries(this.subtasks_mapping))if(qe in this.processor.image_processor){Q=this.processor.image_processor[qe].bind(this.processor.image_processor),Ze=We;break}const we=this.model.config.id2label,Se=[];if(Ze==="panoptic"||Ze==="instance"){const We=Q(le,ve,Ke,Ne,Ue,ze??lt)[0],qe=We.segmentation;for(const tt of We.segments_info){const st=new Uint8ClampedArray(qe.data.length);for(let Nt=0;NtKe.replace("{}",O)),Ze=this.tokenizer(ze,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:at}=await this.processor(Ue),mt=await this.model({...Ze,pixel_values:at}),lt=this.model.config.model_type==="siglip"?O=>O.sigmoid().data:O=>(0,y.softmax)(O.data),ct=[];for(const O of mt.logits_per_image){const Q=[...lt(O)].map((we,Se)=>({score:we,label:ve[Se]}));Q.sort((we,Se)=>Se.score-we.score),ct.push(Q)}return Ne?ct:ct[0]}}class Je extends se{constructor(te){super(te)}async _call(te,{threshold:ve=.9,percentage:Ke=!1}={}){const Ne=Array.isArray(te);if(Ne&&te.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ue=await v(te),ze=Ke?null:Ue.map(le=>[le.height,le.width]),{pixel_values:Ze,pixel_mask:at}=await this.processor(Ue),mt=await this.model({pixel_values:Ze,pixel_mask:at}),lt=this.processor.image_processor.post_process_object_detection(mt,ve,ze),ct=this.model.config.id2label,O=lt.map(le=>le.boxes.map((Q,we)=>({score:le.scores[we],label:ct[le.classes[we]],box:K(Q,!Ke)})));return Ne?O:O[0]}}class je extends se{constructor(te){super(te)}async _call(te,ve,{threshold:Ke=.1,top_k:Ne=null,percentage:Ue=!1}={}){const ze=Array.isArray(te),Ze=await v(te),at=this.tokenizer(ve,{padding:!0,truncation:!0}),mt=await this.processor(Ze),lt=[];for(let ct=0;ct({score:We.scores[tt],label:We.labels[tt],box:K(qe,!Ue)}))}else{const We=this.processor.image_processor.post_process_object_detection(we,Ke,le,!0)[0];Se=We.boxes.map((qe,tt)=>({score:We.scores[tt],label:ve[We.classes[tt]],box:K(qe,!Ue)}))}Se.sort((We,qe)=>qe.score-We.score),Ne!==null&&(Se=Se.slice(0,Ne)),lt.push(Se)}return ze?lt:lt[0]}}class _e extends se{constructor(te){super(te)}async _call(te,ve,Ke={}){const Ne=(await v(te))[0],{pixel_values:Ue}=await this.processor(Ne),ze=`${ve}`,Ze=this.tokenizer(ze,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,at=await this.model.generate({inputs:Ue,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ze,...Ke}),lt=this.tokenizer.batch_decode(at)[0].match(/(.*?)<\/s_answer>/);let ct=null;return lt&<.length>=2&&(ct=lt[1].trim()),[{answer:ct}]}}class X extends se{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(te){super(te),this.vocoder=te.vocoder??null}async _call(te,{speaker_embeddings:ve=null}={}){return this.processor?this._call_text_to_spectrogram(te,{speaker_embeddings:ve}):this._call_text_to_waveform(te)}async _call_text_to_waveform(te){const ve=this.tokenizer(te,{padding:!0,truncation:!0}),{waveform:Ke}=await this.model(ve),Ne=this.model.config.sampling_rate;return new T.RawAudio(Ke.data,Ne)}async _call_text_to_spectrogram(te,{speaker_embeddings:ve}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await $.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof ve=="string"||ve instanceof URL)&&(ve=new Float32Array(await(await fetch(ve)).arrayBuffer())),ve instanceof Float32Array)ve=new b.Tensor("float32",ve,[1,ve.length]);else if(!(ve instanceof b.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ke}=this.tokenizer(te,{padding:!0,truncation:!0}),{waveform:Ne}=await this.model.generate_speech(Ke,ve,{vocoder:this.vocoder}),Ue=this.processor.feature_extractor.config.sampling_rate;return new T.RawAudio(Ne.data,Ue)}}class de extends se{constructor(te){super(te)}async _call(te){const ve=await v(te),Ke=await this.processor(ve),Ne=await this.model(Ke),Ue=[];for(const ze of Ne.reconstruction){const Ze=ze.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ue.push(x.RawImage.fromTensor(Ze))}return Ue.length>1?Ue:Ue[0]}}class Ee extends se{constructor(te){super(te)}async _call(te){const ve=await v(te),Ke=await this.processor(ve),{predicted_depth:Ne}=await this.model(Ke),Ue=[];for(let ze=0;ze1?Ue:Ue[0]}}const Oe=Object.freeze({"text-classification":{tokenizer:g.AutoTokenizer,pipeline:oe,model:$.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:g.AutoTokenizer,pipeline:V,model:$.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:g.AutoTokenizer,pipeline:U,model:$.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:g.AutoTokenizer,pipeline:H,model:$.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:g.AutoTokenizer,pipeline:S,model:$.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:g.AutoTokenizer,pipeline:w,model:$.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:g.AutoTokenizer,pipeline:I,model:$.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:g.AutoTokenizer,pipeline:F,model:$.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:g.AutoTokenizer,pipeline:ae,model:$.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ge,model:$.AutoModelForAudioClassification,processor:N.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:g.AutoTokenizer,pipeline:re,model:$.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:g.AutoTokenizer,pipeline:Me,model:[$.AutoModelForSpeechSeq2Seq,$.AutoModelForCTC],processor:N.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:g.AutoTokenizer,pipeline:X,model:[$.AutoModelForTextToWaveform,$.AutoModelForTextToSpectrogram],processor:[N.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:g.AutoTokenizer,pipeline:pe,model:$.AutoModelForVision2Seq,processor:N.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Ce,model:$.AutoModelForImageClassification,processor:N.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ae,model:[$.AutoModelForImageSegmentation,$.AutoModelForSemanticSegmentation,$.AutoModelForUniversalSegmentation],processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:g.AutoTokenizer,pipeline:Pe,model:$.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Je,model:$.AutoModelForObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:g.AutoTokenizer,pipeline:je,model:$.AutoModelForZeroShotObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:g.AutoTokenizer,pipeline:_e,model:$.AutoModelForDocumentQuestionAnswering,processor:N.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:de,model:$.AutoModelForImageToImage,processor:N.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ee,model:$.AutoModelForDepthEstimation,processor:N.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:g.AutoTokenizer,pipeline:ie,model:$.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:N.AutoProcessor,pipeline:ye,model:[$.AutoModelForImageFeatureExtraction,$.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Xe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ee(Re,te=null,{progress_callback:ve=null,config:Ke=null,cache_dir:Ne=null,local_files_only:Ue=!1,revision:ze="main",device:Ze=null,dtype:at=null,model_file_name:mt=null,session_options:lt={}}={}){Re=Xe[Re]??Re;const ct=Oe[Re.split("_",1)[0]];if(!ct)throw Error(`Unsupported pipeline: ${Re}. Must be one of [${Object.keys(Oe)}]`);te||(te=ct.default.model,console.log(`No model specified. Using default model: "${te}".`));const O={progress_callback:ve,config:Ke,cache_dir:Ne,local_files_only:Ue,revision:ze,device:Ze,dtype:at,model_file_name:mt,session_options:lt},le=new Map([["tokenizer",ct.tokenizer],["model",ct.model],["processor",ct.processor]]),Q=await Ve(le,te,O);Q.task=Re,(0,j.dispatchCallback)(ve,{status:"ready",task:Re,model:te});const we=ct.pipeline;return new we(Q)}async function Ve(Re,te,ve){const Ke=Object.create(null),Ne=[];for(const[Ue,ze]of Re.entries()){if(!ze)continue;let Ze;Array.isArray(ze)?Ze=new Promise(async(at,mt)=>{let lt;for(const ct of ze){if(ct===null){at(null);return}try{at(await ct.from_pretrained(te,ve));return}catch(O){if(O.message?.includes("Unsupported model type"))lt=O;else if(O.message?.includes("Could not locate file"))lt=O;else{mt(O);return}}}mt(lt)}):Ze=ze.from_pretrained(te,ve),Ke[Ue]=Ze,Ne.push(Ze)}await Promise.all(Ne);for(const[Ue,ze]of Object.entries(Ke))Ke[Ue]=await ze;return Ke}},"./src/tokenizers.js":(ke,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>Pr,AutoTokenizer:()=>as,BartTokenizer:()=>dn,BertTokenizer:()=>Kr,BlenderbotSmallTokenizer:()=>Fn,BlenderbotTokenizer:()=>In,BloomTokenizer:()=>Qr,CLIPTokenizer:()=>mn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>hn,CodeLlamaTokenizer:()=>zr,CohereTokenizer:()=>gn,ConvBertTokenizer:()=>Dr,DebertaTokenizer:()=>dr,DebertaV2Tokenizer:()=>qr,DistilBertTokenizer:()=>or,ElectraTokenizer:()=>Ft,EsmTokenizer:()=>Br,FalconTokenizer:()=>Sn,GPT2Tokenizer:()=>Cn,GPTNeoXTokenizer:()=>$n,GemmaTokenizer:()=>Zn,Grok1Tokenizer:()=>Rr,HerbertTokenizer:()=>Cr,LlamaTokenizer:()=>cn,M2M100Tokenizer:()=>pn,MBart50Tokenizer:()=>br,MBartTokenizer:()=>gs,MPNetTokenizer:()=>kn,MarianTokenizer:()=>Ot,MgpstrTokenizer:()=>Ln,MobileBertTokenizer:()=>Er,NllbTokenizer:()=>ar,NougatTokenizer:()=>Nr,PreTrainedTokenizer:()=>Lt,Qwen2Tokenizer:()=>An,RoFormerTokenizer:()=>Lr,RobertaTokenizer:()=>Ls,SiglipTokenizer:()=>fn,SpeechT5Tokenizer:()=>On,SqueezeBertTokenizer:()=>Hr,T5Tokenizer:()=>Ys,TokenizerModel:()=>ye,VitsTokenizer:()=>Dn,Wav2Vec2CTCTokenizer:()=>_n,WhisperTokenizer:()=>Xr,XLMRobertaTokenizer:()=>Jn,XLMTokenizer:()=>vt,is_chinese_char:()=>H});var g=r("./src/utils/generic.js"),$=r("./src/utils/core.js"),N=r("./src/utils/hub.js"),Z=r("./src/utils/maths.js"),j=r("./src/utils/tensor.js"),y=r("./src/utils/data-structures.js"),T=r("./node_modules/@huggingface/jinja/dist/index.js"),b=r("./src/models/whisper/common_whisper.js");async function x(Te,M){const Y=await Promise.all([(0,N.getModelJSON)(Te,"tokenizer.json",!0,M),(0,N.getModelJSON)(Te,"tokenizer_config.json",!0,M)]);return M.legacy!==null&&(Y[1].legacy=M.legacy),Y}function v(Te,M){const Y=[];let ce=0;for(const me of Te.matchAll(M)){const Fe=me[0];ce0&&Y.push(Fe),ce=me.index+Fe.length}return ce=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 I(Te,M,Y){const ce=[];let me=0;for(;methis.tokens_to_ids.get(Y)??this.unk_token_id)}convert_ids_to_tokens(M){return M.map(Y=>this.vocab[Y]??this.unk_token)}}class ge extends ye{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[Y,ce]of this.tokens_to_ids)this.vocab[ce]=Y}encode(M){const Y=[];for(const ce of M){const me=[...ce];if(me.length>this.max_input_chars_per_word){Y.push(this.unk_token);continue}let Fe=!1,Ye=0;const gt=[];for(;Ye0&&(pt=this.config.continuing_subword_prefix+pt),this.tokens_to_ids.has(pt)){yt=pt;break}--wt}if(yt===null){Fe=!0;break}gt.push(yt),Ye=wt}Fe?Y.push(this.unk_token):Y.push(...gt)}return Y}}class re extends ye{constructor(M,Y){super(M);const ce=M.vocab.length;this.vocab=new Array(ce),this.scores=new Array(ce);for(let me=0;me[me,Fe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Y.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,Z.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 Y=M.chars,ce=1;let me=0;for(;me{const Te=[...Array.from({length:94},(me,Fe)=>Fe+33),...Array.from({length:12},(me,Fe)=>Fe+161),...Array.from({length:82},(me,Fe)=>Fe+174)],M=Te.slice();let Y=0;for(let me=0;me<256;++me)Te.includes(me)||(Te.push(me),M.push(256+Y),Y+=1);const ce=M.map(me=>String.fromCharCode(me));return Object.fromEntries(Te.map((me,Fe)=>[me,ce[Fe]]))})(),pe=(0,$.reverseDictionary)(Me);class Ce extends ye{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[ce,me]of this.tokens_to_ids)this.vocab[me]=ce;const Y=Array.isArray(M.merges[0]);this.merges=Y?M.merges:M.merges.map(ce=>ce.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ce,me)=>[JSON.stringify(ce),me])),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 Y=this.cache.get(M);if(Y!==void 0)return Y;const ce=Array.from(M);this.end_of_word_suffix&&(ce[ce.length-1]+=this.end_of_word_suffix);let me=[];if(ce.length>1){const Fe=new y.PriorityQueue((wt,yt)=>wt.score`<0x${gt.toString(16).toUpperCase().padStart(2,"0")}>`);Ye.every(gt=>this.tokens_to_ids.has(gt))?Y.push(...Ye):Y.push(this.unk_token)}else Y.push(this.unk_token)}return Y}}class Ae extends ye{constructor(M,Y){super(M),this.tokens_to_ids=K(Y.target_lang?M.vocab[Y.target_lang]:M.vocab),this.bos_token=Y.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Y.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=Y.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=Y.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[ce,me]of this.tokens_to_ids)this.vocab[me]=ce}encode(M){return M}}class Pe extends g.Callable{constructor(M){super(),this.config=M}static fromConfig(M){if(M===null)return null;switch(M.type){case"BertNormalizer":return new Ve(M);case"Precompiled":return new ms(M);case"Sequence":return new ee(M);case"Replace":return new Je(M);case"NFC":return new je(M);case"NFKC":return new _e(M);case"NFKD":return new X(M);case"Strip":return new de(M);case"StripAccents":return new Ee(M);case"Lowercase":return new Oe(M);case"Prepend":return new Xe(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 Je extends Pe{normalize(M){const Y=L(this.config.pattern);return Y===null?M:M.replaceAll(Y,this.config.content)}}class je extends Pe{normalize(M){return M=M.normalize("NFC"),M}}class _e extends Pe{normalize(M){return M=M.normalize("NFKC"),M}}class X extends Pe{normalize(M){return M=M.normalize("NFKD"),M}}class de extends Pe{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 Ee extends Pe{normalize(M){return M=V(M),M}}class Oe extends Pe{normalize(M){return M=M.toLowerCase(),M}}class Xe extends Pe{normalize(M){return M=this.config.prepend+M,M}}class ee extends Pe{constructor(M){super(M),this.normalizers=M.normalizers.map(Y=>Pe.fromConfig(Y))}normalize(M){return this.normalizers.reduce((Y,ce)=>ce.normalize(Y),M)}}class Ve extends Pe{_tokenize_chinese_chars(M){const Y=[];for(let ce=0;cethis.pre_tokenize_text(ce,Y)):this.pre_tokenize_text(M,Y)).flat()}_call(M,Y){return this.pre_tokenize(M,Y)}}class te extends Re{constructor(M){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(M,Y){return M.trim().match(this.pattern)||[]}}class ve extends Re{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=Me,this.text_encoder=new TextEncoder}pre_tokenize_text(M,Y){return this.add_prefix_space&&!M.startsWith(" ")&&(M=" "+M),(this.use_regex?M.match(this.pattern)||[]:[M]).map(me=>Array.from(this.text_encoder.encode(me),Fe=>this.byte_encoder[Fe]).join(""))}}class Ke extends Re{constructor(M){super(),this.config=M,this.pattern=L(this.config.pattern,this.config.invert)}pre_tokenize_text(M,Y){return this.pattern===null?[]:this.config.invert?M.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?M.split(this.pattern).filter(ce=>ce):v(M,this.pattern)}}class Ne extends Re{constructor(M){super(),this.config=M,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(M,Y){return M.match(this.pattern)||[]}}class Ue extends Re{constructor(M){super(),this.config=M;const Y=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Y,"gu")}pre_tokenize_text(M,Y){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 mt(M);case"ByteLevel":return new lt(M);case"RobertaProcessing":return new at(M);case"BertProcessing":return new Ze(M);case"Sequence":return new ct(M);default:throw new Error(`Unknown PostProcessor type: ${M.type}`)}}post_process(M,...Y){throw Error("post_process should be implemented in subclass.")}_call(M,...Y){return this.post_process(M,...Y)}}class Ze extends ze{constructor(M){super(M),this.cls=M.cls[0],this.sep=M.sep[0]}post_process(M,Y=null,{add_special_tokens:ce=!0}={}){ce&&(M=(0,$.mergeArrays)([this.cls],M,[this.sep]));let me=new Array(M.length).fill(0);if(Y!==null){const Fe=ce&&this instanceof at?[this.sep]:[],Ye=ce?[this.sep]:[];M=(0,$.mergeArrays)(M,Fe,Y,Ye),me=(0,$.mergeArrays)(me,new Array(Y.length+Fe.length+Ye.length).fill(1))}return{tokens:M,token_type_ids:me}}}class at extends Ze{}class mt extends ze{constructor(M){super(M),this.single=M.single,this.pair=M.pair}post_process(M,Y=null,{add_special_tokens:ce=!0}={}){const me=Y===null?this.single:this.pair;let Fe=[],Ye=[];for(const gt of me)"SpecialToken"in gt?ce&&(Fe.push(gt.SpecialToken.id),Ye.push(gt.SpecialToken.type_id)):"Sequence"in gt&&(gt.Sequence.id==="A"?(Fe=(0,$.mergeArrays)(Fe,M),Ye=(0,$.mergeArrays)(Ye,new Array(M.length).fill(gt.Sequence.type_id))):gt.Sequence.id==="B"&&(Fe=(0,$.mergeArrays)(Fe,Y),Ye=(0,$.mergeArrays)(Ye,new Array(Y.length).fill(gt.Sequence.type_id))));return{tokens:Fe,token_type_ids:Ye}}}class lt extends ze{post_process(M,Y=null){return Y&&(M=(0,$.mergeArrays)(M,Y)),{tokens:M}}}class ct extends ze{constructor(M){super(M),this.processors=M.processors.map(Y=>ze.fromConfig(Y))}post_process(M,Y=null,ce={}){let me;for(const Fe of this.processors)if(Fe instanceof lt)M=Fe.post_process(M).tokens,Y&&(Y=Fe.post_process(Y).tokens);else{const Ye=Fe.post_process(M,Y,ce);M=Ye.tokens,me=Ye.token_type_ids}return{tokens:M,token_type_ids:me}}}class O 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 We(M);case"Metaspace":return new Ts(M);case"ByteLevel":return new qe(M);case"Replace":return new le(M);case"ByteFallback":return new Q(M);case"Fuse":return new we(M);case"Strip":return new Se(M);case"Sequence":return new st(M);case"CTC":return new tt(M);case"BPEDecoder":return new ft(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 le extends O{decode_chain(M){const Y=L(this.config.pattern);return Y===null?M:M.map(ce=>ce.replaceAll(Y,this.config.content))}}class Q extends O{constructor(M){super(M),this.text_decoder=new TextDecoder}decode_chain(M){const Y=[];let ce=[];for(const me of M){let Fe=null;if(me.length===6&&me.startsWith("<0x")&&me.endsWith(">")){const Ye=parseInt(me.slice(3,5),16);isNaN(Ye)||(Fe=Ye)}if(Fe!==null)ce.push(Fe);else{if(ce.length>0){const Ye=this.text_decoder.decode(Uint8Array.from(ce));Y.push(Ye),ce=[]}Y.push(me)}}if(ce.length>0){const me=this.text_decoder.decode(Uint8Array.from(ce));Y.push(me),ce=[]}return Y}}class we extends O{decode_chain(M){return[M.join("")]}}class Se extends O{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(Y=>{let ce=0;for(let Fe=0;Fe(ce!==0&&(Y.startsWith(this.config.prefix)?Y=Y.replace(this.config.prefix,""):Y=" "+Y),this.cleanup&&(Y=oe(Y)),Y))}}class qe extends O{constructor(M){super(M),this.byte_decoder=pe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(M){const Y=M.join(""),ce=new Uint8Array([...Y].map(Fe=>this.byte_decoder[Fe]));return this.text_decoder.decode(ce)}decode_chain(M){const Y=[];let ce=[];for(const me of M)this.added_tokens.find(Fe=>Fe.content===me)!==void 0?(ce.length>0&&(Y.push(this.convert_tokens_to_string(ce)),ce=[]),Y.push(me)):ce.push(me);return ce.length>0&&Y.push(this.convert_tokens_to_string(ce)),Y}}class tt extends O{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 Y=[M[0]];for(let Fe=1;FeFe!==this.pad_token).join("");return this.cleanup&&(me=oe(me).replaceAll(this.word_delimiter_token," ").trim()),me}decode_chain(M){return[this.convert_tokens_to_string(M)]}}class st extends O{constructor(M){super(M),this.decoders=M.decoders.map(Y=>O.fromConfig(Y))}decode_chain(M){return this.decoders.reduce((Y,ce)=>ce.decode_chain(Y),M)}}class ft extends O{constructor(M){super(M),this.suffix=this.config.suffix}decode_chain(M){return M.map((Y,ce)=>Y.replaceAll(this.suffix,ce===M.length-1?"":" "))}}class Nt extends O{decode_chain(M){let Y="";for(let ce=1;cece.normalize("NFKC")).join("~"):M=M.normalize("NFKC"),M}}class Ps extends Re{constructor(M){super(),this.tokenizers=M.pretokenizers.map(Y=>Re.fromConfig(Y))}pre_tokenize_text(M,Y){return this.tokenizers.reduce((ce,me)=>me.pre_tokenize(ce,Y),[M])}}class As extends Re{constructor(M){super()}pre_tokenize_text(M,Y){return M.match(/\w+|[^\w\s]+/g)||[]}}class tr extends Re{constructor(M){super()}pre_tokenize_text(M,Y){return S(M)}}class Tr extends Re{constructor(M){super(),this.config=M,this.pattern=L(this.config.pattern),this.content=this.config.content}pre_tokenize_text(M,Y){return this.pattern===null?[M]:[M.replaceAll(this.pattern,this.config.content)]}}const Gr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ns(Te,M,Y,ce){for(const me of Object.keys(Te)){const Fe=M-Te[me].length,Ye=Y(me),gt=new Array(Fe).fill(Ye);Te[me]=ce==="right"?(0,$.mergeArrays)(Te[me],gt):(0,$.mergeArrays)(gt,Te[me])}}function Mr(Te,M){for(const Y of Object.keys(Te))Te[Y].length=M}class Lt extends g.Callable{return_token_type_ids=!1;padding_side="right";constructor(M,Y){super(),this._tokenizer_config=Y,this.normalizer=Pe.fromConfig(M.normalizer),this.pre_tokenizer=Re.fromConfig(M.pre_tokenizer),this.model=ye.fromConfig(M.model,Y),this.post_processor=ze.fromConfig(M.post_processor),this.decoder=O.fromConfig(M.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ce of M.added_tokens){const me=new ie(ce);this.added_tokens.push(me),this.model.tokens_to_ids.set(me.content,me.id),this.model.vocab[me.id]=me.content,me.special&&(this.special_tokens.push(me.content),this.all_special_ids.push(me.id))}if(this.additional_special_tokens=Y.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((ce,me)=>me.content.length-ce.content.length).map(ce=>`${ce.lstrip?"\\s*":""}(${(0,$.escapeRegExp)(ce.content)})${ce.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=Y.model_max_length,this.remove_space=Y.remove_space,this.clean_up_tokenization_spaces=Y.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Y.do_lowercase_and_remove_accent??!1,Y.padding_side&&(this.padding_side=Y.padding_side),this.legacy=!1,this.chat_template=Y.chat_template??null,Array.isArray(this.chat_template)){const ce=Object.create(null);for(const{name:me,template:Fe}of this.chat_template){if(typeof me!="string"||typeof Fe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ce[me]=Fe}this.chat_template=ce}this._compiled_template_cache=new Map}getToken(...M){for(const Y of M){const ce=this._tokenizer_config[Y];if(ce)if(typeof ce=="object"){if(ce.__type==="AddedToken")return ce.content;throw Error(`Unknown token: ${ce}`)}else return ce}return null}static async from_pretrained(M,{progress_callback:Y=null,config:ce=null,cache_dir:me=null,local_files_only:Fe=!1,revision:Ye="main",legacy:gt=null}={}){const wt=await x(M,{progress_callback:Y,config:ce,cache_dir:me,local_files_only:Fe,revision:Ye,legacy:gt});return new this(...wt)}_call(M,{text_pair:Y=null,add_special_tokens:ce=!0,padding:me=!1,truncation:Fe=null,max_length:Ye=null,return_tensor:gt=!0,return_token_type_ids:wt=null}={}){const yt=Array.isArray(M);let pt;if(yt){if(M.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(M.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");pt=M.map((Yt,Ms)=>this._encode_plus(Yt,{text_pair:Y[Ms],add_special_tokens:ce,return_token_type_ids:wt}))}else pt=M.map(Yt=>this._encode_plus(Yt,{add_special_tokens:ce,return_token_type_ids:wt}))}else{if(M==null)throw Error("text may not be null or undefined");if(Array.isArray(Y))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");pt=[this._encode_plus(M,{text_pair:Y,add_special_tokens:ce,return_token_type_ids:wt})]}if(Ye===null?me==="max_length"?Ye=this.model_max_length:Ye=(0,Z.max)(pt.map(Yt=>Yt.input_ids.length))[0]:Fe||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."),Ye=Math.min(Ye,this.model_max_length??1/0),me||Fe)for(let Yt=0;YtYe?Fe&&Mr(pt[Yt],Ye):me&&Ns(pt[Yt],Ye,Ms=>Ms==="input_ids"?this.pad_token_id:0,this.padding_side));const rs={};if(gt){if(!(me&&Fe)&&pt.some(Ms=>{for(const Gs of Object.keys(Ms))if(Ms[Gs].length!==pt[0][Gs]?.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 Yt=[pt.length,pt[0].input_ids.length];for(const Ms of Object.keys(pt[0]))rs[Ms]=new j.Tensor("int64",BigInt64Array.from(pt.flatMap(Gs=>Gs[Ms]).map(BigInt)),Yt)}else{for(const Yt of Object.keys(pt[0]))rs[Yt]=pt.map(Ms=>Ms[Yt]);if(!yt)for(const Yt of Object.keys(rs))rs[Yt]=rs[Yt][0]}return rs}_encode_text(M){return M===null?null:(this.added_tokens_regex?M.split(this.added_tokens_regex).filter(me=>me):[M]).map((me,Fe)=>{if(this.added_tokens.find(gt=>gt.content===me)!==void 0)return me;{if(this.remove_space===!0&&(me=me.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(me=U(me)),this.normalizer!==null&&(me=this.normalizer(me)),me.length===0)return[];const gt=this.pre_tokenizer!==null?this.pre_tokenizer(me,{section_index:Fe}):[me];return this.model(gt)}}).flat()}_encode_plus(M,{text_pair:Y=null,add_special_tokens:ce=!0,return_token_type_ids:me=null}={}){const{tokens:Fe,token_type_ids:Ye}=this._tokenize_helper(M,{pair:Y,add_special_tokens:ce}),gt=this.model.convert_tokens_to_ids(Fe),wt={input_ids:gt,attention_mask:new Array(gt.length).fill(1)};return(me??this.return_token_type_ids)&&Ye&&(wt.token_type_ids=Ye),wt}_tokenize_helper(M,{pair:Y=null,add_special_tokens:ce=!1}={}){const me=this._encode_text(M),Fe=this._encode_text(Y);return this.post_processor?this.post_processor(me,Fe,{add_special_tokens:ce}):{tokens:(0,$.mergeArrays)(me??[],Fe??[])}}tokenize(M,{pair:Y=null,add_special_tokens:ce=!1}={}){return this._tokenize_helper(M,{pair:Y,add_special_tokens:ce}).tokens}encode(M,{text_pair:Y=null,add_special_tokens:ce=!0,return_token_type_ids:me=null}={}){return this._encode_plus(M,{text_pair:Y,add_special_tokens:ce,return_token_type_ids:me}).input_ids}batch_decode(M,Y={}){return M instanceof j.Tensor&&(M=M.tolist()),M.map(ce=>this.decode(ce,Y))}decode(M,Y={}){if(M instanceof j.Tensor&&(M=se(M)),!Array.isArray(M)||M.length===0||!(0,$.isIntegralNumber)(M[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(M,Y)}decode_single(M,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:ce=null}){let me=this.model.convert_ids_to_tokens(M);Y&&(me=me.filter(Ye=>!this.special_tokens.includes(Ye)));let Fe=this.decoder?this.decoder(me):me.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Fe=Fe.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Fe=Fe.trim())),(ce??this.clean_up_tokenization_spaces)&&(Fe=oe(Fe)),Fe}get_chat_template({chat_template:M=null,tools:Y=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ce=this.chat_template;if(M!==null&&Object.hasOwn(ce,M))M=ce[M];else if(M===null)if(Y!==null&&"tool_use"in ce)M=ce.tool_use;else if("default"in ce)M=ce.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(ce).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:Y=null,documents:ce=null,chat_template:me=null,add_generation_prompt:Fe=!1,tokenize:Ye=!0,padding:gt=!1,truncation:wt=!1,max_length:yt=null,return_tensor:pt=!0,return_dict:rs=!1,tokenizer_kwargs:Yt={},...Ms}={}){if(me=this.get_chat_template({chat_template:me,tools:Y}),typeof me!="string")throw Error(`chat_template must be a string, but got ${typeof me}`);let Gs=this._compiled_template_cache.get(me);Gs===void 0&&(Gs=new T.Template(me),this._compiled_template_cache.set(me,Gs));const jt=Object.create(null);for(const Ks of Gr){const Js=this.getToken(Ks);Js&&(jt[Ks]=Js)}const is=Gs.render({messages:M,add_generation_prompt:Fe,tools:Y,documents:ce,...jt,...Ms});if(Ye){const Ks=this._call(is,{add_special_tokens:!1,padding:gt,truncation:wt,max_length:yt,return_tensor:pt,...Yt});return rs?Ks:Ks.input_ids}return is}}class Kr extends Lt{return_token_type_ids=!0}class Pr extends Lt{return_token_type_ids=!0}class Er extends Lt{return_token_type_ids=!0}class Hr extends Lt{return_token_type_ids=!0}class dr extends Lt{return_token_type_ids=!0}class qr extends Lt{return_token_type_ids=!0}class Cr extends Lt{return_token_type_ids=!0}class Dr extends Lt{return_token_type_ids=!0}class Lr extends Lt{return_token_type_ids=!0}class or extends Lt{}class it extends Lt{}class vt extends Lt{return_token_type_ids=!0;constructor(M,Y){super(M,Y),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ft extends Lt{return_token_type_ids=!0}class Ys extends Lt{}class Cn extends Lt{}class dn extends Lt{}class gs extends Lt{constructor(M,Y){super(M,Y),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ce=>this.languageRegex.test(ce)),this.lang_to_token=ce=>ce}_build_translation_inputs(M,Y,ce){return fr(this,M,Y,ce)}}class br extends gs{}class Ls extends Lt{}class Qr extends Lt{}const ns="▁";class cn extends Lt{padding_side="left";constructor(M,Y){super(M,Y),this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new ss({replacement:ns,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 Y=super._encode_text(ns+M.replaceAll(ns," "));return Y.length>1&&Y[0]===ns&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class zr extends Lt{}class Jn extends Lt{}class kn extends Lt{}class Sn extends Lt{}class $n extends Lt{}class Br extends Lt{}class An extends Lt{}class Zn extends Lt{}class Rr extends Lt{}function fr(Te,M,Y,ce){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 me=ce.src_lang,Fe=ce.tgt_lang;if(!Te.language_codes.includes(Fe))throw new Error(`Target language code "${Fe}" is not valid. Must be one of: {${Te.language_codes.join(", ")}}`);if(me!==void 0){if(!Te.language_codes.includes(me))throw new Error(`Source language code "${me}" is not valid. Must be one of: {${Te.language_codes.join(", ")}}`);for(const Ye of Te.post_processor.config.single)if("SpecialToken"in Ye&&Te.languageRegex.test(Ye.SpecialToken.id)){Ye.SpecialToken.id=Te.lang_to_token(me);break}}return ce.forced_bos_token_id=Te.model.convert_tokens_to_ids([Te.lang_to_token(Fe)])[0],Te._call(M,Y)}class ar extends Lt{constructor(M,Y){super(M,Y),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ce=>this.languageRegex.test(ce)),this.lang_to_token=ce=>ce}_build_translation_inputs(M,Y,ce){return fr(this,M,Y,ce)}}class pn extends Lt{constructor(M,Y){super(M,Y),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ce=>this.languageRegex.test(ce)).map(ce=>ce.slice(2,-2)),this.lang_to_token=ce=>`__${ce}__`}_build_translation_inputs(M,Y,ce){return fr(this,M,Y,ce)}}class Xr extends Lt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(M,{return_timestamps:Y=!1,return_language:ce=!1,time_precision:me=null,force_full_sequences:Fe=!0}={}){if(me===null)throw Error("Must specify time_precision");let Ye=null;const gt=Y==="word";function wt(){return{language:Ye,timestamp:[null,null],text:""}}const yt=[];let pt=wt(),rs=0;const Yt=this.timestamp_begin,Gs=Yt+1500;let jt=[],is=[],Ks=!1,Js=null;const De=new Set(this.all_special_ids);for(const Es of M){const Hs=Es.tokens,$t=gt?Es.token_timestamps:null;let sr=null,_r=Yt;if("stride"in Es){const[Mt,Gt,Is]=Es.stride;if(rs-=Gt,Js=Mt-Is,Gt&&(_r=Gt/me+Yt),Is)for(let ks=Hs.length-1;ks>=0;--ks){const js=Number(Hs[ks]);if(js>=Yt){if(sr!==null&&(js-Yt)*me=Yt&&Gt<=Gs){const Is=(Gt-Yt)*me+rs,ks=(0,Z.round)(Is,2);if(sr!==null&&Gt>=sr)Ks=!0;else if(Ks||jt.length>0&&Gt<_r)Ks=!1;else if(pt.timestamp[0]===null)pt.timestamp[0]=ks;else if(ks!==pt.timestamp[0]){pt.timestamp[1]=ks,jt.push(ds),gt&&is.push(Cs);const[js,Tt]=this.findLongestCommonSequence(jt,is),Yr=this.decode(js);pt.text=Yr,gt&&(pt.words=this.collateWordTimestamps(js,Tt,Ye)),yt.push(pt),jt=[],ds=[],is=[],Cs=[],pt=wt()}}else if(ds.push(Gt),gt){let Is=(0,Z.round)($t[Mt]+rs,2),ks;if(Mt+1<$t.length){ks=(0,Z.round)($t[Mt+1]+rs,2);const js=this.decode([Gt]);P.test(js)&&(ks=(0,Z.round)(Math.min(Is+me,ks),2))}else ks=null;Cs.push([Is,ks])}}if("stride"in Es){const[Mt,Gt,Is]=Es.stride;rs+=Mt-Is}ds.length>0?(jt.push(ds),gt&&is.push(Cs)):jt.every(Mt=>Mt.length===0)&&(pt=wt(),jt=[],ds=[],is=[],Cs=[])}if(jt.length>0){if(Fe&&Y)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Es,Hs]=this.findLongestCommonSequence(jt,is),$t=this.decode(Es);pt.text=$t,gt&&(pt.words=this.collateWordTimestamps(Es,Hs,Ye)),yt.push(pt)}let Xs=Object.create(null);const kr=yt.map(Es=>Es.text).join("");if(Y||ce){for(let Es=0;Es0;let gt=Ye?[]:null,wt=Ye?Y[0]:null;for(let yt=1;ytGt===_r[Is]&&wt[kr+Is]<=Y[yt][$t+Is]).length:ds=Hs.filter((Gt,Is)=>Gt===_r[Is]).length;const Cs=Xs/1e4,Mt=ds/Xs+Cs;ds>1&&Mt>rs&&(rs=Mt,Yt=[kr,Es,$t,sr])}const[Gs,jt,is,Ks]=Yt,Js=Math.floor((jt+Gs)/2),De=Math.floor((Ks+is)/2);Fe.push(...ce.slice(0,Js)),ce=pt.slice(De),me=ce.length,Ye&&(gt.push(...wt.slice(0,Js)),wt=Y[yt].slice(De))}return Fe.push(...ce),Ye?(gt.push(...wt),[Fe,gt]):[Fe,[]]}collateWordTimestamps(M,Y,ce){const[me,Fe,Ye]=this.combineTokensIntoWords(M,ce),gt=[];for(let wt=0;wt=me){const gt=((Ye-me)*ce).toFixed(2);Fe.push(`<|${gt}|>`),Fe.push([])}else Fe[Fe.length-1].push(Ye);return Fe=Fe.map(Ye=>typeof Ye=="string"?Ye:super.decode(Ye,Y)),Fe.join("")}splitTokensOnUnicode(M){const Y=this.decode(M,{decode_with_timestamps:!0}),ce="�",me=[],Fe=[],Ye=[];let gt=[],wt=[],yt=0;for(let pt=0;pt=this.model.tokens_to_ids.get("<|endoftext|>"),Gs=pt.startsWith(" "),jt=pt.trim(),is=wt.test(jt);if(Ms||Gs||is||Fe.length===0)Fe.push(pt),Ye.push(rs),gt.push(Yt);else{const Ks=Fe.length-1;Fe[Ks]+=pt,Ye[Ks].push(...rs),gt[Ks].push(...Yt)}}return[Fe,Ye,gt]}mergePunctuations(M,Y,ce,me,Fe){const Ye=structuredClone(M),gt=structuredClone(Y),wt=structuredClone(ce);let yt=Ye.length-2,pt=Ye.length-1;for(;yt>=0;)Ye[yt].startsWith(" ")&&me.includes(Ye[yt].trim())?(Ye[pt]=Ye[yt]+Ye[pt],gt[pt]=(0,$.mergeArrays)(gt[yt],gt[pt]),wt[pt]=(0,$.mergeArrays)(wt[yt],wt[pt]),Ye[yt]="",gt[yt]=[],wt[yt]=[]):pt=yt,--yt;for(yt=0,pt=1;ptrs),gt.filter(rs=>rs.length>0),wt.filter(rs=>rs.length>0)]}}class hn extends Lt{}class mn extends Lt{}class fn extends Lt{}class Ot extends Lt{constructor(M,Y){super(M,Y),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ce=>this.languageRegex.test(ce)),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[Y,...ce]=M.trim().split(this.languageRegex);if(ce.length===0)return super._encode_text(Y);if(ce.length===2){const[me,Fe]=ce;return this.supported_language_codes.includes(me)||console.warn(`Unsupported language code "${me}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,$.mergeArrays)([me],super._encode_text(Fe))}}}class _n extends Lt{}class In extends Lt{}class Fn extends Lt{}class On extends Lt{}class Nr extends Lt{}class Dn extends Lt{constructor(M,Y){super(M,Y),this.decoder=new Nt({})}}class gn extends Lt{}class Ln extends Lt{}class as{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:Ys,DistilBertTokenizer:or,CamembertTokenizer:it,DebertaTokenizer:dr,DebertaV2Tokenizer:qr,BertTokenizer:Kr,HerbertTokenizer:Cr,ConvBertTokenizer:Dr,RoFormerTokenizer:Lr,XLMTokenizer:vt,ElectraTokenizer:Ft,MobileBertTokenizer:Er,SqueezeBertTokenizer:Hr,AlbertTokenizer:Pr,GPT2Tokenizer:Cn,BartTokenizer:dn,MBartTokenizer:gs,MBart50Tokenizer:br,RobertaTokenizer:Ls,WhisperTokenizer:Xr,CodeGenTokenizer:hn,CLIPTokenizer:mn,SiglipTokenizer:fn,MarianTokenizer:Ot,BloomTokenizer:Qr,NllbTokenizer:ar,M2M100Tokenizer:pn,LlamaTokenizer:cn,CodeLlamaTokenizer:zr,XLMRobertaTokenizer:Jn,MPNetTokenizer:kn,FalconTokenizer:Sn,GPTNeoXTokenizer:$n,EsmTokenizer:Br,Wav2Vec2CTCTokenizer:_n,BlenderbotTokenizer:In,BlenderbotSmallTokenizer:Fn,SpeechT5Tokenizer:On,NougatTokenizer:Nr,VitsTokenizer:Dn,Qwen2Tokenizer:An,GemmaTokenizer:Zn,Grok1Tokenizer:Rr,CohereTokenizer:gn,MgpstrTokenizer:Ln,PreTrainedTokenizer:Lt};static async from_pretrained(M,{progress_callback:Y=null,config:ce=null,cache_dir:me=null,local_files_only:Fe=!1,revision:Ye="main",legacy:gt=null}={}){const[wt,yt]=await x(M,{progress_callback:Y,config:ce,cache_dir:me,local_files_only:Fe,revision:Ye,legacy:gt}),pt=yt.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let rs=this.TOKENIZER_CLASS_MAPPING[pt];return rs||(console.warn(`Unknown tokenizer class "${pt}", attempting to construct from base class.`),rs=Lt),new rs(wt,yt)}}},"./src/utils/audio.js":(ke,A,r)=>{r.r(A),r.d(A,{RawAudio:()=>ge,hamming:()=>v,hanning:()=>x,mel_filter_bank:()=>H,read_audio:()=>T,spectrogram:()=>F,window_function:()=>ae});var g=r("./src/utils/hub.js"),$=r("./src/utils/maths.js"),N=r("./src/utils/core.js"),Z=r("./src/env.js"),j=r("?7a2c"),y=r("./src/utils/tensor.js");async function T(re,Me){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const pe=await(await(0,g.getFile)(re)).arrayBuffer(),Ce=new AudioContext({sampleRate:Me});typeof Me>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const Ae=await Ce.decodeAudioData(pe);let Pe;if(Ae.numberOfChannels===2){const Je=Math.sqrt(2),je=Ae.getChannelData(0),_e=Ae.getChannelData(1);Pe=new Float32Array(je.length);for(let X=0;X2595*Math.log10(1+re/700),kaldi:re=>1127*Math.log(1+re/700),slaney:(re,Me=1e3,pe=15,Ce=27/Math.log(6.4))=>re>=Me?pe+Math.log(re/Me)*Ce:3*re/200};function K(re,Me="htk"){const pe=L[Me];if(!pe)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?pe(re):re.map(Ce=>pe(Ce))}const se={htk:re=>700*(10**(re/2595)-1),kaldi:re=>700*(Math.exp(re/1127)-1),slaney:(re,Me=1e3,pe=15,Ce=Math.log(6.4)/27)=>re>=pe?Me*Math.exp(Ce*(re-pe)):200*re/3};function oe(re,Me="htk"){const pe=se[Me];if(!pe)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?pe(re):re.map(Ce=>pe(Ce))}function V(re,Me){const pe=Float64Array.from({length:Me.length-1},(Je,je)=>Me[je+1]-Me[je]),Ce=Array.from({length:re.length},()=>new Array(Me.length));for(let Je=0;Jenew Array(re.length));for(let Je=0;Jere+Ce*Pe)}function H(re,Me,pe,Ce,Ae,Pe=null,Je="htk",je=!1){if(Pe!==null&&Pe!=="slaney")throw new Error('norm must be one of null or "slaney"');const _e=K(pe,Je),X=K(Ce,Je),de=U(_e,X,Me+2);let Ee=oe(de,Je),Oe;if(je){const ee=Ae/(re*2);Oe=K(Float64Array.from({length:re},(Ve,Re)=>Re*ee),Je),Ee=de}else Oe=U(0,Math.floor(Ae/2),re);const Xe=V(Oe,Ee);if(Pe!==null&&Pe==="slaney")for(let ee=0;eeAe)throw Error(`frame_length (${pe}) may not be larger than fft_length (${Ae})`);if(Ue!==pe)throw new Error(`Length of the window (${Ue}) must equal frame_length (${pe})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(Pe===null&&de!==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(Je){if(je!=="reflect")throw new Error(`pad_mode="${je}" not implemented yet.`);const We=Math.floor((Ae-1)/2)+1;re=I(re,We,We)}let ze=Math.floor(1+Math.floor((re.length-pe)/Ce));te!==null&&zeze?Ke&&(mt=ve):mt=at=ve);const lt=new $.FFT(Ae),ct=new Float64Array(Ae),O=new Float64Array(lt.outputBufferSize),le=new Float32Array(Ze*mt);for(let We=0;We=1;--st)ct[st]-=X*ct[st-1];ct[0]*=1-X}for(let st=0;stMath.pow(je,.85));break;default:throw new Error(`Unknown window type ${Me}.`)}if(pe&&(Je=Je.subarray(0,re)),Ce===null)return Je;if(re>Ce)throw new Error(`Length of the window (${re}) may not be larger than frame_length (${Ce})`);return Je}function ie(re,Me){let pe=44;const Ce=new ArrayBuffer(pe+re.length*4),Ae=new DataView(Ce);ye(Ae,0,"RIFF"),Ae.setUint32(4,36+re.length*4,!0),ye(Ae,8,"WAVE"),ye(Ae,12,"fmt "),Ae.setUint32(16,16,!0),Ae.setUint16(20,3,!0),Ae.setUint16(22,1,!0),Ae.setUint32(24,Me,!0),Ae.setUint32(28,Me*4,!0),Ae.setUint16(32,4,!0),Ae.setUint16(34,32,!0),ye(Ae,36,"data"),Ae.setUint32(40,re.length*4,!0);for(let Pe=0;Pe{let Pe=await Ae.arrayBuffer();j.writeFileSync(Ce,Buffer.from(Pe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await pe(Me,this.toBlob())}}},"./src/utils/constants.js":(ke,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>y,CONFIG_NAME:()=>$,FEATURE_EXTRACTOR_NAME:()=>N,GENERATION_CONFIG_NAME:()=>T,GITHUB_ISSUE_URL:()=>g,IMAGE_PROCESSOR_NAME:()=>Z,PROCESSOR_NAME:()=>j});const g="https://github.com/huggingface/transformers.js/issues/new/choose",$="config.json",N="preprocessor_config.json",Z=N,j="processor_config.json",y="chat_template.json",T="generation_config.json"},"./src/utils/core.js":(ke,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>T,calculateReflectOffset:()=>L,count:()=>V,dispatchCallback:()=>g,escapeRegExp:()=>N,isIntegralNumber:()=>j,isNullishDimension:()=>y,isTypedArray:()=>Z,len:()=>oe,mergeArrays:()=>x,pick:()=>se,pop:()=>b,product:()=>v,reverseDictionary:()=>$,saveBlob:()=>K});function g(U,H){U&&U(H)}function $(U){return Object.fromEntries(Object.entries(U).map(([H,I])=>[I,H]))}function N(U){return U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Z(U){return U?.prototype?.__proto__?.constructor?.name==="TypedArray"}function j(U){return Number.isInteger(U)||typeof U=="bigint"}function y(U){return U==null||U===-1}function T(U){const H=[];let I=U;for(;Array.isArray(I);)H.push(I.length),I=I[0];return H}function b(U,H,I=void 0){const S=U[H];if(S!==void 0)return delete U[H],S;if(I===void 0)throw Error(`Key ${H} does not exist in object.`);return I}function x(...U){return Array.prototype.concat.apply([],U)}function v(...U){return U.reduce((H,I)=>H.flatMap(S=>I.map(w=>[S,w])))}function L(U,H){return Math.abs((U+H)%(2*H)-H)}function K(U,H){const I=URL.createObjectURL(H),S=document.createElement("a");S.href=I,S.download=U,S.click(),S.remove(),URL.revokeObjectURL(I)}function se(U,H){return Object.assign({},...H.map(I=>{if(U[I]!==void 0)return{[I]:U[I]}}))}function oe(U){let H=0;for(const I of U)++H;return H}function V(U,H){let I=0;for(const S of U)S===H&&++I;return I}},"./src/utils/data-structures.js":(ke,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>$,PriorityQueue:()=>g,TokenLattice:()=>Z});class g{constructor(T=(x,v)=>x>v,b=1/0){this._heap=[],this._comparator=T,this._maxSize=b}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...T){return this.extend(T)}extend(T){for(const b of T)if(this.size0&&this._swap(0,b),this._heap.pop(),this._siftDown(),T}replace(T){const b=this.peek();return this._heap[0]=T,this._siftDown(),b}_parent(T){return(T+1>>>1)-1}_left(T){return(T<<1)+1}_right(T){return T+1<<1}_greater(T,b){return this._comparator(this._heap[T],this._heap[b])}_swap(T,b){const x=this._heap[T];this._heap[T]=this._heap[b],this._heap[b]=x}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(T){for(;T>0&&this._greater(T,this._parent(T));)this._swap(T,this._parent(T)),T=this._parent(T)}_siftDown(){let T=0;for(;this._left(T)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const v=new j(this.bosTokenId,0,0,0,0),L=new j(this.eosTokenId,1,this.len,0,0);this.nodes.push(v.clone()),this.nodes.push(L.clone()),this.beginNodes[this.len].push(L),this.endNodes[0].push(v)}insert(T,b,x,v){const L=this.nodes.length,K=new j(v,L,T,b,x);this.beginNodes[T].push(K),this.endNodes[T+b].push(K),this.nodes.push(K)}viterbi(){const T=this.len;let b=0;for(;b<=T;){if(this.beginNodes[b].length==0)return[];for(let se of this.beginNodes[b]){se.prev=null;let oe=0,V=null;for(let U of this.endNodes[b]){const H=U.backtraceScore+se.score;(V===null||H>oe)&&(V=U.clone(),oe=H)}if(V!==null)se.prev=V,se.backtraceScore=oe;else return[]}++b}const x=[],L=this.beginNodes[T][0].prev;if(L===null)return[];let K=L.clone();for(;K.prev!==null;)x.push(K.clone()),K=K.clone().prev.clone();return x.reverse(),x}piece(T){return this.chars.slice(T.pos,T.pos+T.length).join("")}tokens(){return this.viterbi().map(b=>this.piece(b))}tokenIds(){return this.viterbi().map(b=>b.tokenId)}}class j{constructor(T,b,x,v,L){this.tokenId=T,this.nodeId=b,this.pos=x,this.length=v,this.score=L,this.prev=null,this.backtraceScore=0}clone(){const T=new j(this.tokenId,this.nodeId,this.pos,this.length,this.score);return T.prev=this.prev,T.backtraceScore=this.backtraceScore,T}}},"./src/utils/devices.js":(ke,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":(ke,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>Z,DEFAULT_DEVICE_DTYPE_MAPPING:()=>j,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>y,isWebGpuFp16Supported:()=>N});var g=r("./src/env.js"),$=r("./src/utils/devices.js");const N=function(){let T;return async function(){if(T===void 0)if(!g.apis.IS_WEBGPU_AVAILABLE)T=!1;else try{T=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{T=!1}return T}}(),Z=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),j=Object.freeze({[$.DEVICE_TYPES.wasm]:Z.q8}),y=Object.freeze({[Z.fp32]:"",[Z.fp16]:"_fp16",[Z.int8]:"_int8",[Z.uint8]:"_uint8",[Z.q8]:"_quantized",[Z.q4]:"_q4",[Z.q4f16]:"_q4f16",[Z.bnb4]:"_bnb4"})},"./src/utils/generic.js":(ke,A,r)=>{r.r(A),r.d(A,{Callable:()=>g});const g=class{constructor(){let $=function(...N){return $._call(...N)};return Object.setPrototypeOf($,new.target.prototype)}_call(...$){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(ke,A,r)=>{r.r(A),r.d(A,{getFile:()=>b,getModelFile:()=>se,getModelJSON:()=>oe});var g=r("?7a2c"),$=r("?a42a"),N=r("./src/env.js"),Z=r("./src/utils/core.js");const j={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(I){if(this.filePath=I,this.headers=new Headers,this.exists=g.existsSync(I),this.exists){this.status=200,this.statusText="OK";let S=g.statSync(I);this.headers.set("content-length",S.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(P){w.arrayBuffer().then(F=>{P.enqueue(new Uint8Array(F)),P.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const I=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",j[I]??"application/octet-stream")}clone(){let I=new y(this.filePath);return I.exists=this.exists,I.status=this.status,I.statusText=this.statusText,I.headers=new Headers(this.headers),I}async arrayBuffer(){return(await g.promises.readFile(this.filePath)).buffer}async blob(){const I=await g.promises.readFile(this.filePath);return new Blob([I],{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 T(H,I=null,S=null){let w;try{w=new URL(H)}catch{return!1}return!(I&&!I.includes(w.protocol)||S&&!S.includes(w.hostname))}async function b(H){if(N.env.useFS&&!T(H,["http:","https:","blob:"]))return new y(H);if(typeof process<"u"&&process?.release?.name==="node"){const I=!!bh?.TESTING_REMOTELY,S=N.env.version,w=new Headers;if(w.set("User-Agent",`transformers.js/${S}; is_ci/${I};`),T(H,["http:","https:"],["huggingface.co","hf.co"])){const F=bh?.HF_TOKEN??bh?.HF_ACCESS_TOKEN;F&&w.set("Authorization",`Bearer ${F}`)}return fetch(H,{headers:w})}else return fetch(H)}const x={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,I,S){if(!S)return null;const w=x[H]??`Error (${H}) occurred while trying to load file`;throw Error(`${w}: "${I}".`)}class L{constructor(I){this.path=I}async match(I){let S=$.join(this.path,I),w=new y(S);if(w.exists)return w}async put(I,S){const w=Buffer.from(await S.arrayBuffer());let P=$.join(this.path,I);try{await g.promises.mkdir($.dirname(P),{recursive:!0}),await g.promises.writeFile(P,w)}catch(F){console.warn("An error occurred while writing the file to cache:",F)}}}async function K(H,...I){for(let S of I)try{let w=await H.match(S);if(w)return w}catch{continue}}async function se(H,I,S=!0,w={}){if(!N.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(!N.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,Z.dispatchCallback)(w.progress_callback,{status:"initiate",name:H,file:I});let P;if(!P&&N.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{P=await caches.open("transformers-cache")}catch(Je){console.warn("An error occurred while opening the browser cache:",Je)}}if(!P&&N.env.useFSCache&&(P=new L(w.cache_dir??N.env.cacheDir)),!P&&N.env.useCustomCache){if(!N.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!N.env.customCache.match||!N.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");P=N.env.customCache}const F=w.revision??"main";let ae=U(H,I),ie=U(N.env.localModelPath,ae),ye=U(N.env.remoteHost,N.env.remotePathTemplate.replaceAll("{model}",H).replaceAll("{revision}",encodeURIComponent(F)),I),ge=F==="main"?ae:U(H,F,I),re,Me=P instanceof L?ge:ye,pe=!1,Ce;P&&(Ce=await K(P,ie,Me));const Ae=Ce!==void 0;if(Ce===void 0){if(N.env.allowLocalModels)if(T(ae,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!N.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{Ce=await b(ie),re=ie}catch(je){console.warn(`Unable to load from local path "${ie}": "${je}"`)}if(Ce===void 0||Ce.status===404){if(w.local_files_only||!N.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ie}".`);return null}if(Ce=await b(ye),Ce.status!==200)return v(Ce.status,ye,S);re=Me}pe=P&&typeof Response<"u"&&Ce instanceof Response&&Ce.status===200}(0,Z.dispatchCallback)(w.progress_callback,{status:"download",name:H,file:I});let Pe;return w.progress_callback?Ae&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Pe=new Uint8Array(await Ce.arrayBuffer()),(0,Z.dispatchCallback)(w.progress_callback,{status:"progress",name:H,file:I,progress:100,loaded:Pe.length,total:Pe.length})):Pe=await V(Ce,Je=>{(0,Z.dispatchCallback)(w.progress_callback,{status:"progress",name:H,file:I,...Je})}):Pe=new Uint8Array(await Ce.arrayBuffer()),pe&&re&&await P.match(re)===void 0&&await P.put(re,new Response(Pe,{headers:Ce.headers})).catch(Je=>{console.warn(`Unable to add response to browser cache: ${Je}.`)}),(0,Z.dispatchCallback)(w.progress_callback,{status:"done",name:H,file:I}),Pe}async function oe(H,I,S=!0,w={}){let P=await se(H,I,S,w);if(P===null)return{};let ae=new TextDecoder("utf-8").decode(P);return JSON.parse(ae)}async function V(H,I){const S=H.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt(S??"0"),P=new Uint8Array(w),F=0;const ae=H.body.getReader();async function ie(){const{done:ye,value:ge}=await ae.read();if(ye)return;let re=F+ge.length;if(re>w){w=re;let pe=new Uint8Array(w);pe.set(P),P=pe}P.set(ge,F),F=re;const Me=F/w*100;return I({progress:Me,loaded:F,total:w}),ie()}return await ie(),P}function U(...H){return H=H.map((I,S)=>(S&&(I=I.replace(new RegExp("^/"),"")),S!==H.length-1&&(I=I.replace(new RegExp("/$"),"")),I)),H.join("/")}},"./src/utils/image.js":(ke,A,r)=>{r.r(A),r.d(A,{RawImage:()=>K,load_image:()=>se});var g=r("./src/utils/core.js"),$=r("./src/utils/hub.js"),N=r("./src/env.js"),Z=r("./src/utils/tensor.js"),j=r("?2b25");let y,T,b;const x=N.apis.IS_BROWSER_ENV||N.apis.IS_WEBWORKER_ENV;if(x)y=(oe,V)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(oe,V)},b=self.createImageBitmap,T=self.ImageData;else if(j)b=async oe=>{const U=(await oe.metadata()).channels,{data:H,info:I}=await oe.rotate().raw().toBuffer({resolveWithObject:!0}),S=new K(new Uint8ClampedArray(H),I.width,I.height,I.channels);return U!==void 0&&U!==I.channels&&S.convert(U),S};else throw new Error("Unable to load image processing library.");const v={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},L=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class K{constructor(V,U,H,I){this.data=V,this.width=U,this.height=H,this.channels=I}get size(){return[this.width,this.height]}static async read(V){if(V instanceof K)return V;if(typeof V=="string"||V instanceof URL)return await this.fromURL(V);throw new Error(`Unsupported input type: ${typeof V}`)}static fromCanvas(V){if(!x)throw new Error("fromCanvas() is only supported in browser environments.");const H=V.getContext("2d").getImageData(0,0,V.width,V.height).data;return new K(H,V.width,V.height,4)}static async fromURL(V){const U=await(0,$.getFile)(V);if(U.status!==200)throw new Error(`Unable to read image from "${V}" (${U.status} ${U.statusText})`);const H=await U.blob();return this.fromBlob(H)}static async fromBlob(V){if(x){const U=await b(V),H=y(U.width,U.height).getContext("2d");return H.drawImage(U,0,0),new this(H.getImageData(0,0,U.width,U.height).data,U.width,U.height,4)}else{const U=j(await V.arrayBuffer());return await b(U)}}static fromTensor(V,U="CHW"){if(V.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${V.dims.length} dimensions.`);if(U==="CHW")V=V.transpose(1,2,0);else if(U!=="HWC")throw new Error(`Unsupported channel format: ${U}`);if(!(V.data instanceof Uint8ClampedArray||V.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${V.type}`);switch(V.dims[2]){case 1:case 2:case 3:case 4:return new K(V.data,V.dims[1],V.dims[0],V.dims[2]);default:throw new Error(`Unsupported number of channels: ${V.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const V=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let U=0,H=0;U=0?F=H:ie=-H,I>=0?ae=I:ye=-I,P.drawImage(w,F,ae,V,U,ie,ye,V,U),new K(P.getImageData(0,0,V,U).data,V,U,4).convert(S)}else{let S=this.toSharp();if(H>=0&&I>=0)S=S.extract({left:Math.floor(H),top:Math.floor(I),width:V,height:U});else if(H<=0&&I<=0){const w=Math.floor(-I),P=Math.floor(-H);S=S.extend({top:w,left:P,right:V-this.width-P,bottom:U-this.height-w})}else{let w=[0,0],P=0;I<0?(w[0]=Math.floor(-I),w[1]=U-this.height-w[0]):P=Math.floor(I);let F=[0,0],ae=0;H<0?(F[0]=Math.floor(-H),F[1]=V-this.width-F[0]):ae=Math.floor(H),S=S.extend({top:w[0],bottom:w[1],left:F[0],right:F[1]}).extract({left:ae,top:P,width:V,height:U})}return await b(S)}}async toBlob(V="image/png",U=1){if(!x)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:V,quality:U})}toTensor(V="CHW"){let U=new Z.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(V!=="HWC")if(V==="CHW")U=U.permute(2,0,1);else throw new Error(`Unsupported channel format: ${V}`);return U}toCanvas(){if(!x)throw new Error("toCanvas() is only supported in browser environments.");const V=this.clone().rgba(),U=y(V.width,V.height),H=new T(V.data,V.width,V.height);return U.getContext("2d").putImageData(H,0,0),U}split(){const{data:V,width:U,height:H,channels:I}=this,S=V.constructor,w=V.length/I,P=Array.from({length:I},()=>new S(w));for(let F=0;Fnew K(F,U,H,1))}_update(V,U,H,I=null){return this.data=V,this.width=U,this.height=H,I!==null&&(this.channels=I),this}clone(){return new K(this.data.slice(),this.width,this.height,this.channels)}convert(V){if(this.channels===V)return this;switch(V){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(V){if(x){if(N.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const U=V.split(".").pop().toLowerCase(),H=L.get(U)??"image/png",I=await this.toBlob(H);(0,g.saveBlob)(V,I)}else{if(N.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(V);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(x)throw new Error("toSharp() is only supported in server-side environments.");return j(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const se=K.read.bind(K)},"./src/utils/maths.js":(ke,A,r)=>{r.r(A),r.d(A,{FFT:()=>se,bankers_round:()=>U,cos_sim:()=>y,dot:()=>j,dynamic_time_warping:()=>H,interpolate_data:()=>g,log_softmax:()=>Z,magnitude:()=>T,max:()=>x,medianFilter:()=>oe,min:()=>b,permute_data:()=>$,round:()=>V,softmax:()=>N});function g(I,[S,w,P],[F,ae],ie="bilinear",ye=!1){const ge=ae/P,re=F/w,Me=new I.constructor(F*ae*S),pe=w*P,Ce=F*ae;for(let Ae=0;Ae=0;--ye)F[ye]=ge,P[ye]=S[w[ye]],ge*=P[ye];const ae=w.map((ye,ge)=>F[w.indexOf(ge)]),ie=new I.constructor(I.length);for(let ye=0;ye=0;--re)ge+=Me%S[re]*ae[re],Me=Math.floor(Me/S[re]);ie[ge]=I[ye]}return[ie,P]}function N(I){const S=x(I)[0],w=I.map(ae=>Math.exp(ae-S)),P=w.reduce((ae,ie)=>ae+ie,0);return w.map(ae=>ae/P)}function Z(I){const S=x(I)[0];let w=0;for(let ae=0;aeae-S-P)}function j(I,S){let w=0;for(let P=0;PS+w*w,0))}function b(I){if(I.length===0)throw Error("Array must not be empty");let S=I[0],w=0;for(let P=1;PS&&(S=I[P],w=P);return[S,w]}function v(I){return I>0&&(I&I-1)===0}class L{constructor(S){if(this.size=S|0,this.size<=1||!v(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=S<<1,this.table=new Float64Array(this.size*2);for(let P=0;PP;P<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>F&3)<>>1);for(let F=0;F>>1]=S[F];return P}toComplexArray(S,w){const P=w||this.createComplexArray();for(let F=0;F>>1],P[F+1]=0;return P}transform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,1)}realTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._realTransform4(S,w,1)}inverseTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,-1);for(let P=0;P>=2;ie>=2;ie>>=2){ye=F/ie<<1;const Ce=ye>>>2;for(ge=0;ge>>1,ie>>>1)}else for(ge=0,re=0;ge>>1,ie>>>1,P)}const pe=this.table;for(ie>>=2;ie>=2;ie>>=2){ye=F/ie<<1;const Ae=ye>>>1,Pe=Ae>>>1,Je=Pe>>>1;for(ge=0;ge>>1;for(let Ae=2;Ae>1;++Me){const pe=(Me+1-S)**2/2,Ce=Math.sqrt(ge**2+re**2)**pe,Ae=pe*Math.atan2(re,ge),Pe=2*Me;ae[Pe]=Ce*Math.cos(Ae),ae[Pe+1]=Ce*Math.sin(Ae),ie[Pe]=ae[Pe],ie[Pe+1]=-ae[Pe+1]}this._slicedChirpBuffer=ae.subarray(w,P),this._f=new L(F>>1),this._f.transform(this._chirpBuffer,ie)}_transform(S,w,P){const F=this._buffer1,ae=this._buffer2,ie=this._outBuffer1,ye=this._outBuffer2,ge=this._chirpBuffer,re=this._slicedChirpBuffer,Me=this._a;if(P)for(let pe=0;pe>1,Pe=w[Ae];F[pe]=Pe*re[pe],F[Ce]=Pe*re[Ce]}else for(let pe=0;pe=I.length&&(ge=2*(I.length-1)-ge),P[ie++]=I[ge]}P.sort(),w[ae]=P[F]}return w}function V(I,S){const w=Math.pow(10,S);return Math.round(I*w)/w}function U(I){const S=Math.round(I);return Math.abs(I)%1===.5?S%2===0?S:S-1:S}function H(I){const S=I.length,w=I[0].length,P=[S+1,w+1],F=Array.from({length:P[0]},()=>Array(P[1]).fill(1/0));F[0][0]=0;const ae=Array.from({length:P[0]},()=>Array(P[1]).fill(-1));for(let Me=1;Me0||ye>0;)switch(ge.push(ie-1),re.push(ye-1),ae[ie][ye]){case 0:--ie,--ye;break;case 1:--ie;break;case 2:--ye;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ie}, ${ye}]. Please file a bug report.`)}return ge.reverse(),re.reverse(),[ge,re]}},"./src/utils/tensor.js":(ke,A,r)=>{r.r(A),r.d(A,{Tensor:()=>j,cat:()=>w,full:()=>re,full_like:()=>Me,interpolate:()=>b,interpolate_4d:()=>x,layer_norm:()=>U,matmul:()=>v,mean:()=>ie,mean_pooling:()=>V,ones:()=>pe,ones_like:()=>Ce,permute:()=>T,quantize_embeddings:()=>je,rand:()=>Je,rfft:()=>L,slice:()=>oe,stack:()=>P,std_mean:()=>ae,topk:()=>K,zeros:()=>Ae,zeros_like:()=>Pe});var g=r("./src/utils/maths.js"),$=r("./src/backends/onnx.js"),N=r("./src/ops/registry.js");const Z=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 j{get dims(){return this.ort_tensor.dims}set dims(X){this.ort_tensor.dims=X}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(...X){return(0,$.isONNXTensor)(X[0])?this.ort_tensor=X[0]:this.ort_tensor=new $.Tensor(X[0],X[1],X[2]),new Proxy(this,{get:(de,Ee)=>{if(typeof Ee=="string"){let Oe=Number(Ee);if(Number.isInteger(Oe))return de._getitem(Oe)}return de[Ee]},set:(de,Ee,Oe)=>de[Ee]=Oe})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[X,...de]=this.dims;if(de.length>0){const Ee=de.reduce((Oe,Xe)=>Oe*Xe);for(let Oe=0;Oe0){const Oe=Ee.reduce((Xe,ee)=>Xe*ee);return this._subarray(X,Oe,Ee)}else return new j(this.type,[this.data[X]],Ee)}indexOf(X){const de=this.data;for(let Ee=0;EeNe)throw new Error(`Invalid slice: ${ve}`);const Ue=[Math.max(Ke,0),Math.min(Ne,this.dims[te])];Ee.push(Ue),de.push(Ue[1]-Ue[0])}else throw new Error(`Invalid slice: ${ve}`)}const Oe=Ee.map(([te,ve])=>ve-te),Xe=Oe.reduce((te,ve)=>te*ve),ee=this.data,Ve=new ee.constructor(Xe),Re=this.stride();for(let te=0;te=0;--Ke){const Ue=Oe[Ke];ve+=(Ne%Ue+Ee[Ke][0])*Re[Ke],Ne=Math.floor(Ne/Ue)}Ve[te]=ee[ve]}return new j(this.type,Ve,de)}permute(...X){return T(this,X)}transpose(...X){return this.permute(...X)}sum(X=null,de=!1){return this.norm(1,X,de)}norm(X="fro",de=null,Ee=!1){if(X==="fro")X=2;else if(typeof X=="string")throw Error(`Unsupported norm: ${X}`);const Oe=this.data,Xe=(te,ve)=>te+ve**X;if(de===null){const te=Oe.reduce(Xe,0)**(1/X);return new j(this.type,[te],[])}const[ee,Ve,Re]=F(Xe,this,de,Ee);if(X!==1)for(let te=0;te=0;--Re){const Ke=this.dims[Re];if(Re!==de){const Ne=te%Ke;Ve+=Ne*ve,ve*=this.dims[Re]}te=Math.floor(te/Ke)}Oe[ee]/=Xe[Ve]}return this}normalize(X=2,de=1){return this.clone().normalize_(X,de)}stride(){return ye(this.dims)}squeeze(X=null){return new j(this.type,this.data,H(this.dims,X))}squeeze_(X=null){return this.dims=H(this.dims,X),this}unsqueeze(X=null){return new j(this.type,this.data,I(this.dims,X))}unsqueeze_(X=null){return this.dims=I(this.dims,X),this}flatten_(X=0,de=-1){de=(de+this.dims.length)%this.dims.length;let Ee=this.dims.slice(0,X),Oe=this.dims.slice(X,de+1),Xe=this.dims.slice(de+1);return this.dims=[...Ee,Oe.reduce((ee,Ve)=>ee*Ve,1),...Xe],this}flatten(X=0,de=-1){return this.clone().flatten_(X,de)}view(...X){let de=-1;for(let Oe=0;OeVe!==de?Xe*ee:Xe,1);X[de]=Ee.length/Oe}return new j(this.type,Ee,X)}neg_(){const X=this.data;for(let de=0;deX?1:0;return new j("bool",de,this.dims)}lt(X){const de=new Uint8Array(this.data.length),Ee=this.data;for(let Oe=0;OeMath.min(ee,Ve),this,X,de,1/0);return new j(Ee,Oe,Xe)}max(X=null,de=!1){if(X===null){const ee=(0,g.max)(this.data)[0];return new j(this.type,[ee],[])}const[Ee,Oe,Xe]=F((ee,Ve)=>Math.max(ee,Ve),this,X,de,-1/0);return new j(Ee,Oe,Xe)}argmin(X=null,de=!1){if(X!==null)throw new Error("`dim !== null` not yet implemented.");const Ee=(0,g.min)(this.data)[1];return new j("int64",[BigInt(Ee)],[])}argmax(X=null,de=!1){if(X!==null)throw new Error("`dim !== null` not yet implemented.");const Ee=(0,g.max)(this.data)[1];return new j("int64",[BigInt(Ee)],[])}to(X){if(this.type===X)return this;if(!Z.hasOwnProperty(X))throw new Error(`Unsupported type: ${X}`);let de;const Ee=["int64","uint64"].includes(this.type),Oe=["int64","uint64"].includes(X);return Ee&&!Oe?de=Number:!Ee&&Oe&&(de=BigInt),new j(X,Z[X].from(this.data,de),this.dims)}}function y(_e,X){const de=_e.length,Ee=X.reduce((Xe,ee)=>Xe*ee);if(de!==Ee)throw Error(`cannot reshape array of size ${de} into shape (${X})`);let Oe=_e;for(let Xe=X.length-1;Xe>=0;Xe--)Oe=Oe.reduce((ee,Ve)=>{let Re=ee[ee.length-1];return Re.lengthnew j("int64",_e,[_e.length]);async function oe(_e,X,de,Ee,Oe){return await(await N.TensorOpRegistry.slice)({x:_e,s:se(X),e:se(de),a:se(Ee),t:se(Oe??new Array(Ee.length).fill(1))})}function V(_e,X){const de=_e.data,Ee=X.data,Oe=[_e.dims[0],_e.dims[2]],Xe=new de.constructor(Oe[0]*Oe[1]),[ee,Ve,Re]=_e.dims;let te=0;for(let ve=0;vede!==1):typeof X=="number"?_e[X]===1&&_e.splice(X,1):Array.isArray(X)&&(_e=_e.filter((de,Ee)=>de!==1||!X.includes(Ee))),_e}function I(_e,X){return X=S(X,_e.length+1),_e=_e.slice(),_e.splice(X,0,1),_e}function S(_e,X,de=null,Ee=!0){if(Ee&&(_e<-X||_e>=X))throw new Error(`IndexError: index ${_e} is out of bounds for dimension${de===null?"":" "+de} with size ${X}`);return _e<0&&(_e=(_e%X+X)%X),_e}function w(_e,X=0){X=S(X,_e[0].dims.length);const de=_e[0].dims.slice();de[X]=_e.reduce((ee,Ve)=>ee+Ve.dims[X],0);const Ee=de.reduce((ee,Ve)=>ee*Ve,1),Oe=new _e[0].data.constructor(Ee),Xe=_e[0].type;if(X===0){let ee=0;for(const Ve of _e){const Re=Ve.data;Oe.set(Re,ee),ee+=Re.length}}else{let ee=0;for(let Ve=0;Ve<_e.length;++Ve){const{data:Re,dims:te}=_e[Ve];for(let ve=0;ve=0;--Ne){const Ze=te[Ne];let at=Ue%Ze;Ne===X&&(at+=ee),Ke+=at*ze,ze*=de[Ne],Ue=Math.floor(Ue/Ze)}Oe[Ke]=Re[ve]}ee+=te[X]}}return new j(Xe,Oe,de)}function P(_e,X=0){return w(_e.map(de=>de.unsqueeze(X)),X)}function F(_e,X,de=null,Ee=!1,Oe=null){const Xe=X.data,ee=X.dims;de=S(de,ee.length);const Ve=ee.slice();Ve[de]=1;const Re=new Xe.constructor(Xe.length/ee[de]);Oe!==null&&Re.fill(Oe);for(let te=0;te=0;--Ke){const ze=ee[Ke];if(Ke!==de){const Ze=Ne%ze;ve+=Ze*Ue,Ue*=Ve[Ke]}Ne=Math.floor(Ne/ze)}Re[ve]=_e(Re[ve],Xe[te],te,ve)}return Ee||Ve.splice(de,1),[X.type,Re,Ve]}function ae(_e,X=null,de=1,Ee=!1){const Oe=_e.data,Xe=_e.dims;if(X===null){const Ue=Oe.reduce((mt,lt)=>mt+lt,0)/Oe.length,ze=Math.sqrt(Oe.reduce((mt,lt)=>mt+(lt-Ue)**2,0)/(Oe.length-de)),Ze=new j(_e.type,[Ue],[]);return[new j(_e.type,[ze],[]),Ze]}X=S(X,Xe.length);const ee=ie(_e,X,Ee),Ve=ee.data,[Re,te,ve]=F((Ne,Ue,ze,Ze)=>Ne+(Ue-Ve[Ze])**2,_e,X,Ee);for(let Ne=0;Nete+ve,0);return new j(_e.type,[Re/Oe.length],[])}X=S(X,Ee.length);const[Xe,ee,Ve]=F((Re,te)=>Re+te,_e,X,de);if(Ee[X]!==1)for(let Re=0;Re=0;--de)X[de]=Ee,Ee*=_e[de];return X}function ge(_e,X,de,Ee){const Oe=_e.reduce((Xe,ee)=>Xe*ee,1);return new j(de,new Ee(Oe).fill(X),_e)}function re(_e,X){let de,Ee;if(typeof X=="number")de="float32",Ee=Float32Array;else if(typeof X=="bigint")de="int64",Ee=BigInt64Array;else if(typeof X=="boolean")de="bool",Ee=Uint8Array;else throw new Error(`Unsupported data type: ${typeof X}`);return ge(_e,X,de,Ee)}function Me(_e,X){return re(_e.dims,X)}function pe(_e){return ge(_e,1n,"int64",BigInt64Array)}function Ce(_e){return pe(_e.dims)}function Ae(_e){return ge(_e,0n,"int64",BigInt64Array)}function Pe(_e){return Ae(_e.dims)}function Je(_e){const X=_e.reduce((de,Ee)=>de*Ee,1);return new j("float32",Float32Array.from({length:X},()=>Math.random()),_e)}function je(_e,X){if(_e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(_e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(X))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=X==="binary",Ee=de?"int8":"uint8",Oe=de?Int8Array:Uint8Array,Xe=_e.data,ee=new Oe(Xe.length/8);for(let Ve=0;Ve0?1:0,te=Math.floor(Ve/8),ve=Ve%8;ee[te]|=Re<<7-ve,de&&ve===0&&(ee[te]-=128)}return new j(Ee,ee,[_e.dims[0],_e.dims[1]/8])}}},af={};function cs(ke){var A=af[ke];if(A!==void 0)return A.exports;var r=af[ke]={exports:{}};return pf[ke](r,r.exports,cs),r.exports}cs.m=pf;(()=>{var ke=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;cs.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 $=Object.create(null);cs.r($);var N={};A=A||[null,ke({}),ke([]),ke(ke)];for(var Z=g&2&&r;typeof Z=="object"&&!~A.indexOf(Z);Z=ke(Z))Object.getOwnPropertyNames(Z).forEach(j=>N[j]=()=>r[j]);return N.default=()=>r,cs.d($,N),$}})();cs.d=(ke,A)=>{for(var r in A)cs.o(A,r)&&!cs.o(ke,r)&&Object.defineProperty(ke,r,{enumerable:!0,get:A[r]})};cs.o=(ke,A)=>Object.prototype.hasOwnProperty.call(ke,A);cs.r=ke=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(ke,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(ke,"__esModule",{value:!0})};(()=>{var ke;if(typeof import.meta.url=="string"&&(ke=import.meta.url),!ke)throw new Error("Automatic publicPath is not supported in this browser");ke=ke.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),cs.p=ke})();cs.b=new URL("./",import.meta.url);var d={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/cs.r(d),cs.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:()=>$.AutoConfig,AutoFeatureExtractor:()=>x.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:()=>V.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:()=>U.BaseStreamer,BeitFeatureExtractor:()=>L.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:()=>L.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:()=>L.CLIPFeatureExtractor,CLIPImageProcessor:()=>L.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:()=>L.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>b.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>I.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:()=>L.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>L.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>L.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>L.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:()=>L.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>L.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>L.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>L.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>r.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>r.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>r.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>g.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>L.DonutFeatureExtractor,DonutImageProcessor:()=>L.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>L.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:()=>T.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>oe.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>I.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>I.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>L.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,GroundingDinoForObjectDetection:()=>r.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>L.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>r.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>oe.GroundingDinoProcessor,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:()=>L.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>oe.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:()=>L.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>oe.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:()=>L.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>I.LogitsProcessor,LogitsProcessorList:()=>I.LogitsProcessorList,LogitsWarper:()=>I.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:()=>L.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>L.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>L.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>H.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>oe.MgpstrProcessor,MgpstrTokenizer:()=>g.MgpstrTokenizer,MinLengthLogitsProcessor:()=>I.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>I.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:()=>L.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>L.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>L.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>L.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>L.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>L.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>L.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>L.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>L.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>L.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>b.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>oe.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:()=>I.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>I.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>L.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:()=>L.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>L.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>oe.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>L.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>oe.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:()=>L.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>oe.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>g.PreTrainedTokenizer,PretrainedConfig:()=>$.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>se.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>L.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>b.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>oe.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>g.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>L.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>oe.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>L.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawAudio:()=>N.RawAudio,RawImage:()=>Z.RawImage,RepetitionPenaltyLogitsProcessor:()=>I.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:()=>L.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>oe.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>b.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>L.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>L.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>L.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:()=>oe.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,StyleTextToSpeech2Model:()=>r.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>r.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>I.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>L.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:()=>I.TemperatureLogitsWarper,Tensor:()=>j.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>U.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>g.TokenizerModel,TopKLogitsWarper:()=>I.TopKLogitsWarper,TopPLogitsWarper:()=>I.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:()=>oe.VLChatProcessor,VLMImageProcessor:()=>L.VLMImageProcessor,ViTFeatureExtractor:()=>L.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>L.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:()=>L.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>L.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:()=>oe.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:()=>oe.WhisperProcessor,WhisperTextStreamer:()=>U.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>I.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:()=>L.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>L.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:()=>j.cat,cos_sim:()=>y.cos_sim,dot:()=>y.dot,dynamic_time_warping:()=>y.dynamic_time_warping,env:()=>ke.env,full:()=>j.full,full_like:()=>j.full_like,getKeyValueShapes:()=>$.getKeyValueShapes,hamming:()=>N.hamming,hanning:()=>N.hanning,interpolate:()=>j.interpolate,interpolate_4d:()=>j.interpolate_4d,interpolate_data:()=>y.interpolate_data,is_chinese_char:()=>g.is_chinese_char,layer_norm:()=>j.layer_norm,load_image:()=>Z.load_image,log_softmax:()=>y.log_softmax,magnitude:()=>y.magnitude,matmul:()=>j.matmul,max:()=>y.max,mean:()=>j.mean,mean_pooling:()=>j.mean_pooling,medianFilter:()=>y.medianFilter,mel_filter_bank:()=>N.mel_filter_bank,min:()=>y.min,ones:()=>j.ones,ones_like:()=>j.ones_like,permute:()=>j.permute,permute_data:()=>y.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>j.quantize_embeddings,rand:()=>j.rand,read_audio:()=>N.read_audio,rfft:()=>j.rfft,round:()=>y.round,slice:()=>j.slice,softmax:()=>y.softmax,spectrogram:()=>N.spectrogram,stack:()=>j.stack,std_mean:()=>j.std_mean,topk:()=>j.topk,window_function:()=>N.window_function,zeros:()=>j.zeros,zeros_like:()=>j.zeros_like});var ke=cs("./src/env.js"),A=cs("./src/pipelines.js"),r=cs("./src/models.js"),g=cs("./src/tokenizers.js"),$=cs("./src/configs.js"),N=cs("./src/utils/audio.js"),Z=cs("./src/utils/image.js"),j=cs("./src/utils/tensor.js"),y=cs("./src/utils/maths.js"),T=cs("./src/base/feature_extraction_utils.js"),b=cs("./src/models/feature_extractors.js"),x=cs("./src/models/auto/feature_extraction_auto.js"),v=cs("./src/base/image_processors_utils.js"),L=cs("./src/models/image_processors.js"),K=cs("./src/models/auto/image_processing_auto.js"),se=cs("./src/base/processing_utils.js"),oe=cs("./src/models/processors.js"),V=cs("./src/models/auto/processing_auto.js"),U=cs("./src/generation/streamers.js"),H=cs("./src/generation/stopping_criteria.js"),I=cs("./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 lf=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;var U_=d.AutoProcessor,W_=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.Dinov2WithRegistersForImageClassification;d.Dinov2WithRegistersModel;d.Dinov2WithRegistersPreTrainedModel;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.GroundingDinoForObjectDetection;d.GroundingDinoImageProcessor;d.GroundingDinoPreTrainedModel;d.GroundingDinoProcessor;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.ModernBertForMaskedLM;d.ModernBertForSequenceClassification;d.ModernBertForTokenClassification;d.ModernBertModel;d.ModernBertPreTrainedModel;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.RawAudio;var G_=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.StyleTextToSpeech2Model;d.StyleTextToSpeech2PreTrainedModel;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;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;var K_=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;var H_=d.layer_norm;d.load_image;d.log_softmax;d.magnitude;d.matmul;d.max;d.mean;var q_=d.mean_pooling;d.medianFilter;d.mel_filter_bank;d.min;d.ones;d.ones_like;d.permute;d.permute_data;d.pipeline;d.quantize_embeddings;d.rand;d.read_audio;d.rfft;d.round;d.slice;var Q_=d.softmax;d.spectrogram;d.stack;d.std_mean;d.topk;d.window_function;d.zeros;d.zeros_like;const zp=document.getElementById("status"),uf=document.getElementById("container"),lc=document.getElementById("video"),Ph=document.getElementById("labels"),Lp=document.getElementById("template"),Fp=document.getElementById("overlay");zp.textContent="Loading model (300MB)...";async function X_(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}await X_();let ff,_f,gf,wf;try{const ke="nomic-ai/nomic-embed-text-v1.5";ff=await W_.from_pretrained(ke),_f=await lf.from_pretrained(ke,{device:"webgpu",dtype:"q4"});const A="nomic-ai/nomic-embed-vision-v1.5";gf=await U_.from_pretrained(A),wf=await lf.from_pretrained(A,{device:"webgpu",dtype:"fp32"})}catch(ke){throw zp.textContent=ke.message,alert(ke.message),ke}Ph.disabled=!1;Lp.disabled=!1;zp.textContent="Ready";const Y_=Math.exp(4.6052),Ai=224,Eh=document.createElement("canvas");Eh.width=Eh.height=Ai;const df=Eh.getContext("2d",{willReadFrequently:!0});let vh=!1,xh,En,Th,cf,Op;function yf(){vh||(vh=!0,async function(){if(Th!==Ph.value||cf!==Lp.value)if(En=null,Th=Ph.value,cf=Lp.value,Op=Th.split(/\s*,\s*/).filter(ke=>ke),Op.length>0){const ke=Op.map(g=>Lp.value.replaceAll("{}",g)),A=ff(ke,{padding:!0,truncation:!0}),{last_hidden_state:r}=await _f(A);En=q_(r,A.attention_mask),En=H_(En,[En.dims[1]]),En=En.normalize(2,-1).tolist()}else Fp.innerHTML="";if(En){df.drawImage(lc,0,0,Ai,Ai);const ke=df.getImageData(0,0,Ai,Ai).data,A=new G_(ke,Ai,Ai,4),r=await gf(A),{last_hidden_state:g}=await wf(r),$=g.mean(1).normalize(2,-1).tolist()[0],N=En.map(j=>K_(j,$)*Y_),Z=Q_(N).map((j,y)=>[j,y]).sort((j,y)=>y[0]-j[0]);Fp.innerHTML="";for(const[j,y]of Z)Fp.appendChild(document.createTextNode(`${Op[y]}: ${j.toFixed(2)}`)),Fp.appendChild(document.createElement("br"))}if(xh!==void 0){const ke=1e3/(performance.now()-xh);zp.textContent=`FPS: ${ke.toFixed(2)}`}xh=performance.now(),vh=!1}()),window.requestAnimationFrame(yf)}navigator.mediaDevices.getUserMedia({video:!0}).then(ke=>{lc.srcObject=ke,lc.play();const A=ke.getVideoTracks()[0],{width:r,height:g}=A.getSettings();lc.width=r,lc.height=g;const $=r/g,[N,Z]=$>720/405?[720,720/$]:[405*$,405];uf.style.width=`${N}px`,uf.style.height=`${Z}px`,window.requestAnimationFrame(yf)}).catch(ke=>{alert(ke)});