var sp={},em={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Me,v,s)=>{Me.exports=s.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Me,v,s)=>{s.r(v),s.d(v,{Environment:()=>st,Interpreter:()=>lt,Template:()=>gt,parse:()=>Se,tokenize:()=>x});var _=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"}),A=Object.freeze({set:_.Set,for:_.For,in:_.In,is:_.Is,if:_.If,else:_.Else,endif:_.EndIf,elif:_.ElseIf,endfor:_.EndFor,and:_.And,or:_.Or,not:_.Not,"not in":_.NotIn,macro:_.Macro,endmacro:_.EndMacro,true:_.BooleanLiteral,false:_.BooleanLiteral,none:_.NullLiteral,True:_.BooleanLiteral,False:_.BooleanLiteral,None:_.NullLiteral}),j=class{constructor(I,se){this.value=I,this.type=se}};function ee(I){return/\w/.test(I)}function U(I){return/[0-9]/.test(I)}var b=[["{%",_.OpenStatement],["%}",_.CloseStatement],["{{",_.OpenExpression],["}}",_.CloseExpression],["(",_.OpenParen],[")",_.CloseParen],["{",_.OpenCurlyBracket],["}",_.CloseCurlyBracket],["[",_.OpenSquareBracket],["]",_.CloseSquareBracket],[",",_.Comma],[".",_.Dot],[":",_.Colon],["|",_.Pipe],["<=",_.ComparisonBinaryOperator],[">=",_.ComparisonBinaryOperator],["==",_.ComparisonBinaryOperator],["!=",_.ComparisonBinaryOperator],["<",_.ComparisonBinaryOperator],[">",_.ComparisonBinaryOperator],["+",_.AdditiveBinaryOperator],["-",_.AdditiveBinaryOperator],["*",_.MultiplicativeBinaryOperator],["/",_.MultiplicativeBinaryOperator],["%",_.MultiplicativeBinaryOperator],["=",_.Equals]],T=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(I,se={}){return I.endsWith(` `)&&(I=I.slice(0,-1)),I=I.replace(/{#.*?#}/gs,"{##}"),se.lstrip_blocks&&(I=I.replace(/^[ \t]*({[#%])/gm,"$1")),se.trim_blocks&&(I=I.replace(/([#%]})\n/g,"$1")),I.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function x(I,se={}){const X=[],he=M(I,se);let Ae=0;const Ge=Je=>{let nt="";for(;Je(he[Ae]);){if(he[Ae]==="\\"){if(++Ae,Ae>=he.length)throw new SyntaxError("Unexpected end of input");const wt=he[Ae++],pt=T.get(wt);if(pt===void 0)throw new SyntaxError(`Unexpected escaped character: ${wt}`);nt+=pt;continue}if(nt+=he[Ae++],Ae>=he.length)throw new SyntaxError("Unexpected end of input")}return nt};e:for(;Ae0){X.push(new j(wt,_.Text));continue}}Ge(wt=>/\s/.test(wt));const nt=he[Ae];if(nt==="-"||nt==="+"){const wt=X.at(-1)?.type;if(wt===_.Text||wt===void 0)throw new SyntaxError(`Unexpected character: ${nt}`);switch(wt){case _.Identifier:case _.NumericLiteral:case _.BooleanLiteral:case _.NullLiteral:case _.StringLiteral:case _.CloseParen:case _.CloseSquareBracket:break;default:{++Ae;const pt=Ge(U);X.push(new j(`${nt}${pt}`,pt.length>0?_.NumericLiteral:_.UnaryOperator));continue}}}for(const[wt,pt]of b)if(he.slice(Ae,Ae+wt.length)===wt){X.push(new j(wt,pt)),Ae+=wt.length;continue e}if(nt==="'"||nt==='"'){++Ae;const wt=Ge(pt=>pt!==nt);X.push(new j(wt,_.StringLiteral)),++Ae;continue}if(U(nt)){const wt=Ge(U);X.push(new j(wt,_.NumericLiteral));continue}if(ee(nt)){const wt=Ge(ee),pt=Object.hasOwn(A,wt)?A[wt]:_.Identifier;pt===_.In&&X.at(-1)?.type===_.Not?(X.pop(),X.push(new j("not in",_.NotIn))):X.push(new j(wt,pt));continue}throw new SyntaxError(`Unexpected character: ${nt}`)}return X}var P=class{type="Statement"},R=class extends P{constructor(I){super(),this.body=I}type="Program"},Q=class extends P{constructor(I,se,X){super(),this.test=I,this.body=se,this.alternate=X}type="If"},ne=class extends P{constructor(I,se,X,he){super(),this.loopvar=I,this.iterable=se,this.body=X,this.defaultBlock=he}type="For"},de=class extends P{constructor(I,se){super(),this.assignee=I,this.value=se}type="Set"},N=class extends P{constructor(I,se,X){super(),this.name=I,this.args=se,this.body=X}type="Macro"},K=class extends P{type="Expression"},q=class extends K{constructor(I,se,X){super(),this.object=I,this.property=se,this.computed=X}type="MemberExpression"},B=class extends K{constructor(I,se){super(),this.callee=I,this.args=se}type="CallExpression"},O=class extends K{constructor(I){super(),this.value=I}type="Identifier"},w=class extends K{constructor(I){super(),this.value=I}type="Literal"},$=class extends w{type="NumericLiteral"},E=class extends w{type="StringLiteral"},Z=class extends w{type="BooleanLiteral"},J=class extends w{type="NullLiteral"},ae=class extends w{type="ArrayLiteral"},me=class extends w{type="TupleLiteral"},ge=class extends w{type="ObjectLiteral"},Ee=class extends K{constructor(I,se,X){super(),this.operator=I,this.left=se,this.right=X}type="BinaryExpression"},ve=class extends K{constructor(I,se){super(),this.operand=I,this.filter=se}type="FilterExpression"},Le=class extends K{constructor(I,se){super(),this.iterable=I,this.test=se}type="SelectExpression"},fe=class extends K{constructor(I,se,X){super(),this.operand=I,this.negate=se,this.test=X}type="TestExpression"},W=class extends K{constructor(I,se){super(),this.operator=I,this.argument=se}type="UnaryExpression"},ce=class extends K{constructor(I=void 0,se=void 0,X=void 0){super(),this.start=I,this.stop=se,this.step=X}type="SliceExpression"},_e=class extends K{constructor(I,se){super(),this.key=I,this.value=se}type="KeywordArgumentExpression"};function Se(I){const se=new R([]);let X=0;function he(ot,dt){const kt=I[X++];if(!kt||kt.type!==ot)throw new Error(`Parser Error: ${dt}. ${kt.type} !== ${ot}.`);return kt}function Ae(){switch(I[X].type){case _.Text:return nt();case _.OpenStatement:return wt();case _.OpenExpression:return pt();default:throw new SyntaxError(`Unexpected token type: ${I[X].type}`)}}function Ge(...ot){return X+ot.length<=I.length&&ot.some((dt,kt)=>dt!==I[X+kt].type)}function Je(...ot){return X+ot.length<=I.length&&ot.every((dt,kt)=>dt===I[X+kt].type)}function nt(){return new E(he(_.Text,"Expected text token").value)}function wt(){he(_.OpenStatement,"Expected opening statement token");let ot;switch(I[X].type){case _.Set:++X,ot=Qt(),he(_.CloseStatement,"Expected closing statement token");break;case _.If:++X,ot=tr(),he(_.OpenStatement,"Expected {% token"),he(_.EndIf,"Expected endif token"),he(_.CloseStatement,"Expected %} token");break;case _.Macro:++X,ot=Tr(),he(_.OpenStatement,"Expected {% token"),he(_.EndMacro,"Expected endmacro token"),he(_.CloseStatement,"Expected %} token");break;case _.For:++X,ot=Sr(),he(_.OpenStatement,"Expected {% token"),he(_.EndFor,"Expected endfor token"),he(_.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${I[X].type}`)}return ot}function pt(){he(_.OpenExpression,"Expected opening expression token");const ot=br();return he(_.CloseExpression,"Expected closing expression token"),ot}function Qt(){const ot=br();if(Je(_.Equals)){++X;const dt=Qt();return new de(ot,dt)}return ot}function tr(){const ot=br();he(_.CloseStatement,"Expected closing statement token");const dt=[],kt=[];for(;!(I[X]?.type===_.OpenStatement&&(I[X+1]?.type===_.ElseIf||I[X+1]?.type===_.Else||I[X+1]?.type===_.EndIf));)dt.push(Ae());if(I[X]?.type===_.OpenStatement&&I[X+1]?.type!==_.EndIf)if(++X,Je(_.ElseIf))he(_.ElseIf,"Expected elseif token"),kt.push(tr());else for(he(_.Else,"Expected else token"),he(_.CloseStatement,"Expected closing statement token");!(I[X]?.type===_.OpenStatement&&I[X+1]?.type===_.EndIf);)kt.push(Ae());return new Q(ot,dt,kt)}function Tr(){const ot=os();if(ot.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const dt=ks();he(_.CloseStatement,"Expected closing statement token");const kt=[];for(;Ge(_.OpenStatement,_.EndMacro);)kt.push(Ae());return new N(ot,dt,kt)}function mr(ot=!1){const dt=ot?os:br,kt=[dt()],cr=Je(_.Comma);for(;cr&&(++X,kt.push(dt()),!!Je(_.Comma)););return cr?new me(kt):kt[0]}function Sr(){const ot=mr(!0);if(!(ot instanceof O||ot instanceof me))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ot.type} instead`);he(_.In,"Expected `in` keyword following loop variable");const dt=br();he(_.CloseStatement,"Expected closing statement token");const kt=[];for(;Ge(_.OpenStatement,_.EndFor)&&Ge(_.OpenStatement,_.Else);)kt.push(Ae());const cr=[];if(Je(_.OpenStatement,_.Else))for(++X,++X,he(_.CloseStatement,"Expected closing statement token");Ge(_.OpenStatement,_.EndFor);)cr.push(Ae());return new ne(ot,dt,kt,cr)}function br(){return Hr()}function Hr(){const ot=ns();if(Je(_.If)){++X;const dt=ns();if(Je(_.Else)){++X;const kt=ns();return new Q(dt,[ot],[kt])}else return new Le(ot,dt)}return ot}function ns(){let ot=Bs();for(;Je(_.Or);){const dt=I[X];++X;const kt=Bs();ot=new Ee(dt,ot,kt)}return ot}function Bs(){let ot=Cs();for(;Je(_.And);){const dt=I[X];++X;const kt=Cs();ot=new Ee(dt,ot,kt)}return ot}function Cs(){let ot;for(;Je(_.Not);){const dt=I[X];++X;const kt=Cs();ot=new W(dt,kt)}return ot??an()}function an(){let ot=Ot();for(;Je(_.ComparisonBinaryOperator)||Je(_.In)||Je(_.NotIn);){const dt=I[X];++X;const kt=Ot();ot=new Ee(dt,ot,kt)}return ot}function Ot(){let ot=ls();for(;Je(_.AdditiveBinaryOperator);){const dt=I[X];++X;const kt=ls();ot=new Ee(dt,ot,kt)}return ot}function Rs(){const ot=Jr();return Je(_.OpenParen)?ys(ot):ot}function ys(ot){let dt=new B(ot,ks());return Je(_.OpenParen)&&(dt=ys(dt)),dt}function ks(){he(_.OpenParen,"Expected opening parenthesis for arguments list");const ot=bs();return he(_.CloseParen,"Expected closing parenthesis for arguments list"),ot}function bs(){const ot=[];for(;!Je(_.CloseParen);){let dt=br();if(Je(_.Equals)){if(++X,!(dt instanceof O))throw new SyntaxError("Expected identifier for keyword argument");const kt=br();dt=new _e(dt,kt)}ot.push(dt),Je(_.Comma)&&++X}return ot}function $s(){const ot=[];let dt=!1;for(;!Je(_.CloseSquareBracket);)Je(_.Colon)?(ot.push(void 0),++X,dt=!0):(ot.push(br()),Je(_.Colon)&&(++X,dt=!0));if(ot.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(dt){if(ot.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ce(...ot)}return ot[0]}function Jr(){let ot=os();for(;Je(_.Dot)||Je(_.OpenSquareBracket);){const dt=I[X];++X;let kt;const cr=dt.type!==_.Dot;if(cr)kt=$s(),he(_.CloseSquareBracket,"Expected closing square bracket");else if(kt=os(),kt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ot=new q(ot,kt,cr)}return ot}function ls(){let ot=Ms();for(;Je(_.MultiplicativeBinaryOperator);){const dt=I[X];++X;const kt=Ms();ot=new Ee(dt,ot,kt)}return ot}function Ms(){let ot=Ns();for(;Je(_.Is);){++X;const dt=Je(_.Not);dt&&++X;let kt=os();if(kt instanceof Z?kt=new O(kt.value.toString()):kt instanceof J&&(kt=new O("none")),!(kt instanceof O))throw new SyntaxError("Expected identifier for the test");ot=new fe(ot,dt,kt)}return ot}function Ns(){let ot=Rs();for(;Je(_.Pipe);){++X;let dt=os();if(!(dt instanceof O))throw new SyntaxError("Expected identifier for the filter");Je(_.OpenParen)&&(dt=ys(dt)),ot=new ve(ot,dt)}return ot}function os(){const ot=I[X];switch(ot.type){case _.NumericLiteral:return++X,new $(Number(ot.value));case _.StringLiteral:return++X,new E(ot.value);case _.BooleanLiteral:return++X,new Z(ot.value.toLowerCase()==="true");case _.NullLiteral:return++X,new J(null);case _.Identifier:return++X,new O(ot.value);case _.OpenParen:{++X;const dt=mr();if(I[X].type!==_.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${I[X].type} instead`);return++X,dt}case _.OpenSquareBracket:{++X;const dt=[];for(;!Je(_.CloseSquareBracket);)dt.push(br()),Je(_.Comma)&&++X;return++X,new ae(dt)}case _.OpenCurlyBracket:{++X;const dt=new Map;for(;!Je(_.CloseCurlyBracket);){const kt=br();he(_.Colon,"Expected colon between key and value in object literal");const cr=br();dt.set(kt,cr),Je(_.Comma)&&++X}return++X,new ge(dt)}default:throw new SyntaxError(`Unexpected token: ${ot.type}`)}}for(;X=0?(se=(se??=0)<0?Math.max(I.length+se,0):Math.min(se,I.length),X=(X??=I.length)<0?Math.max(I.length+X,0):Math.min(X,I.length)):(se=(se??=I.length-1)<0?Math.max(I.length+se,-1):Math.min(se,I.length-1),X=(X??=-1)<-1?Math.max(I.length+X,-1):Math.min(X,I.length-1));const Ge=[];for(let Je=se;Ae*Jese.toUpperCase())}var at=class{type="RuntimeValue";value;builtins=new Map;constructor(I=void 0){this.value=I}__bool__(){return new Ve(!!this.value)}},Ue=class extends at{type="NumericValue"},oe=class extends at{type="StringValue";builtins=new Map([["upper",new He(()=>new oe(this.value.toUpperCase()))],["lower",new He(()=>new oe(this.value.toLowerCase()))],["strip",new He(()=>new oe(this.value.trim()))],["title",new He(()=>new oe(Qe(this.value)))],["length",new Ue(this.value.length)],["rstrip",new He(()=>new oe(this.value.trimEnd()))],["lstrip",new He(()=>new oe(this.value.trimStart()))]])},Ve=class extends at{type="BooleanValue"},Ne=class extends at{type="ObjectValue";__bool__(){return new Ve(this.value.size>0)}builtins=new Map([["get",new He(([I,se])=>{if(!(I instanceof oe))throw new Error(`Object key must be a string: got ${I.type}`);return this.value.get(I.value)??se??new Xe})],["items",new He(()=>new ke(Array.from(this.value.entries()).map(([I,se])=>new ke([new oe(I),se]))))]])},ue=class extends Ne{type="KeywordArgumentsValue"},ke=class extends at{type="ArrayValue";builtins=new Map([["length",new Ue(this.value.length)]]);__bool__(){return new Ve(this.value.length>0)}},tt=class extends ke{type="TupleValue"},He=class extends at{type="FunctionValue"},Xe=class extends at{type="NullValue"},Be=class extends at{type="UndefinedValue"},st=class{constructor(I){this.parent=I}variables=new Map([["namespace",new He(I=>{if(I.length===0)return new Ne(new Map);if(I.length!==1||!(I[0]instanceof Ne))throw new Error("`namespace` expects either zero arguments or a single object argument");return I[0]})]]);tests=new Map([["boolean",I=>I.type==="BooleanValue"],["callable",I=>I instanceof He],["odd",I=>{if(I.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${I.type}`);return I.value%2!==0}],["even",I=>{if(I.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${I.type}`);return I.value%2===0}],["false",I=>I.type==="BooleanValue"&&!I.value],["true",I=>I.type==="BooleanValue"&&I.value],["none",I=>I.type==="NullValue"],["string",I=>I.type==="StringValue"],["number",I=>I.type==="NumericValue"],["integer",I=>I.type==="NumericValue"&&Number.isInteger(I.value)],["iterable",I=>I.type==="ArrayValue"||I.type==="StringValue"],["mapping",I=>I.type==="ObjectValue"],["lower",I=>{const se=I.value;return I.type==="StringValue"&&se===se.toLowerCase()}],["upper",I=>{const se=I.value;return I.type==="StringValue"&&se===se.toUpperCase()}],["none",I=>I.type==="NullValue"],["defined",I=>I.type!=="UndefinedValue"],["undefined",I=>I.type==="UndefinedValue"],["equalto",(I,se)=>I.value===se.value],["eq",(I,se)=>I.value===se.value]]);set(I,se){return this.declareVariable(I,xt(se))}declareVariable(I,se){if(this.variables.has(I))throw new SyntaxError(`Variable already declared: ${I}`);return this.variables.set(I,se),se}setVariable(I,se){return this.variables.set(I,se),se}resolve(I){if(this.variables.has(I))return this;if(this.parent)return this.parent.resolve(I);throw new Error(`Unknown variable: ${I}`)}lookupVariable(I){try{return this.resolve(I).variables.get(I)??new Be}catch{return new Be}}},lt=class{global;constructor(I){this.global=I??new st}run(I){return this.evaluate(I,this.global)}evaluateBinaryExpression(I,se){const X=this.evaluate(I.left,se);switch(I.operator.value){case"and":return X.__bool__().value?this.evaluate(I.right,se):X;case"or":return X.__bool__().value?X:this.evaluate(I.right,se)}const he=this.evaluate(I.right,se);switch(I.operator.value){case"==":return new Ve(X.value==he.value);case"!=":return new Ve(X.value!=he.value)}if(X instanceof Be||he instanceof Be)throw new Error("Cannot perform operation on undefined values");if(X instanceof Xe||he instanceof Xe)throw new Error("Cannot perform operation on null values");if(X instanceof Ue&&he instanceof Ue)switch(I.operator.value){case"+":return new Ue(X.value+he.value);case"-":return new Ue(X.value-he.value);case"*":return new Ue(X.value*he.value);case"/":return new Ue(X.value/he.value);case"%":return new Ue(X.value%he.value);case"<":return new Ve(X.value":return new Ve(X.value>he.value);case">=":return new Ve(X.value>=he.value);case"<=":return new Ve(X.value<=he.value)}else if(X instanceof ke&&he instanceof ke)switch(I.operator.value){case"+":return new ke(X.value.concat(he.value))}else if(he instanceof ke){const Ae=he.value.find(Ge=>Ge.value===X.value)!==void 0;switch(I.operator.value){case"in":return new Ve(Ae);case"not in":return new Ve(!Ae)}}if(X instanceof oe||he instanceof oe)switch(I.operator.value){case"+":return new oe(X.value.toString()+he.value.toString())}if(X instanceof oe&&he instanceof oe)switch(I.operator.value){case"in":return new Ve(he.value.includes(X.value));case"not in":return new Ve(!he.value.includes(X.value))}if(X instanceof oe&&he instanceof Ne)switch(I.operator.value){case"in":return new Ve(he.value.has(X.value));case"not in":return new Ve(!he.value.has(X.value))}throw new SyntaxError(`Unknown operator "${I.operator.value}" between ${X.type} and ${he.type}`)}evaluateArguments(I,se){const X=[],he=new Map;for(const Ae of I)if(Ae.type==="KeywordArgumentExpression"){const Ge=Ae;he.set(Ge.key.value,this.evaluate(Ge.value,se))}else{if(he.size>0)throw new Error("Positional arguments must come before keyword arguments");X.push(this.evaluate(Ae,se))}return[X,he]}evaluateFilterExpression(I,se){const X=this.evaluate(I.operand,se);if(I.filter.type==="Identifier"){const he=I.filter;if(he.value==="tojson")return new oe(ut(X));if(X instanceof ke)switch(he.value){case"list":return X;case"first":return X.value[0];case"last":return X.value[X.value.length-1];case"length":return new Ue(X.value.length);case"reverse":return new ke(X.value.reverse());case"sort":return new ke(X.value.sort((Ae,Ge)=>{if(Ae.type!==Ge.type)throw new Error(`Cannot compare different types: ${Ae.type} and ${Ge.type}`);switch(Ae.type){case"NumericValue":return Ae.value-Ge.value;case"StringValue":return Ae.value.localeCompare(Ge.value);default:throw new Error(`Cannot compare type: ${Ae.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${he.value}`)}else if(X instanceof oe)switch(he.value){case"length":return new Ue(X.value.length);case"upper":return new oe(X.value.toUpperCase());case"lower":return new oe(X.value.toLowerCase());case"title":return new oe(Qe(X.value));case"capitalize":return new oe(X.value.charAt(0).toUpperCase()+X.value.slice(1));case"trim":return new oe(X.value.trim());case"indent":return new oe(X.value.split(` `).map((Ae,Ge)=>Ge===0||Ae.length===0?Ae:" "+Ae).join(` `));case"string":return X;default:throw new Error(`Unknown StringValue filter: ${he.value}`)}else if(X instanceof Ue)switch(he.value){case"abs":return new Ue(Math.abs(X.value));default:throw new Error(`Unknown NumericValue filter: ${he.value}`)}else if(X instanceof Ne)switch(he.value){case"items":return new ke(Array.from(X.value.entries()).map(([Ae,Ge])=>new ke([new oe(Ae),Ge])));case"length":return new Ue(X.value.size);default:throw new Error(`Unknown ObjectValue filter: ${he.value}`)}throw new Error(`Cannot apply filter "${he.value}" to type: ${X.type}`)}else if(I.filter.type==="CallExpression"){const he=I.filter;if(he.callee.type!=="Identifier")throw new Error(`Unknown filter: ${he.callee.type}`);const Ae=he.callee.value;if(Ae==="tojson"){const[,Ge]=this.evaluateArguments(he.args,se),Je=Ge.get("indent")??new Xe;if(!(Je instanceof Ue||Je instanceof Xe))throw new Error("If set, indent must be a number");return new oe(ut(X,Je.value))}if(X instanceof ke){switch(Ae){case"selectattr":case"rejectattr":{const Ge=Ae==="selectattr";if(X.value.some(tr=>!(tr instanceof Ne)))throw new Error(`\`${Ae}\` can only be applied to array of objects`);if(he.args.some(tr=>tr.type!=="StringLiteral"))throw new Error(`arguments of \`${Ae}\` must be strings`);const[Je,nt,wt]=he.args.map(tr=>this.evaluate(tr,se));let pt;if(nt){const tr=se.tests.get(nt.value);if(!tr)throw new Error(`Unknown test: ${nt.value}`);pt=tr}else pt=(...tr)=>tr[0].__bool__().value;const Qt=X.value.filter(tr=>{const Tr=tr.value.get(Je.value),mr=Tr?pt(Tr,wt):!1;return Ge?mr:!mr});return new ke(Qt)}case"map":{const[,Ge]=this.evaluateArguments(he.args,se);if(Ge.has("attribute")){const Je=Ge.get("attribute");if(!(Je instanceof oe))throw new Error("attribute must be a string");const nt=Ge.get("default"),wt=X.value.map(pt=>{if(!(pt instanceof Ne))throw new Error("items in map must be an object");return pt.value.get(Je.value)??nt??new Be});return new ke(wt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Ae}`)}else if(X instanceof oe){switch(Ae){case"indent":{const[Ge,Je]=this.evaluateArguments(he.args,se),nt=Ge.at(0)??Je.get("width")??new Ue(4);if(!(nt instanceof Ue))throw new Error("width must be a number");const wt=Ge.at(1)??Je.get("first")??new Ve(!1),pt=Ge.at(2)??Je.get("blank")??new Ve(!1),Qt=X.value.split(` `),tr=" ".repeat(nt.value),Tr=Qt.map((mr,Sr)=>!wt.value&&Sr===0||!pt.value&&mr.length===0?mr:tr+mr);return new oe(Tr.join(` `))}}throw new Error(`Unknown StringValue filter: ${Ae}`)}else throw new Error(`Cannot apply filter "${Ae}" to type: ${X.type}`)}throw new Error(`Unknown filter: ${I.filter.type}`)}evaluateTestExpression(I,se){const X=this.evaluate(I.operand,se),he=se.tests.get(I.test.value);if(!he)throw new Error(`Unknown test: ${I.test.value}`);const Ae=he(X);return new Ve(I.negate?!Ae:Ae)}evaluateUnaryExpression(I,se){const X=this.evaluate(I.argument,se);switch(I.operator.value){case"not":return new Ve(!X.value);default:throw new SyntaxError(`Unknown operator: ${I.operator.value}`)}}evalProgram(I,se){return this.evaluateBlock(I.body,se)}evaluateBlock(I,se){let X="";for(const he of I){const Ae=this.evaluate(he,se);Ae.type!=="NullValue"&&Ae.type!=="UndefinedValue"&&(X+=Ae.value)}return new oe(X)}evaluateIdentifier(I,se){return se.lookupVariable(I.value)}evaluateCallExpression(I,se){const[X,he]=this.evaluateArguments(I.args,se);he.size>0&&X.push(new ue(he));const Ae=this.evaluate(I.callee,se);if(Ae.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Ae.type}`);return Ae.value(X,se)}evaluateSliceExpression(I,se,X){if(!(I instanceof ke||I instanceof oe))throw new Error("Slice object must be an array or string");const he=this.evaluate(se.start,X),Ae=this.evaluate(se.stop,X),Ge=this.evaluate(se.step,X);if(!(he instanceof Ue||he instanceof Be))throw new Error("Slice start must be numeric or undefined");if(!(Ae instanceof Ue||Ae instanceof Be))throw new Error("Slice stop must be numeric or undefined");if(!(Ge instanceof Ue||Ge instanceof Be))throw new Error("Slice step must be numeric or undefined");return I instanceof ke?new ke(We(I.value,he.value,Ae.value,Ge.value)):new oe(We(Array.from(I.value),he.value,Ae.value,Ge.value).join(""))}evaluateMemberExpression(I,se){const X=this.evaluate(I.object,se);let he;if(I.computed){if(I.property.type==="SliceExpression")return this.evaluateSliceExpression(X,I.property,se);he=this.evaluate(I.property,se)}else he=new oe(I.property.value);let Ae;if(X instanceof Ne){if(!(he instanceof oe))throw new Error(`Cannot access property with non-string: got ${he.type}`);Ae=X.value.get(he.value)??X.builtins.get(he.value)}else if(X instanceof ke||X instanceof oe)if(he instanceof Ue)Ae=X.value.at(he.value),X instanceof oe&&(Ae=new oe(X.value.at(he.value)));else if(he instanceof oe)Ae=X.builtins.get(he.value);else throw new Error(`Cannot access property with non-string/non-number: got ${he.type}`);else{if(!(he instanceof oe))throw new Error(`Cannot access property with non-string: got ${he.type}`);Ae=X.builtins.get(he.value)}return Ae instanceof at?Ae:new Be}evaluateSet(I,se){const X=this.evaluate(I.value,se);if(I.assignee.type==="Identifier"){const he=I.assignee.value;se.setVariable(he,X)}else if(I.assignee.type==="MemberExpression"){const he=I.assignee,Ae=this.evaluate(he.object,se);if(!(Ae instanceof Ne))throw new Error("Cannot assign to member of non-object");if(he.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Ae.value.set(he.property.value,X)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(I.assignee)}`);return new Xe}evaluateIf(I,se){const X=this.evaluate(I.test,se);return this.evaluateBlock(X.__bool__().value?I.body:I.alternate,se)}evaluateFor(I,se){const X=new st(se);let he,Ae;if(I.iterable.type==="SelectExpression"){const pt=I.iterable;Ae=this.evaluate(pt.iterable,X),he=pt.test}else Ae=this.evaluate(I.iterable,X);if(!(Ae instanceof ke))throw new Error(`Expected iterable type in for loop: got ${Ae.type}`);const Ge=[],Je=[];for(let pt=0;ptmr.setVariable(I.loopvar.value,tr);else if(I.loopvar.type==="TupleLiteral"){const mr=I.loopvar;if(tr.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${tr.type}`);const Sr=tr;if(mr.value.length!==Sr.value.length)throw new Error(`Too ${mr.value.length>Sr.value.length?"few":"many"} items to unpack`);Tr=br=>{for(let Hr=0;Hr0?Ge[pt-1]:new Be],["nextitem",pt{const Ae=new st(he);X=X.slice();let Ge;X.at(-1)?.type==="KeywordArgumentsValue"&&(Ge=X.pop());for(let Je=0;Jethis.evaluate(X,se)));case"TupleLiteral":return new tt(I.value.map(X=>this.evaluate(X,se)));case"ObjectLiteral":{const X=new Map;for(const[he,Ae]of I.value){const Ge=this.evaluate(he,se);if(!(Ge instanceof oe))throw new Error(`Object keys must be strings: got ${Ge.type}`);X.set(Ge.value,this.evaluate(Ae,se))}return new Ne(X)}case"Identifier":return this.evaluateIdentifier(I,se);case"CallExpression":return this.evaluateCallExpression(I,se);case"MemberExpression":return this.evaluateMemberExpression(I,se);case"UnaryExpression":return this.evaluateUnaryExpression(I,se);case"BinaryExpression":return this.evaluateBinaryExpression(I,se);case"FilterExpression":return this.evaluateFilterExpression(I,se);case"TestExpression":return this.evaluateTestExpression(I,se);default:throw new SyntaxError(`Unknown node type: ${I.type}`)}}};function xt(I){switch(typeof I){case"number":return new Ue(I);case"string":return new oe(I);case"boolean":return new Ve(I);case"undefined":return new Be;case"object":return I===null?new Xe:Array.isArray(I)?new ke(I.map(xt)):new Ne(new Map(Object.entries(I).map(([se,X])=>[se,xt(X)])));case"function":return new He((se,X)=>{const he=I(...se.map(Ae=>Ae.value))??null;return xt(he)});default:throw new Error(`Cannot convert to runtime value: ${I}`)}}function ut(I,se,X){const he=X??0;switch(I.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(I.value);case"ArrayValue":case"ObjectValue":{const Ae=se?" ".repeat(se):"",Ge=` `+Ae.repeat(he),Je=Ge+Ae;if(I.type==="ArrayValue"){const nt=I.value.map(wt=>ut(wt,se,he+1));return se?`[${Je}${nt.join(`,${Je}`)}${Ge}]`:`[${nt.join(", ")}]`}else{const nt=Array.from(I.value.entries()).map(([wt,pt])=>{const Qt=`"${wt}": ${ut(pt,se,he+1)}`;return se?`${Je}${Qt}`:Qt});return se?`{${nt.join(",")}${Ge}}`:`{${nt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${I.type}`)}}var gt=class{parsed;constructor(I){const se=x(I,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Se(se)}render(I){const se=new st;se.set("false",!1),se.set("true",!0),se.set("raise_exception",Ae=>{throw new Error(Ae)}),se.set("range",Re);for(const[Ae,Ge]of Object.entries(I))se.set(Ae,Ge);return new lt(se).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{registerBackend:()=>j,resolveBackendAndExecutionProviders:()=>U});const _=new Map,A=[],j=(b,T,M)=>{if(T&&typeof T.init=="function"&&typeof T.createInferenceSessionHandler=="function"){const x=_.get(b);if(x===void 0)_.set(b,{backend:T,priority:M});else{if(x.priority>M)return;if(x.priority===M&&x.backend!==T)throw new Error(`cannot register backend "${b}" using priority ${M}`)}if(M>=0){const P=A.indexOf(b);P!==-1&&A.splice(P,1);for(let R=0;R{const T=_.get(b);if(!T)return"backend not found.";if(T.initialized)return T.backend;if(T.aborted)return T.error;{const M=!!T.initPromise;try{return M||(T.initPromise=T.backend.init(b)),await T.initPromise,T.initialized=!0,T.backend}catch(x){return M||(T.error=`${x}`,T.aborted=!0),T.error}finally{delete T.initPromise}}},U=async b=>{const T=b.executionProviders||[],M=T.map(de=>typeof de=="string"?de:de.name),x=M.length===0?A:M;let P;const R=[],Q=new Set;for(const de of x){const N=await ee(de);typeof N=="string"?R.push({name:de,err:N}):(P||(P=N),P===N&&Q.add(de))}if(!P)throw new Error(`no available backend found. ERR: ${R.map(de=>`[${de.name}] ${de.err}`).join(", ")}`);for(const{name:de,err:N}of R)M.includes(de)&&console.warn(`removing requested execution provider "${de}" from session options because it is not available: ${N}`);const ne=T.filter(de=>Q.has(typeof de=="string"?de:de.name));return[P,new Proxy(b,{get:(de,N)=>N==="executionProviders"?ne:Reflect.get(de,N)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Me,v,s)=>{s.r(v),s.d(v,{registerBackend:()=>_.registerBackend});var _=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{env:()=>j});var _=s("./node_modules/onnxruntime-common/dist/esm/version.js");let A="warning";const j={wasm:{},webgl:{},webgpu:{},versions:{common:_.version},set logLevel(ee){if(ee!==void 0){if(typeof ee!="string"||["verbose","info","warning","error","fatal"].indexOf(ee)===-1)throw new Error(`Unsupported logging level: ${ee}`);A=ee}},get logLevel(){return A}};Object.defineProperty(j,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Me,v,s)=>{s.r(v),s.d(v,{env:()=>A});var _=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const A=_.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Me,v,s)=>{s.r(v),s.d(v,{InferenceSession:()=>j.InferenceSession,TRACE:()=>U.TRACE,TRACE_FUNC_BEGIN:()=>U.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>U.TRACE_FUNC_END,Tensor:()=>ee.Tensor,TrainingSession:()=>b.TrainingSession,env:()=>A.env,registerBackend:()=>_.registerBackend});var _=s("./node_modules/onnxruntime-common/dist/esm/backend.js"),A=s("./node_modules/onnxruntime-common/dist/esm/env.js"),j=s("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),ee=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),s("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var U=s("./node_modules/onnxruntime-common/dist/esm/trace.js");s("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),s("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var b=s("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{InferenceSession:()=>ee});var _=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),A=s("./node_modules/onnxruntime-common/dist/esm/tensor.js"),j=s("./node_modules/onnxruntime-common/dist/esm/trace.js");class ee{constructor(b){this.handler=b}async run(b,T,M){(0,j.TRACE_FUNC_BEGIN)();const x={};let P={};if(typeof b!="object"||b===null||b instanceof A.Tensor||Array.isArray(b))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let R=!0;if(typeof T=="object"){if(T===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(T instanceof A.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.");R=!1;for(const de of T){if(typeof de!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(de)===-1)throw new RangeError(`'fetches' contains invalid output name: ${de}.`);x[de]=null}if(typeof M=="object"&&M!==null)P=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let de=!1;const N=Object.getOwnPropertyNames(T);for(const K of this.outputNames)if(N.indexOf(K)!==-1){const q=T[K];(q===null||q instanceof A.Tensor)&&(de=!0,R=!1,x[K]=q)}if(de){if(typeof M=="object"&&M!==null)P=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else P=T}}else if(typeof T<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const de of this.inputNames)if(typeof b[de]>"u")throw new Error(`input '${de}' is missing in 'feeds'.`);if(R)for(const de of this.outputNames)x[de]=null;const Q=await this.handler.run(b,x,P),ne={};for(const de in Q)if(Object.hasOwnProperty.call(Q,de)){const N=Q[de];N instanceof A.Tensor?ne[de]=N:ne[de]=new A.Tensor(N.type,N.data,N.dims)}return(0,j.TRACE_FUNC_END)(),ne}async release(){return this.handler.dispose()}static async create(b,T,M,x){(0,j.TRACE_FUNC_BEGIN)();let P,R={};if(typeof b=="string"){if(P=b,typeof T=="object"&&T!==null)R=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(b instanceof Uint8Array){if(P=b,typeof T=="object"&&T!==null)R=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(b instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&b instanceof SharedArrayBuffer){const N=b;let K=0,q=b.byteLength;if(typeof T=="object"&&T!==null)R=T;else if(typeof T=="number"){if(K=T,!Number.isSafeInteger(K))throw new RangeError("'byteOffset' must be an integer.");if(K<0||K>=N.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${N.byteLength}).`);if(q=b.byteLength-K,typeof M=="number"){if(q=M,!Number.isSafeInteger(q))throw new RangeError("'byteLength' must be an integer.");if(q<=0||K+q>N.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${N.byteLength-K}].`);if(typeof x=="object"&&x!==null)R=x;else if(typeof x<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof T<"u")throw new TypeError("'options' must be an object.");P=new Uint8Array(N,K,q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[Q,ne]=await(0,_.resolveBackendAndExecutionProviders)(R),de=await Q.createInferenceSessionHandler(P,ne);return(0,j.TRACE_FUNC_END)(),new ee(de)}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":(Me,v,s)=>{s.r(v),s.d(v,{InferenceSession:()=>A});var _=s("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const A=_.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Me,v,s)=>{s.r(v)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Me,v,s)=>{s.r(v)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{tensorToDataURL:()=>_,tensorToImageData:()=>A});const _=(j,ee)=>{const U=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);U.width=j.dims[3],U.height=j.dims[2];const b=U.getContext("2d");if(b!=null){let T,M;ee?.tensorLayout!==void 0&&ee.tensorLayout==="NHWC"?(T=j.dims[2],M=j.dims[3]):(T=j.dims[3],M=j.dims[2]);const x=ee?.format!==void 0?ee.format:"RGB",P=ee?.norm;let R,Q;P===void 0||P.mean===void 0?R=[255,255,255,255]:typeof P.mean=="number"?R=[P.mean,P.mean,P.mean,P.mean]:(R=[P.mean[0],P.mean[1],P.mean[2],0],P.mean[3]!==void 0&&(R[3]=P.mean[3])),P===void 0||P.bias===void 0?Q=[0,0,0,0]:typeof P.bias=="number"?Q=[P.bias,P.bias,P.bias,P.bias]:(Q=[P.bias[0],P.bias[1],P.bias[2],0],P.bias[3]!==void 0&&(Q[3]=P.bias[3]));const ne=M*T;let de=0,N=ne,K=ne*2,q=-1;x==="RGBA"?(de=0,N=ne,K=ne*2,q=ne*3):x==="RGB"?(de=0,N=ne,K=ne*2):x==="RBG"&&(de=0,K=ne,N=ne*2);for(let B=0;B{const U=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let b;if(U!=null){let T,M,x;ee?.tensorLayout!==void 0&&ee.tensorLayout==="NHWC"?(T=j.dims[2],M=j.dims[1],x=j.dims[3]):(T=j.dims[3],M=j.dims[2],x=j.dims[1]);const P=ee!==void 0&&ee.format!==void 0?ee.format:"RGB",R=ee?.norm;let Q,ne;R===void 0||R.mean===void 0?Q=[255,255,255,255]:typeof R.mean=="number"?Q=[R.mean,R.mean,R.mean,R.mean]:(Q=[R.mean[0],R.mean[1],R.mean[2],255],R.mean[3]!==void 0&&(Q[3]=R.mean[3])),R===void 0||R.bias===void 0?ne=[0,0,0,0]:typeof R.bias=="number"?ne=[R.bias,R.bias,R.bias,R.bias]:(ne=[R.bias[0],R.bias[1],R.bias[2],0],R.bias[3]!==void 0&&(ne[3]=R.bias[3]));const de=M*T;if(ee!==void 0&&(ee.format!==void 0&&x===4&&ee.format!=="RGBA"||x===3&&ee.format!=="RGB"&&ee.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const N=4;let K=0,q=1,B=2,O=3,w=0,$=de,E=de*2,Z=-1;P==="RGBA"?(w=0,$=de,E=de*2,Z=de*3):P==="RGB"?(w=0,$=de,E=de*2):P==="RBG"&&(w=0,E=de,$=de*2),b=U.createImageData(T,M);for(let J=0;J{s.r(v)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{bufferToTensor:()=>A,tensorFromGpuBuffer:()=>U,tensorFromImage:()=>j,tensorFromMLTensor:()=>b,tensorFromPinnedBuffer:()=>T,tensorFromTexture:()=>ee});var _=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const A=(M,x)=>{if(M===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:P,width:R}=x,Q=x.norm??{mean:255,bias:0};let ne,de;typeof Q.mean=="number"?ne=[Q.mean,Q.mean,Q.mean,Q.mean]:ne=[Q.mean[0],Q.mean[1],Q.mean[2],Q.mean[3]??255],typeof Q.bias=="number"?de=[Q.bias,Q.bias,Q.bias,Q.bias]:de=[Q.bias[0],Q.bias[1],Q.bias[2],Q.bias[3]??0];const N=x.format!==void 0?x.format:"RGBA",K=x.tensorFormat!==void 0&&x.tensorFormat!==void 0?x.tensorFormat:"RGB",q=P*R,B=K==="RGBA"?new Float32Array(q*4):new Float32Array(q*3);let O=4,w=0,$=1,E=2,Z=3,J=0,ae=q,me=q*2,ge=-1;N==="RGB"&&(O=3,w=0,$=1,E=2,Z=-1),K==="RGBA"?ge=q*3:K==="RBG"?(J=0,me=q,ae=q*2):K==="BGR"&&(me=0,ae=q,J=q*2);for(let ve=0;ve{const P=typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement,R=typeof ImageData<"u"&&M instanceof ImageData,Q=typeof ImageBitmap<"u"&&M instanceof ImageBitmap,ne=typeof M=="string";let de,N=x??{};const K=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},q=B=>typeof HTMLCanvasElement<"u"&&B instanceof HTMLCanvasElement||B instanceof OffscreenCanvas?B.getContext("2d"):null;if(P){const B=K();B.width=M.width,B.height=M.height;const O=q(B);if(O!=null){let w=M.height,$=M.width;if(x!==void 0&&x.resizedHeight!==void 0&&x.resizedWidth!==void 0&&(w=x.resizedHeight,$=x.resizedWidth),x!==void 0){if(N=x,x.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");N.tensorFormat="RGBA",N.height=w,N.width=$}else N.tensorFormat="RGBA",N.height=w,N.width=$;O.drawImage(M,0,0),de=O.getImageData(0,0,$,w).data}else throw new Error("Can not access image data")}else if(R){let B,O;if(x!==void 0&&x.resizedWidth!==void 0&&x.resizedHeight!==void 0?(B=x.resizedHeight,O=x.resizedWidth):(B=M.height,O=M.width),x!==void 0&&(N=x),N.format="RGBA",N.height=B,N.width=O,x!==void 0){const w=K();w.width=O,w.height=B;const $=q(w);if($!=null)$.putImageData(M,0,0),de=$.getImageData(0,0,O,B).data;else throw new Error("Can not access image data")}else de=M.data}else if(Q){if(x===void 0)throw new Error("Please provide image config with format for Imagebitmap");const B=K();B.width=M.width,B.height=M.height;const O=q(B);if(O!=null){const w=M.height,$=M.width;return O.drawImage(M,0,0,$,w),de=O.getImageData(0,0,$,w).data,N.height=w,N.width=$,A(de,N)}else throw new Error("Can not access image data")}else{if(ne)return new Promise((B,O)=>{const w=K(),$=q(w);if(!M||!$)return O();const E=new Image;E.crossOrigin="Anonymous",E.src=M,E.onload=()=>{w.width=E.width,w.height=E.height,$.drawImage(E,0,0,w.width,w.height);const Z=$.getImageData(0,0,w.width,w.height);N.height=w.height,N.width=w.width,B(A(Z.data,N))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(de!==void 0)return A(de,N);throw new Error("Input data provided is not supported - aborted tensor creation")},ee=(M,x)=>{const{width:P,height:R,download:Q,dispose:ne}=x,de=[1,R,P,4];return new _.Tensor({location:"texture",type:"float32",texture:M,dims:de,download:Q,dispose:ne})},U=(M,x)=>{const{dataType:P,dims:R,download:Q,dispose:ne}=x;return new _.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:M,dims:R,download:Q,dispose:ne})},b=(M,x)=>{const{dataType:P,dims:R,download:Q,dispose:ne}=x;return new _.Tensor({location:"ml-tensor",type:P??"float32",mlTensor:M,dims:R,download:Q,dispose:ne})},T=(M,x,P)=>new _.Tensor({location:"cpu-pinned",type:M,data:x,dims:P??[x.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Me,v,s)=>{s.r(v)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Me,v,s)=>{s.r(v),s.d(v,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>A,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>_,checkTypedArray:()=>ee});const _=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),A=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let j=!1;const ee=()=>{if(!j){j=!0;const U=typeof BigInt64Array<"u"&&BigInt64Array.from,b=typeof BigUint64Array<"u"&&BigUint64Array.from,T=typeof Float16Array<"u"&&Float16Array.from;U&&(_.set("int64",BigInt64Array),A.set(BigInt64Array,"int64")),b&&(_.set("uint64",BigUint64Array),A.set(BigUint64Array,"uint64")),T?(_.set("float16",Float16Array),A.set(Float16Array,"float16")):_.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{Tensor:()=>U});var _=s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),A=s("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),j=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),ee=s("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class U{constructor(T,M,x){(0,j.checkTypedArray)();let P,R;if(typeof T=="object"&&"location"in T)switch(this.dataLocation=T.location,P=T.type,R=T.dims,T.location){case"cpu-pinned":{const ne=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(P);if(!ne)throw new TypeError(`unsupported type "${P}" to create tensor from pinned buffer`);if(!(T.data instanceof ne))throw new TypeError(`buffer should be of type ${ne.name}`);this.cpuData=T.data;break}case"texture":{if(P!=="float32")throw new TypeError(`unsupported type "${P}" to create tensor from texture`);this.gpuTextureData=T.texture,this.downloader=T.download,this.disposer=T.dispose;break}case"gpu-buffer":{if(P!=="float32"&&P!=="float16"&&P!=="int32"&&P!=="int64"&&P!=="uint32"&&P!=="uint8"&&P!=="bool"&&P!=="uint4"&&P!=="int4")throw new TypeError(`unsupported type "${P}" to create tensor from gpu buffer`);this.gpuBufferData=T.gpuBuffer,this.downloader=T.download,this.disposer=T.dispose;break}case"ml-tensor":{if(P!=="float32"&&P!=="float16"&&P!=="int32"&&P!=="int64"&&P!=="uint32"&&P!=="uint64"&&P!=="int8"&&P!=="uint8"&&P!=="bool")throw new TypeError(`unsupported type "${P}" 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 ne,de;if(typeof T=="string")if(P=T,de=x,T==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");ne=M}else{const N=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(T);if(N===void 0)throw new TypeError(`Unsupported tensor type: ${T}.`);if(Array.isArray(M)){if(T==="float16"&&N===Uint16Array||T==="uint4"||T==="int4")throw new TypeError(`Creating a ${T} tensor from number array is not supported. Please use ${N.name} as data.`);T==="uint64"||T==="int64"?ne=N.from(M,BigInt):ne=N.from(M)}else if(M instanceof N)ne=M;else if(M instanceof Uint8ClampedArray)if(T==="uint8")ne=Uint8Array.from(M);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${P} tensor's data must be type of ${N}`)}else if(de=M,Array.isArray(T)){if(T.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const N=typeof T[0];if(N==="string")P="string",ne=T;else if(N==="boolean")P="bool",ne=Uint8Array.from(T);else throw new TypeError(`Invalid element type of data array: ${N}.`)}else if(T instanceof Uint8ClampedArray)P="uint8",ne=Uint8Array.from(T);else{const N=j.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(T.constructor);if(N===void 0)throw new TypeError(`Unsupported type for tensor data: ${T.constructor}.`);P=N,ne=T}if(de===void 0)de=[ne.length];else if(!Array.isArray(de))throw new TypeError("A tensor's dims must be a number array");R=de,this.cpuData=ne,this.dataLocation="cpu"}const Q=(0,ee.calculateSize)(R);if(this.cpuData&&Q!==this.cpuData.length&&!((P==="uint4"||P==="int4")&&Math.ceil(Q/2)===this.cpuData.length))throw new Error(`Tensor's size(${Q}) does not match data length(${this.cpuData.length}).`);this.type=P,this.dims=R,this.size=Q}static async fromImage(T,M){return(0,A.tensorFromImage)(T,M)}static fromTexture(T,M){return(0,A.tensorFromTexture)(T,M)}static fromGpuBuffer(T,M){return(0,A.tensorFromGpuBuffer)(T,M)}static fromMLTensor(T,M){return(0,A.tensorFromMLTensor)(T,M)}static fromPinnedBuffer(T,M,x){return(0,A.tensorFromPinnedBuffer)(T,M,x)}toDataURL(T){return(0,_.tensorToDataURL)(this,T)}toImageData(T){return(0,_.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 M=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=M,T&&this.disposer&&(this.disposer(),this.disposer=void 0),M}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,ee.tensorReshape)(this,T)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{calculateSize:()=>A,tensorReshape:()=>j});var _=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const A=ee=>{let U=1;for(let b=0;b{switch(ee.location){case"cpu":return new _.Tensor(ee.type,ee.data,U);case"cpu-pinned":return new _.Tensor({location:"cpu-pinned",data:ee.data,type:ee.type,dims:U});case"texture":return new _.Tensor({location:"texture",texture:ee.texture,type:ee.type,dims:U});case"gpu-buffer":return new _.Tensor({location:"gpu-buffer",gpuBuffer:ee.gpuBuffer,type:ee.type,dims:U});case"ml-tensor":return new _.Tensor({location:"ml-tensor",mlTensor:ee.mlTensor,type:ee.type,dims:U});default:throw new Error(`tensorReshape: tensor location ${ee.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Me,v,s)=>{s.r(v),s.d(v,{Tensor:()=>A});var _=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const A=_.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Me,v,s)=>{s.r(v),s.d(v,{TRACE:()=>A,TRACE_FUNC_BEGIN:()=>ee,TRACE_FUNC_END:()=>U});var _=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const A=(b,T)=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||console.timeStamp(`${b}::ORT::${T}`)},j=(b,T)=>{const M=new Error().stack?.split(/\r\n|\r|\n/g)||[];let x=!1;for(let P=0;P{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||j("BEGIN",b)},U=b=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||j("END",b)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Me,v,s)=>{s.r(v),s.d(v,{TrainingSession:()=>ee});var _=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),A=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");const j="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class ee{constructor(b,T,M){this.handler=b,this.hasOptimizerModel=T,this.hasEvalModel=M}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(b,T){const M=b.evalModel||"",x=b.optimizerModel||"",P=T||{},[R,Q]=await(0,_.resolveBackendAndExecutionProviders)(P);if(R.createTrainingSessionHandler){const ne=await R.createTrainingSessionHandler(b.checkpointState,b.trainModel,M,x,Q);return new ee(ne,!!b.optimizerModel,!!b.evalModel)}else throw new Error(j)}typeNarrowingForRunStep(b,T,M,x,P){const R={};let Q={};if(typeof M!="object"||M===null||M instanceof A.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof x=="object"){if(x===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(x instanceof A.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.");ne=!1;for(const de of x){if(typeof de!="string")throw new TypeError("'fetches' must be a string array or an object.");if(T.indexOf(de)===-1)throw new RangeError(`'fetches' contains invalid output name: ${de}.`);R[de]=null}if(typeof P=="object"&&P!==null)Q=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else{let de=!1;const N=Object.getOwnPropertyNames(x);for(const K of T)if(N.indexOf(K)!==-1){const q=x[K];(q===null||q instanceof A.Tensor)&&(de=!0,ne=!1,R[K]=q)}if(de){if(typeof P=="object"&&P!==null)Q=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else Q=x}}else if(typeof x<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const de of b)if(typeof M[de]>"u")throw new Error(`input '${de}' is missing in 'feeds'.`);if(ne)for(const de of T)R[de]=null;return[R,Q]}convertHandlerReturnTypeToMapOfTensors(b){const T={};for(const M in b)if(Object.hasOwnProperty.call(b,M)){const x=b[M];x instanceof A.Tensor?T[M]=x:T[M]=new A.Tensor(x.type,x.data,x.dims)}return T}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(b,T,M){const[x,P]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,b,T,M),R=await this.handler.runTrainStep(b,x,P);return this.convertHandlerReturnTypeToMapOfTensors(R)}async runOptimizerStep(b){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(b||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(b,T,M){if(this.hasEvalModel){const[x,P]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,b,T,M),R=await this.handler.runEvalStep(b,x,P);return this.convertHandlerReturnTypeToMapOfTensors(R)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(b=!0){return this.handler.getParametersSize(b)}async loadParametersBuffer(b,T=!0){const M=await this.getParametersSize(T);if(b.length!==4*M)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(b,T)}async getContiguousParameters(b=!0){return this.handler.getContiguousParameters(b)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Me,v,s)=>{s.r(v),s.d(v,{TrainingSession:()=>A});var _=s("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const A=_.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Me,v,s)=>{s.r(v),s.d(v,{version:()=>_});const _="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs":(Me,v,s)=>{s.r(v),s.d(v,{InferenceSession:()=>ut,TRACE:()=>tt,TRACE_FUNC_BEGIN:()=>Xe,TRACE_FUNC_END:()=>Be,Tensor:()=>ue,default:()=>cm,env:()=>E,registerBackend:()=>Q});/*! * ONNX Runtime Web v1.21.0-dev.20241205-d27fecd3d3 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var _=Object.defineProperty,A=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyNames,ee=Object.prototype.hasOwnProperty,U=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),b=(e,t)=>()=>(e&&(t=e(e=0)),t),T=(e,t)=>{for(var r in t)_(e,r,{get:t[r],enumerable:!0})},M=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of j(t))!ee.call(e,o)&&o!==r&&_(e,o,{get:()=>t[o],enumerable:!(n=A(t,o))||n.enumerable});return e},x=e=>M(_({},"__esModule",{value:!0}),e),P,R,Q,ne,de,N=b(()=>{P=new Map,R=[],Q=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=P.get(e);if(n===void 0)P.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=R.indexOf(e);o!==-1&&R.splice(o,1);for(let i=0;i{let t=P.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},de=async e=>{let t=e.executionProviders||[],r=t.map(p=>typeof p=="string"?p:p.name),n=r.length===0?R:r,o,i=[],a=new Set;for(let p of n){let h=await ne(p);typeof h=="string"?i.push({name:p,err:h}):(o||(o=h),o===h&&a.add(p))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of i)r.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let u=t.filter(p=>a.has(typeof p=="string"?p:p.name));return[o,new Proxy(e,{get:(p,h)=>h==="executionProviders"?u:Reflect.get(p,h)})]}}),K=b(()=>{N()}),q,B=b(()=>{q="1.21.0-dev.20241205-6ed77cc374"}),O,w,$=b(()=>{B(),O="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:q},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);O=e}},get logLevel(){return O}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),E,Z=b(()=>{$(),E=w}),J,ae,me=b(()=>{J=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:"RGB",u=t?.norm,p,h;u===void 0||u.mean===void 0?p=[255,255,255,255]:typeof u.mean=="number"?p=[u.mean,u.mean,u.mean,u.mean]:(p=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(p[3]=u.mean[3])),u===void 0||u.bias===void 0?h=[0,0,0,0]:typeof u.bias=="number"?h=[u.bias,u.bias,u.bias,u.bias]:(h=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(h[3]=u.bias[3]));let k=i*o,d=0,S=k,L=k*2,z=-1;a==="RGBA"?(d=0,S=k,L=k*2,z=k*3):a==="RGB"?(d=0,S=k,L=k*2):a==="RBG"&&(d=0,L=k,S=k*2);for(let D=0;D{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t?.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let d=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let S=4,L=0,z=1,D=2,re=3,te=0,V=d,ie=d*2,pe=-1;u==="RGBA"?(te=0,V=d,ie=d*2,pe=d*3):u==="RGB"?(te=0,V=d,ie=d*2):u==="RBG"&&(te=0,ie=d,V=d*2),n=r.createImageData(o,i);for(let be=0;be{Ne(),ge=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean=="number"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),d=4,S=0,L=1,z=2,D=3,re=0,te=h,V=h*2,ie=-1;u==="RGB"&&(d=3,S=0,L=1,z=2,D=-1),p==="RGBA"?ie=h*3:p==="RBG"?(re=0,V=h,te=h*2):p==="BGR"&&(V=0,te=h,re=h*2);for(let pe=0;pe{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",a,u=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(r){let k=p();k.width=e.width,k.height=e.height;let d=h(k);if(d!=null){let S=e.height,L=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(S=t.resizedHeight,L=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=S,u.width=L}else u.tensorFormat="RGBA",u.height=S,u.width=L;d.drawImage(e,0,0),a=d.getImageData(0,0,L,S).data}else throw new Error("Can not access image data")}else if(n){let k,d;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,d=t.resizedWidth):(k=e.height,d=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=k,u.width=d,t!==void 0){let S=p();S.width=d,S.height=k;let L=h(S);if(L!=null)L.putImageData(e,0,0),a=L.getImageData(0,0,d,k).data;else throw new Error("Can not access image data")}else a=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let d=h(k);if(d!=null){let S=e.height,L=e.width;return d.drawImage(e,0,0,L,S),a=d.getImageData(0,0,L,S).data,u.height=S,u.width=L,ge(a,u)}else throw new Error("Can not access image data")}else{if(i)return new Promise((k,d)=>{let S=p(),L=h(S);if(!e||!L)return d();let z=new Image;z.crossOrigin="Anonymous",z.src=e,z.onload=()=>{S.width=z.width,S.height=z.height,L.drawImage(z,0,0,S.width,S.height);let D=L.getImageData(0,0,S.width,S.height);u.height=S.height,u.width=S.width,k(ge(D.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return ge(a,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ve=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new Ve({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},Le=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Ve({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},fe=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Ve({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:o,dispose:i})},W=(e,t,r)=>new Ve({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),_e,Se,Re,We,Qe=b(()=>{_e=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Re=!1,We=()=>{if(!Re){Re=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(_e.set("int64",BigInt64Array),Se.set(BigInt64Array,"int64")),t&&(_e.set("uint64",BigUint64Array),Se.set(BigUint64Array,"uint64")),r?(_e.set("float16",Float16Array),Se.set(Float16Array,"float16")):_e.set("float16",Uint16Array)}}}),at,Ue,oe=b(()=>{Ne(),at=e=>{let t=1;for(let r=0;r{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,Ne=b(()=>{me(),ce(),Qe(),oe(),Ve=class{constructor(e,t,r){We();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let a=_e.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,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let p=_e.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(u=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=Se.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,a=e}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");o=u,this.cpuData=a,this.dataLocation="cpu"}let i=at(o);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=i}static async fromImage(e,t){return Ee(e,t)}static fromTexture(e,t){return ve(e,t)}static fromGpuBuffer(e,t){return Le(e,t)}static fromMLTensor(e,t){return fe(e,t)}static fromPinnedBuffer(e,t,r){return W(e,t,r)}toDataURL(e){return J(this,e)}toImageData(e){return ae(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 Ue(this,e)}}}),ue,ke=b(()=>{Ne(),ue=Ve}),tt,He,Xe,Be,st=b(()=>{$(),tt=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},He=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let o=0;o{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||He("BEGIN",e)},Be=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||He("END",e)}}),lt,xt=b(()=>{N(),ke(),st(),lt=class tm{constructor(t){this.handler=t}async run(t,r,n){Xe();let o={},i={};if(typeof t!="object"||t===null||t instanceof ue||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ue)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(r);for(let d of this.outputNames)if(k.indexOf(d)!==-1){let S=r[d];(S===null||S instanceof ue)&&(h=!0,a=!1,o[d]=S)}if(h){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(a)for(let h of this.outputNames)o[h]=null;let u=await this.handler.run(t,o,i),p={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let k=u[h];k instanceof ue?p[h]=k:p[h]=new ue(k.type,k.data,k.dims)}return Be(),p}async release(){return this.handler.dispose()}static async create(t,r,n,o){Xe();let i,a={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,d=0,S=t.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(d=r,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(S=t.byteLength-d,typeof n=="number"){if(S=n,!Number.isSafeInteger(S))throw new RangeError("'byteLength' must be an integer.");if(S<=0||d+S>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-d}].`);if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(k,d,S)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,p]=await de(a),h=await u.createInferenceSessionHandler(i,p);return Be(),new tm(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ut,gt=b(()=>{xt(),ut=lt}),I=b(()=>{}),se=b(()=>{}),X=b(()=>{}),he=b(()=>{}),Ae={};T(Ae,{InferenceSession:()=>ut,TRACE:()=>tt,TRACE_FUNC_BEGIN:()=>Xe,TRACE_FUNC_END:()=>Be,Tensor:()=>ue,env:()=>E,registerBackend:()=>Q});var Ge=b(()=>{K(),Z(),gt(),ke(),I(),se(),st(),X(),he()}),Je=b(()=>{}),nt={};T(nt,{default:()=>Qt});var wt,pt,Qt,tr=b(()=>{wp(),kt(),bs(),wt="ort-wasm-proxy-worker",pt=globalThis.self?.name===wt,pt&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":ot(r.wasm).then(()=>{x1(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:o}=r;T1(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=r,o=Yc(n);postMessage({type:t,out:o});break}case"create":{let{model:n,options:o}=r;E1(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":P1(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:u}=r;k1(n,o,i,a,new Array(a.length).fill(null),u).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},S1([...i,...p]))},p=>{postMessage({type:t,err:p})});break}case"end-profiling":$1(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),Qt=pt?null:e=>new Worker(e??ns,{type:"module",name:wt})}),Tr={};T(Tr,{default:()=>br});var mr,Sr,br,Hr=b(()=>{Sr=(mr=import.meta.url,async function(e={}){function t(){return jt.buffer!=Yt.buffer&&Yr(),Yt}function r(){return jt.buffer!=Yt.buffer&&Yr(),qt}function n(){return jt.buffer!=Yt.buffer&&Yr(),Qr}function o(){return jt.buffer!=Yt.buffer&&Yr(),it}function i(){return jt.buffer!=Yt.buffer&&Yr(),Et}function a(){return jt.buffer!=Yt.buffer&&Yr(),hr}function u(){return jt.buffer!=Yt.buffer&&Yr(),vr}function p(){return jt.buffer!=Yt.buffer&&Yr(),Kr}var h,k,d=Object.assign({},e),S=new Promise((l,m)=>{h=l,k=m}),L=typeof window=="object",z=typeof importScripts=="function",D=z&&self.name=="em-pthread";d.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(d.Fb||(d.Fb=new Map)).set(l,m)},d.unmountExternalData=()=>{delete d.Fb};var re=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let te=()=>{let l=(C,F,G)=>(...ye)=>{let je=nn,Ye=F?.();ye=C(...ye);let vt=F?.();return Ye!==vt&&(C=vt,G(Ye),F=G=null),nn!=je?new Promise((Pt,Rt)=>{X1={resolve:Pt,reject:Rt}}):ye},m=C=>async(...F)=>{try{if(d.Gb)throw Error("Session already started");let G=d.Gb={hc:F[0],errors:[]},ye=await C(...F);if(d.Gb!==G)throw Error("Session mismatch");d.Hb?.flush();let je=G.errors;if(0vt),0d._OrtCreateSession,C=>d._OrtCreateSession=C),d._OrtRun=m(l(d._OrtRun,()=>d._OrtRun,C=>d._OrtRun=C)),d._OrtRunWithBinding=m(l(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,C=>d._OrtRunWithBinding=C)),d._OrtBindInput=l(d._OrtBindInput,()=>d._OrtBindInput,C=>d._OrtBindInput=C),te=void 0};d.jsepInit=(l,m)=>{if(te?.(),l==="webgpu"){[d.Hb,d.Vb,d.Zb,d.Ob,d.Yb,d.kb,d.$b,d.cc,d.Wb,d.Xb,d.ac]=m;let C=d.Hb;d.jsepRegisterBuffer=(F,G,ye,je)=>C.registerBuffer(F,G,ye,je),d.jsepGetBuffer=F=>C.getBuffer(F),d.jsepCreateDownloader=(F,G,ye)=>C.createDownloader(F,G,ye),d.jsepOnCreateSession=F=>{C.onCreateSession(F)},d.jsepOnReleaseSession=F=>{C.onReleaseSession(F)},d.jsepOnRunStart=F=>C.onRunStart(F),d.dc=(F,G)=>{C.upload(F,G)}}else if(l==="webnn"){[d.Hb,d.bc,d.Pb,d.jsepEnsureTensor,d.ec,d.jsepDownloadTensor]=m,d.jsepReleaseTensorId=d.Pb;let C=d.Hb;d.jsepOnRunStart=F=>C.onRunStart(F),d.jsepRegisterMLContext=(F,G)=>{C.registerMLContext(F,G)},d.jsepOnReleaseSession=F=>{C.onReleaseSession(F)},d.jsepCreateMLTensorDownloader=(F,G)=>C.createMLTensorDownloader(F,G),d.jsepRegisterMLTensor=(F,G,ye)=>C.registerMLTensor(F,G,ye),d.jsepCreateMLContext=F=>C.createMLContext(F),d.jsepRegisterMLConstant=(F,G,ye,je,Ye)=>C.registerMLConstant(F,G,ye,je,Ye,d.Fb)}};var V,ie,pe=Object.assign({},d),be="./this.program",De=(l,m)=>{throw m},Pe="";(L||z)&&(z?Pe=self.location.href:typeof document<"u"&&document.currentScript&&(Pe=document.currentScript.src),mr&&(Pe=mr),Pe=Pe.startsWith("blob:")?"":Pe.substr(0,Pe.replace(/[?#].*/,"").lastIndexOf("/")+1),z&&(ie=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),V=(l,m,C)=>{var F=new XMLHttpRequest;F.open("GET",l,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?m(F.response):C()},F.onerror=C,F.send(null)});var Ze,ct=console.log.bind(console),Ct=console.error.bind(console),Dt=ct,St=Ct;if(Object.assign(d,pe),pe=null,D){let l=function(m){try{var C=m.data,F=C.cmd;if(F==="load"){let G=[];self.onmessage=ye=>G.push(ye),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ye of G)l(ye);self.onmessage=l};for(let ye of C.handlers)d[ye]&&!d[ye].proxy||(d[ye]=(...je)=>{postMessage({Nb:"callHandler",pc:ye,args:je})},ye=="print"&&(Dt=d[ye]),ye=="printErr"&&(St=d[ye]));jt=C.wasmMemory,Yr(),bt(C.wasmModule)}else if(F==="run"){Z1(C.pthread_ptr,0,0,1,0,0),H1(C.pthread_ptr),fm(),Up(),Gt||(Rh(),Gt=!0);try{_m(C.start_routine,C.arg)}catch(G){if(G!="unwind")throw G}}else F==="cancel"?_a()&&p1(-1):C.target!=="setimmediate"&&(F==="checkMailbox"?Gt&&r1():F&&(St(`worker: received unknown command ${F}`),St(C)))}catch(G){throw Nh(),G}};var bt,Gt=!1;St=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:_a()})},d.instantiateWasm=(m,C)=>new Promise(F=>{bt=G=>{G=new WebAssembly.Instance(G,zp()),C(G),F()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}d.wasmBinary&&(Ze=d.wasmBinary);var jt,Lt,rr,Yt,qt,Qr,it,Et,hr,vr,xr,gn,Kr,Cr=!1;function Yr(){var l=jt.buffer;d.HEAP8=Yt=new Int8Array(l),d.HEAP16=Qr=new Int16Array(l),d.HEAPU8=qt=new Uint8Array(l),d.HEAPU16=it=new Uint16Array(l),d.HEAP32=Et=new Int32Array(l),d.HEAPU32=hr=new Uint32Array(l),d.HEAPF32=vr=new Float32Array(l),d.HEAPF64=Kr=new Float64Array(l),d.HEAP64=xr=new BigInt64Array(l),d.HEAPU64=gn=new BigUint64Array(l)}if(!D){if(!((jt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof re))throw St("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");Yr()}var e1=[],ju=[],pm=[],Uu=0,Wu=null;function Ip(){if(--Uu==0&&Wu){var l=Wu;Wu=null,l()}}function Kn(l){throw St(l="Aborted("+l+")"),Cr=!0,rr=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),k(l),l}var D1,Op=l=>l.startsWith("data:application/octet-stream;base64,"),Fp=l=>l.startsWith("file://");function Dp(l){if(l==D1&&Ze)return new Uint8Array(Ze);if(ie)return ie(l);throw"both async and sync fetching of the wasm failed"}function Lp(l,m,C){return function(F){if(!Ze&&(L||z)){if(typeof fetch=="function"&&!Fp(F))return fetch(F,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${F}'`;return G.arrayBuffer()}).catch(()=>Dp(F));if(V)return new Promise((G,ye)=>{V(F,je=>G(new Uint8Array(je)),ye)})}return Promise.resolve().then(()=>Dp(F))}(l).then(F=>WebAssembly.instantiate(F,m)).then(C,F=>{St(`failed to asynchronously prepare wasm: ${F}`),Kn(F)})}function zp(){return{a:{O:mm,Aa:hm,b:wm,aa:Kp,B:Xp,qa:Qp,Y:Jp,_:Zp,ra:eh,oa:th,ha:rh,na:sh,L:nh,Z:oh,W:ih,pa:ah,X:lh,va:ym,F:bm,Q:Mm,P:xm,E:Em,u:Pm,q:Cm,G:km,A:Dm,R:Lm,ua:zm,ka:Bm,U:Rm,ba:Nm,H:jm,ja:H1,ta:Um,t:Wm,Ba:Vm,x:Hm,n:qm,l:Qm,c:G1,o:Ym,j:ef,w:tf,p:rf,f:sf,s:nf,m:of,e:af,k:lf,i:df,h:uf,d:cf,ea:pf,fa:hf,ga:mf,ca:vh,da:xh,T:ff,g:_f,D:gf,I:wf,M:yf,y:bf,sa:Mf,V:vf,v:Eh,z:xf,N:Tf,S:Ef,za:Pf,ya:Cf,la:kh,ma:$h,$:N1,C:Sh,K:Ah,ia:Ih,J:Oh,a:jt,xa:R1,wa:Lh,r:Sf}}}var L1={874308:(l,m,C,F,G)=>{if(d===void 0||!d.Fb)return 1;if((l=Fr(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=d.Fb.get(l)))return 2;if(m=Number(m>>>0),C=Number(C>>>0),F=Number(F>>>0),m+C>l.byteLength)return 3;try{let ye=l.subarray(m,m+C);switch(G){case 0:r().set(ye,F>>>0);break;case 1:d.dc(F,ye);break;default:return 4}return 0}catch{return 4}},875023:(l,m,C)=>{d.ec(l,r().subarray(m>>>0,m+C>>>0))},875086:()=>d.bc(),875127:l=>{d.Pb(l)},875163:()=>{d.Wb()},875194:()=>{d.Xb()},875223:()=>{d.ac()},875248:l=>d.Vb(l),875281:l=>d.Zb(l),875313:(l,m,C)=>{d.Ob(Number(l),Number(m),Number(C),!0)},875376:(l,m,C)=>{d.Ob(Number(l),Number(m),Number(C))},875433:()=>typeof wasmOffsetConverter<"u",875490:l=>{d.kb("Abs",l,void 0)},875541:l=>{d.kb("Neg",l,void 0)},875592:l=>{d.kb("Floor",l,void 0)},875645:l=>{d.kb("Ceil",l,void 0)},875697:l=>{d.kb("Reciprocal",l,void 0)},875755:l=>{d.kb("Sqrt",l,void 0)},875807:l=>{d.kb("Exp",l,void 0)},875858:l=>{d.kb("Erf",l,void 0)},875909:l=>{d.kb("Sigmoid",l,void 0)},875964:(l,m,C)=>{d.kb("HardSigmoid",l,{alpha:m,beta:C})},876043:l=>{d.kb("Log",l,void 0)},876094:l=>{d.kb("Sin",l,void 0)},876145:l=>{d.kb("Cos",l,void 0)},876196:l=>{d.kb("Tan",l,void 0)},876247:l=>{d.kb("Asin",l,void 0)},876299:l=>{d.kb("Acos",l,void 0)},876351:l=>{d.kb("Atan",l,void 0)},876403:l=>{d.kb("Sinh",l,void 0)},876455:l=>{d.kb("Cosh",l,void 0)},876507:l=>{d.kb("Asinh",l,void 0)},876560:l=>{d.kb("Acosh",l,void 0)},876613:l=>{d.kb("Atanh",l,void 0)},876666:l=>{d.kb("Tanh",l,void 0)},876718:l=>{d.kb("Not",l,void 0)},876769:(l,m,C)=>{d.kb("Clip",l,{min:m,max:C})},876838:l=>{d.kb("Clip",l,void 0)},876890:(l,m)=>{d.kb("Elu",l,{alpha:m})},876948:l=>{d.kb("Gelu",l,void 0)},877e3:l=>{d.kb("Relu",l,void 0)},877052:(l,m)=>{d.kb("LeakyRelu",l,{alpha:m})},877116:(l,m)=>{d.kb("ThresholdedRelu",l,{alpha:m})},877186:(l,m)=>{d.kb("Cast",l,{to:m})},877244:l=>{d.kb("Add",l,void 0)},877295:l=>{d.kb("Sub",l,void 0)},877346:l=>{d.kb("Mul",l,void 0)},877397:l=>{d.kb("Div",l,void 0)},877448:l=>{d.kb("Pow",l,void 0)},877499:l=>{d.kb("Equal",l,void 0)},877552:l=>{d.kb("Greater",l,void 0)},877607:l=>{d.kb("GreaterOrEqual",l,void 0)},877669:l=>{d.kb("Less",l,void 0)},877721:l=>{d.kb("LessOrEqual",l,void 0)},877780:(l,m,C,F,G)=>{d.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},877955:(l,m,C,F,G)=>{d.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},878129:(l,m,C,F,G)=>{d.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},878303:(l,m,C,F,G)=>{d.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},878478:(l,m,C,F,G)=>{d.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},878652:(l,m,C,F,G)=>{d.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},878825:(l,m,C,F,G)=>{d.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},878998:(l,m,C,F,G)=>{d.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},879175:(l,m,C,F,G)=>{d.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},879355:(l,m,C,F,G)=>{d.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!C,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},879535:l=>{d.kb("Where",l,void 0)},879588:(l,m,C)=>{d.kb("Transpose",l,{perm:m?Array.from(i().subarray(Number(m)>>>0,Number(C)>>>0)):[]})},879712:(l,m,C,F)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Fr(C),format:F?"NHWC":"NCHW"})},879845:(l,m,C,F)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Fr(C),format:F?"NHWC":"NCHW"})},879978:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze,ar)=>{d.kb("ConvTranspose",l,{format:vt?"NHWC":"NCHW",autoPad:m,dilations:[C],group:F,kernelShape:[G],pads:[ye,je],strides:[Ye],wIsConst:()=>!!t()[Pt>>>0],outputPadding:Rt?Array.from(i().subarray(Number(Rt)>>>0,Number(lr)>>>0)):[],outputShape:_r?Array.from(i().subarray(Number(_r)>>>0,Number(ze)>>>0)):[],activation:Fr(ar)})},880411:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze)=>{d.kb("ConvTranspose",l,{format:Ye?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(C)>>>0,2+(Number(C)>>>0)>>>0)),group:F,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(ye)>>>0,4+(Number(ye)>>>0)>>>0)),strides:Array.from(i().subarray(Number(je)>>>0,2+(Number(je)>>>0)>>>0)),wIsConst:()=>!!t()[vt>>>0],outputPadding:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],outputShape:lr?Array.from(i().subarray(Number(lr)>>>0,Number(_r)>>>0)):[],activation:Fr(ze)})},881072:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze,ar)=>{d.kb("ConvTranspose",l,{format:vt?"NHWC":"NCHW",autoPad:m,dilations:[C],group:F,kernelShape:[G],pads:[ye,je],strides:[Ye],wIsConst:()=>!!t()[Pt>>>0],outputPadding:Rt?Array.from(i().subarray(Number(Rt)>>>0,Number(lr)>>>0)):[],outputShape:_r?Array.from(i().subarray(Number(_r)>>>0,Number(ze)>>>0)):[],activation:Fr(ar)})},881505:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze)=>{d.kb("ConvTranspose",l,{format:Ye?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(C)>>>0,2+(Number(C)>>>0)>>>0)),group:F,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(ye)>>>0,4+(Number(ye)>>>0)>>>0)),strides:Array.from(i().subarray(Number(je)>>>0,2+(Number(je)>>>0)>>>0)),wIsConst:()=>!!t()[vt>>>0],outputPadding:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],outputShape:lr?Array.from(i().subarray(Number(lr)>>>0,Number(_r)>>>0)):[],activation:Fr(ze)})},882166:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882257:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze)=>{d.kb("AveragePool",l,{format:ze?"NHWC":"NCHW",auto_pad:m,ceil_mode:C,count_include_pad:F,storage_order:G,dilations:ye?Array.from(i().subarray(Number(ye)>>>0,Number(je)>>>0)):[],kernel_shape:Ye?Array.from(i().subarray(Number(Ye)>>>0,Number(vt)>>>0)):[],pads:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:lr?Array.from(i().subarray(Number(lr)>>>0,Number(_r)>>>0)):[]})},882736:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882827:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze)=>{d.kb("AveragePool",l,{format:ze?"NHWC":"NCHW",auto_pad:m,ceil_mode:C,count_include_pad:F,storage_order:G,dilations:ye?Array.from(i().subarray(Number(ye)>>>0,Number(je)>>>0)):[],kernel_shape:Ye?Array.from(i().subarray(Number(Ye)>>>0,Number(vt)>>>0)):[],pads:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:lr?Array.from(i().subarray(Number(lr)>>>0,Number(_r)>>>0)):[]})},883306:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883393:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze)=>{d.kb("MaxPool",l,{format:ze?"NHWC":"NCHW",auto_pad:m,ceil_mode:C,count_include_pad:F,storage_order:G,dilations:ye?Array.from(i().subarray(Number(ye)>>>0,Number(je)>>>0)):[],kernel_shape:Ye?Array.from(i().subarray(Number(Ye)>>>0,Number(vt)>>>0)):[],pads:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:lr?Array.from(i().subarray(Number(lr)>>>0,Number(_r)>>>0)):[]})},883868:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883955:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze)=>{d.kb("MaxPool",l,{format:ze?"NHWC":"NCHW",auto_pad:m,ceil_mode:C,count_include_pad:F,storage_order:G,dilations:ye?Array.from(i().subarray(Number(ye)>>>0,Number(je)>>>0)):[],kernel_shape:Ye?Array.from(i().subarray(Number(Ye)>>>0,Number(vt)>>>0)):[],pads:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],strides:lr?Array.from(i().subarray(Number(lr)>>>0,Number(_r)>>>0)):[]})},884430:(l,m,C,F,G)=>{d.kb("Gemm",l,{alpha:m,beta:C,transA:F,transB:G})},884534:l=>{d.kb("MatMul",l,void 0)},884588:(l,m,C,F)=>{d.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!C,axis:F})},884696:(l,m,C,F)=>{d.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!C,axis:F})},884804:(l,m)=>{d.kb("Softmax",l,{axis:m})},884867:(l,m)=>{d.kb("Concat",l,{axis:m})},884927:(l,m,C,F,G)=>{d.kb("Split",l,{axis:m,numOutputs:C,splitSizes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},885083:l=>{d.kb("Expand",l,void 0)},885137:(l,m)=>{d.kb("Gather",l,{axis:Number(m)})},885208:(l,m)=>{d.kb("GatherElements",l,{axis:Number(m)})},885287:(l,m)=>{d.kb("GatherND",l,{batch_dims:Number(m)})},885366:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt)=>{d.kb("Resize",l,{antialias:m,axes:C?Array.from(i().subarray(Number(C)>>>0,Number(F)>>>0)):[],coordinateTransformMode:Fr(G),cubicCoeffA:ye,excludeOutside:je,extrapolationValue:Ye,keepAspectRatioPolicy:Fr(vt),mode:Fr(Pt),nearestMode:Fr(Rt)})},885728:(l,m,C,F,G,ye,je)=>{d.kb("Slice",l,{starts:m?Array.from(i().subarray(Number(m)>>>0,Number(C)>>>0)):[],ends:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[],axes:ye?Array.from(i().subarray(Number(ye)>>>0,Number(je)>>>0)):[]})},885992:l=>{d.kb("Tile",l,void 0)},886044:(l,m,C)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:C?"NHWC":"NCHW"})},886158:(l,m,C)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:C?"NHWC":"NCHW"})},886272:l=>{d.kb("Range",l,void 0)},886325:(l,m)=>{d.kb("Einsum",l,{equation:Fr(m)})},886406:(l,m,C,F,G)=>{d.kb("Pad",l,{mode:m,value:C,pads:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},886549:(l,m,C,F,G,ye)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:C,spatial:!!G,trainingMode:!!F,format:ye?"NHWC":"NCHW"})},886718:(l,m,C,F,G,ye)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:C,spatial:!!G,trainingMode:!!F,format:ye?"NHWC":"NCHW"})},886887:(l,m,C)=>{d.kb("CumSum",l,{exclusive:Number(m),reverse:Number(C)})},886984:(l,m,C)=>{d.kb("DequantizeLinear",l,{axis:m,blockSize:C})},887074:(l,m,C,F,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Fr(C),padding_mode:Fr(F),format:G?"NHWC":"NCHW"})},887244:(l,m,C,F,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Fr(C),padding_mode:Fr(F),format:G?"NHWC":"NCHW"})},887414:(l,m)=>{d.kb("ScatterND",l,{reduction:Fr(m)})},887499:(l,m,C,F,G,ye,je,Ye,vt)=>{d.kb("Attention",l,{numHeads:m,isUnidirectional:C,maskFilterValue:F,scale:G,doRotary:ye,qkvHiddenSizes:je?Array.from(i().subarray(Number(Ye)>>>0,Number(Ye)+je>>>0)):[],pastPresentShareBuffer:!!vt})},887771:l=>{d.kb("BiasAdd",l,void 0)},887826:l=>{d.kb("BiasSplitGelu",l,void 0)},887887:l=>{d.kb("FastGelu",l,void 0)},887943:(l,m,C,F,G,ye,je,Ye,vt,Pt,Rt,lr,_r,ze,ar,Dr)=>{d.kb("Conv",l,{format:lr?"NHWC":"NCHW",auto_pad:m,dilations:C?Array.from(i().subarray(Number(C)>>>0,Number(F)>>>0)):[],group:G,kernel_shape:ye?Array.from(i().subarray(Number(ye)>>>0,Number(je)>>>0)):[],pads:Ye?Array.from(i().subarray(Number(Ye)>>>0,Number(vt)>>>0)):[],strides:Pt?Array.from(i().subarray(Number(Pt)>>>0,Number(Rt)>>>0)):[],w_is_const:()=>!!t()[Number(_r)>>>0],activation:Fr(ze),activation_params:ar?Array.from(u().subarray(Number(ar)>>>0,Number(Dr)>>>0)):[]})},888527:l=>{d.kb("Gelu",l,void 0)},888579:(l,m,C,F,G,ye,je,Ye,vt)=>{d.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:C,scale:F,softcap:G,doRotary:ye,rotaryInterleaved:je,smoothSoftmax:Ye,localWindowSize:vt})},888796:(l,m,C,F)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:C,simplified:!!F})},888907:(l,m,C,F)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:C,simplified:!!F})},889018:(l,m,C,F,G,ye)=>{d.kb("MatMulNBits",l,{k:m,n:C,accuracyLevel:F,bits:G,blockSize:ye})},889145:(l,m,C,F,G,ye)=>{d.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:C,maskFilterValue:F,scale:G,doRotary:ye})},889304:(l,m)=>{d.kb("QuickGelu",l,{alpha:m})},889368:(l,m,C,F,G)=>{d.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:C,rotaryEmbeddingDim:F,scale:G})},889507:(l,m,C)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!C})},889609:(l,m,C)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!C})},889711:(l,m,C,F)=>{d.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:C,blockSize:F})},889832:l=>{d.$b(l)},889866:(l,m)=>d.cc(Number(l),Number(m),d.Gb.hc,d.Gb.errors)};function hm(l,m,C){return gh(async()=>{await d.Yb(Number(l),Number(m),Number(C))})}function mm(){return typeof wasmOffsetConverter<"u"}function z1(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var B1=l=>{l.terminate(),l.onmessage=()=>{}},Bp=l=>{Hn.length==0&&(Vp(),Wp(Hn[0]));var m=Hn.pop();if(!m)return 6;Eo.push(m),rn[l.Bb]=m,m.Bb=l.Bb;var C={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(C,l.nc),0},To=0,$r=(l,m,...C)=>{for(var F=2*C.length,G=rp(),ye=tp(8*F),je=ye>>>3,Ye=0;Ye>>0]=vt)}return l=jh(l,0,F,ye,m),h1(G),l};function R1(l){if(D)return $r(0,1,l);if(rr=l,!(0{if(rr=l,D)throw Rp(l),"unwind";R1(l)},Hn=[],Eo=[],Np=[],rn={},jp=l=>{var m=l.Bb;delete rn[m],Hn.push(l),Eo.splice(Eo.indexOf(l),1),l.Bb=0,ep(m)};function Up(){Np.forEach(l=>l())}var Wp=l=>new Promise(m=>{l.onmessage=G=>{var ye=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=_a()){var je=rn[G.targetThread];je?je.postMessage(G,G.transferList):St(`Internal error! Worker sent a message "${ye}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else ye==="checkMailbox"?r1():ye==="spawnThread"?Bp(G):ye==="cleanupThread"?jp(rn[G.thread]):ye==="killThread"?(G=G.thread,ye=rn[G],delete rn[G],B1(ye),ep(G),Eo.splice(Eo.indexOf(ye),1),ye.Bb=0):ye==="cancelThread"?rn[G.thread].postMessage({cmd:"cancel"}):ye==="loaded"?(l.loaded=!0,m(l)):ye==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):ye==="callHandler"?d[G.handler](...G.args):ye&&St(`worker sent an unknown command ${ye}`)},l.onerror=G=>{throw St(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var C,F=[];for(C of[])d.hasOwnProperty(C)&&F.push(C);l.postMessage({cmd:"load",handlers:F,wasmMemory:jt,wasmModule:Lt})});function Vp(){var l=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Hn.push(l)}var t1=l=>{for(;0{var l=_a(),m=a()[l+52>>>2>>>0];l=a()[l+56>>>2>>>0],Wh(m,m-l),h1(m)},_m=(l,m)=>{To=0,l=Vh(l,m),0>>=0);throw m>>>=0,C>>>=0,a()[F.Kb+16>>>2>>>0]=0,a()[F.Kb+4>>>2>>>0]=m,a()[F.Kb+8>>>2>>>0]=C,l}function Gp(l,m,C,F){return D?$r(2,1,l,m,C,F):Kp(l,m,C,F)}function Kp(l,m,C,F){if(l>>>=0,m>>>=0,C>>>=0,F>>>=0,re===void 0)return St("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return D&&G.length===0?Gp(l,m,C,F):(l={ic:C,Bb:l,Rb:F,nc:G},D?(l.Nb="spawnThread",postMessage(l,G),0):Bp(l))}var Hp=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,qp=(l,m,C)=>{var F=(m>>>=0)+C;for(C=m;l[C]&&!(C>=F);)++C;if(16(G=(240&G)==224?(15&G)<<12|ye<<6|je:(7&G)<<18|ye<<12|je<<6|63&l[m++])?F+=String.fromCharCode(G):(G-=65536,F+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else F+=String.fromCharCode(G)}return F},Fr=(l,m)=>(l>>>=0)?qp(r(),l,m):"";function Xp(l,m,C){return D?$r(3,1,l,m,C):0}function Qp(l,m){if(D)return $r(4,1,l,m)}var j1=l=>{for(var m=0,C=0;C=F?m++:2047>=F?m+=2:55296<=F&&57343>=F?(m+=4,++C):m+=3}return m},Yp=(l,m,C,F)=>{if(!(0>>=0;F=C+F-1;for(var ye=0;ye=je&&(je=65536+((1023&je)<<10)|1023&l.charCodeAt(++ye)),127>=je){if(C>=F)break;m[C++>>>0]=je}else{if(2047>=je){if(C+1>=F)break;m[C++>>>0]=192|je>>6}else{if(65535>=je){if(C+2>=F)break;m[C++>>>0]=224|je>>12}else{if(C+3>=F)break;m[C++>>>0]=240|je>>18,m[C++>>>0]=128|je>>12&63}m[C++>>>0]=128|je>>6&63}m[C++>>>0]=128|63&je}}return m[C>>>0]=0,C-G},ma=(l,m,C)=>Yp(l,r(),m,C);function Jp(l,m){if(D)return $r(5,1,l,m)}function Zp(l,m,C){if(D)return $r(6,1,l,m,C)}function eh(l,m,C){return D?$r(7,1,l,m,C):0}function th(l,m){if(D)return $r(8,1,l,m)}function rh(l,m,C){if(D)return $r(9,1,l,m,C)}function sh(l,m,C,F){if(D)return $r(10,1,l,m,C,F)}function nh(l,m,C,F){if(D)return $r(11,1,l,m,C,F)}function oh(l,m,C,F){if(D)return $r(12,1,l,m,C,F)}function ih(l){if(D)return $r(13,1,l)}function ah(l,m){if(D)return $r(14,1,l,m)}function lh(l,m,C){if(D)return $r(15,1,l,m,C)}var dh,qn,ym=()=>{Kn("")},sn=l=>{for(var m="";r()[l>>>0];)m+=dh[r()[l++>>>0]];return m},U1={},W1={};function wn(l,m,C={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(F,G,ye={}){var je=G.name;if(!F)throw new qn(`type "${je}" must have a positive integer typeid pointer`);if(W1.hasOwnProperty(F)){if(ye.Tb)return;throw new qn(`Cannot register type '${je}' twice`)}W1[F]=G,U1.hasOwnProperty(F)&&(G=U1[F],delete U1[F],G.forEach(Ye=>Ye()))}(l,m,C)}var uh=(l,m,C)=>{switch(m){case 1:return C?F=>t()[F>>>0]:F=>r()[F>>>0];case 2:return C?F=>n()[F>>>1>>>0]:F=>o()[F>>>1>>>0];case 4:return C?F=>i()[F>>>2>>>0]:F=>a()[F>>>2>>>0];case 8:return C?F=>xr[F>>>3]:F=>gn[F>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function bm(l,m,C){C>>>=0,wn(l>>>=0,{name:m=sn(m>>>0),fromWireType:F=>F,toWireType:function(F,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(F=typeof G)=="object"||F==="array"||F==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:Xn,readValueFromPointer:uh(m,C,m.indexOf("u")==-1),Eb:null})}var Xn=8;function Mm(l,m,C,F){wn(l>>>=0,{name:m=sn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,ye){return ye?C:F},argPackAdvance:Xn,readValueFromPointer:function(G){return this.fromWireType(r()[G>>>0])},Eb:null})}var V1=[],yn=[];function G1(l){9<(l>>>=0)&&--yn[l+1]==0&&(yn[l]=void 0,V1.push(l))}var ws=l=>{if(!l)throw new qn("Cannot use deleted val. handle = "+l);return yn[l]},Ps=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=V1.pop()||yn.length;return yn[m]=l,yn[m+1]=1,m}};function K1(l){return this.fromWireType(a()[l>>>2>>>0])}var vm={name:"emscripten::val",fromWireType:l=>{var m=ws(l);return G1(l),m},toWireType:(l,m)=>Ps(m),argPackAdvance:Xn,readValueFromPointer:K1,Eb:null};function xm(l){return wn(l>>>0,vm)}var Tm=(l,m)=>{switch(m){case 4:return function(C){return this.fromWireType(u()[C>>>2>>>0])};case 8:return function(C){return this.fromWireType(p()[C>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function Em(l,m,C){C>>>=0,wn(l>>>=0,{name:m=sn(m>>>0),fromWireType:F=>F,toWireType:(F,G)=>G,argPackAdvance:Xn,readValueFromPointer:Tm(m,C),Eb:null})}function Pm(l,m,C,F,G){if(l>>>=0,C>>>=0,m=sn(m>>>0),G===-1&&(G=4294967295),G=Ye=>Ye,F===0){var ye=32-8*C;G=Ye=>Ye<>>ye}var je=m.includes("unsigned")?function(Ye,vt){return vt>>>0}:function(Ye,vt){return vt};wn(l,{name:m,fromWireType:G,toWireType:je,argPackAdvance:Xn,readValueFromPointer:uh(m,C,F!==0),Eb:null})}function Cm(l,m,C){function F(ye){var je=a()[ye>>>2>>>0];return ye=a()[ye+4>>>2>>>0],new G(t().buffer,ye,je)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];wn(l>>>=0,{name:C=sn(C>>>0),fromWireType:F,argPackAdvance:Xn,readValueFromPointer:F},{Tb:!0})}function km(l,m){l>>>=0;var C=(m=sn(m>>>0))==="std::string";wn(l,{name:m,fromWireType:function(F){var G=a()[F>>>2>>>0],ye=F+4;if(C)for(var je=ye,Ye=0;Ye<=G;++Ye){var vt=ye+Ye;if(Ye==G||r()[vt>>>0]==0){if(je=Fr(je,vt-je),Pt===void 0)var Pt=je;else Pt+="\0",Pt+=je;je=vt+1}}else{for(Pt=Array(G),Ye=0;Ye>>0]);Pt=Pt.join("")}return on(F),Pt},toWireType:function(F,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var ye=typeof G=="string";if(!(ye||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new qn("Cannot pass non-string to std::string");var je=C&&ye?j1(G):G.length,Ye=c1(4+je+1),vt=Ye+4;if(a()[Ye>>>2>>>0]=je,C&&ye)ma(G,vt,je+1);else if(ye)for(ye=0;ye>>0]=Pt}else for(ye=0;ye>>0]=G[ye];return F!==null&&F.push(on,Ye),Ye},argPackAdvance:Xn,readValueFromPointer:K1,Eb(F){on(F)}})}var ch=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,$m=(l,m)=>{for(var C=l>>1,F=C+m/2;!(C>=F)&&o()[C>>>0];)++C;if(32<(C<<=1)-l&&ch)return ch.decode(r().slice(l,C));for(C="",F=0;!(F>=m/2);++F){var G=n()[l+2*F>>>1>>>0];if(G==0)break;C+=String.fromCharCode(G)}return C},Sm=(l,m,C)=>{if(C??=2147483647,2>C)return 0;var F=m;C=(C-=2)<2*l.length?C/2:l.length;for(var G=0;G>>1>>>0]=ye,m+=2}return n()[m>>>1>>>0]=0,m-F},Am=l=>2*l.length,Im=(l,m)=>{for(var C=0,F="";!(C>=m/4);){var G=i()[l+4*C>>>2>>>0];if(G==0)break;++C,65536<=G?(G-=65536,F+=String.fromCharCode(55296|G>>10,56320|1023&G)):F+=String.fromCharCode(G)}return F},Om=(l,m,C)=>{if(m>>>=0,C??=2147483647,4>C)return 0;var F=m;C=F+C-4;for(var G=0;G=ye&&(ye=65536+((1023&ye)<<10)|1023&l.charCodeAt(++G)),i()[m>>>2>>>0]=ye,(m+=4)+4>C)break}return i()[m>>>2>>>0]=0,m-F},Fm=l=>{for(var m=0,C=0;C=F&&++C,m+=4}return m};function Dm(l,m,C){if(l>>>=0,m>>>=0,C=sn(C>>>=0),m===2)var F=$m,G=Sm,ye=Am,je=Ye=>o()[Ye>>>1>>>0];else m===4&&(F=Im,G=Om,ye=Fm,je=Ye=>a()[Ye>>>2>>>0]);wn(l,{name:C,fromWireType:Ye=>{for(var vt,Pt=a()[Ye>>>2>>>0],Rt=Ye+4,lr=0;lr<=Pt;++lr){var _r=Ye+4+lr*m;lr!=Pt&&je(_r)!=0||(Rt=F(Rt,_r-Rt),vt===void 0?vt=Rt:(vt+="\0",vt+=Rt),Rt=_r+m)}return on(Ye),vt},toWireType:(Ye,vt)=>{if(typeof vt!="string")throw new qn(`Cannot pass non-string to C++ string type ${C}`);var Pt=ye(vt),Rt=c1(4+Pt+m);return a()[Rt>>>2>>>0]=Pt/m,G(vt,Rt+4,Pt+m),Ye!==null&&Ye.push(on,Rt),Rt},argPackAdvance:Xn,readValueFromPointer:K1,Eb(Ye){on(Ye)}})}function Lm(l,m){wn(l>>>=0,{Ub:!0,name:m=sn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var zm=()=>1;function Bm(l){Z1(l>>>0,!z,1,!L,131072,!1),Up()}var ph=l=>{if(!Cr)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(i(),l>>>2,l).value.then(r1),l+=128,Atomics.store(i(),l>>>2,1))}var r1=()=>{var l=_a();l&&(H1(l),ph(Uh))};function Rm(l,m){(l>>>=0)==m>>>0?setTimeout(r1):D?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=rn[l])&&l.postMessage({cmd:"checkMailbox"})}var q1=[];function Nm(l,m,C,F,G){for(m>>>=0,F/=2,q1.length=F,C=G>>>0>>>3,G=0;G>>0];return(m?L1[m]:Af[l])(...q1)}function jm(l){l>>>=0,D?postMessage({cmd:"cleanupThread",thread:l}):jp(rn[l])}function Um(l){}var s1=(l,m)=>{var C=W1[l];if(C===void 0)throw l=Bh(l),C=sn(l),on(l),new qn(`${m} has unknown type ${C}`);return C},hh=(l,m,C)=>{var F=[];return l=l.toWireType(F,C),F.length&&(a()[m>>>2>>>0]=Ps(F)),l};function Wm(l,m,C){return m>>>=0,C>>>=0,l=ws(l>>>0),m=s1(m,"emval::as"),hh(m,C,l)}function Vm(l,m){return m>>>=0,l=ws(l>>>0),(m=s1(m,"emval::as")).toWireType(null,l)}var n1=l=>{try{l()}catch(m){Kn(m)}},Qn=0,nn=null,mh=0,o1=[],fh={},_h={},Gm=0,X1=null,Km=[];function gh(l){return function(m){if(!Cr){if(Qn===0){var C=!1,F=!1;m((G=0)=>{if(!Cr&&(mh=G,C=!0,F)){Qn=2,n1(()=>Hh(nn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var ye=function(){var vt=i()[nn+8>>>2>>>0];return vt=Bt[_h[vt]],--To,vt()}()}catch(vt){ye=vt,G=!0}var je=!1;if(!nn){var Ye=X1;Ye&&(X1=null,(G?Ye.reject:Ye.resolve)(ye),je=!0)}if(G&&!je)throw ye}}),F=!0,C||(Qn=1,nn=function(){var G=c1(65548),ye=G+12;a()[G>>>2>>>0]=ye,a()[G+4>>>2>>>0]=ye+65536,ye=o1[0];var je=fh[ye];return je===void 0&&(je=Gm++,fh[ye]=je,_h[je]=ye),ye=je,i()[G+8>>>2>>>0]=ye,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),n1(()=>Gh(nn)))}else Qn===2?(Qn=0,n1(qh),on(nn),nn=null,Km.forEach(ph)):Kn(`invalid state: ${Qn}`);return mh}}(m=>{l().then(m)})}function Hm(l){return l>>>=0,gh(()=>(l=ws(l)).then(Ps))}var i1=[];function qm(l,m,C,F){return C>>>=0,F>>>=0,(l=i1[l>>>0])(null,m=ws(m>>>0),C,F)}var Xm={},a1=l=>{var m=Xm[l];return m===void 0?sn(l):m};function Qm(l,m,C,F,G){return C>>>=0,F>>>=0,G>>>=0,(l=i1[l>>>0])(m=ws(m>>>0),m[C=a1(C)],F,G)}var wh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ym(l){return(l>>>=0)==0?Ps(wh()):(l=a1(l),Ps(wh()[l]))}var Jm=l=>{var m=i1.length;return i1.push(l),m},Zm=(l,m)=>{for(var C=Array(l),F=0;F>>2>>>0],"parameter "+F);return C},yh=(l,m)=>Object.defineProperty(m,"name",{value:l});function ef(l,m,C){var F=(m=Zm(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { `,ye=0,je=[];C===0&&je.push("obj");for(var Ye=["retType"],vt=[F],Pt=0;PtRt.name).join(", ")}) => ${F.name}>`,Jm(yh(C,l))}function tf(l){return l=a1(l>>>0),Ps(d[l])}function rf(l,m){return m>>>=0,l=ws(l>>>0),m=ws(m),Ps(l[m])}function sf(l){9<(l>>>=0)&&(yn[l+1]+=1)}function nf(){return Ps([])}function of(l){l=ws(l>>>0);for(var m=Array(l.length),C=0;C>>0))}function lf(){return Ps({})}function df(l){for(var m=ws(l>>>=0);m.length;){var C=m.pop();m.pop()(C)}G1(l)}function uf(l,m,C){m>>>=0,C>>>=0,l=ws(l>>>0),m=ws(m),C=ws(C),l[m]=C}function cf(l,m){return m>>>=0,l=(l=s1(l>>>0,"_emval_take_value")).readValueFromPointer(m),Ps(l)}function pf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getUTCSeconds(),i()[m+4>>>2>>>0]=l.getUTCMinutes(),i()[m+8>>>2>>>0]=l.getUTCHours(),i()[m+12>>>2>>>0]=l.getUTCDate(),i()[m+16>>>2>>>0]=l.getUTCMonth(),i()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,i()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[m+28>>>2>>>0]=l}var fa=l=>l%4==0&&(l%100!=0||l%400==0),bh=[0,31,60,91,121,152,182,213,244,274,305,335],Mh=[0,31,59,90,120,151,181,212,243,273,304,334];function hf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getSeconds(),i()[m+4>>>2>>>0]=l.getMinutes(),i()[m+8>>>2>>>0]=l.getHours(),i()[m+12>>>2>>>0]=l.getDate(),i()[m+16>>>2>>>0]=l.getMonth(),i()[m+20>>>2>>>0]=l.getFullYear()-1900,i()[m+24>>>2>>>0]=l.getDay();var C=(fa(l.getFullYear())?bh:Mh)[l.getMonth()]+l.getDate()-1|0;i()[m+28>>>2>>>0]=C,i()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),C=new Date(l.getFullYear(),6,1).getTimezoneOffset();var F=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(C!=F&&l.getTimezoneOffset()==Math.min(F,C)),i()[m+32>>>2>>>0]=l}function mf(l){l>>>=0;var m=new Date(i()[l+20>>>2>>>0]+1900,i()[l+16>>>2>>>0],i()[l+12>>>2>>>0],i()[l+8>>>2>>>0],i()[l+4>>>2>>>0],i()[l>>>2>>>0],0),C=i()[l+32>>>2>>>0],F=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),ye=new Date(m.getFullYear(),0,1).getTimezoneOffset(),je=Math.min(ye,G);return 0>C?i()[l+32>>>2>>>0]=+(G!=ye&&je==F):0>>2>>>0]=m.getDay(),C=(fa(m.getFullYear())?bh:Mh)[m.getMonth()]+m.getDate()-1|0,i()[l+28>>>2>>>0]=C,i()[l>>>2>>>0]=m.getSeconds(),i()[l+4>>>2>>>0]=m.getMinutes(),i()[l+8>>>2>>>0]=m.getHours(),i()[l+12>>>2>>>0]=m.getDate(),i()[l+16>>>2>>>0]=m.getMonth(),i()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function vh(l,m,C,F,G,ye,je){return D?$r(16,1,l,m,C,F,G,ye,je):-52}function xh(l,m,C,F,G,ye){if(D)return $r(17,1,l,m,C,F,G,ye)}function ff(l,m,C,F){l>>>=0,m>>>=0,C>>>=0,F>>>=0;var G=new Date().getFullYear(),ye=new Date(G,0,1),je=new Date(G,6,1);G=ye.getTimezoneOffset();var Ye=je.getTimezoneOffset(),vt=Math.max(G,Ye);a()[l>>>2>>>0]=60*vt,i()[m>>>2>>>0]=+(G!=Ye),ye=(l=Pt=>Pt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ye),je=l(je),Ye{Q1.length=0;for(var C;C=r()[l++>>>0];){var F=C!=105;m+=(F&=C!=112)&&m%8?4:0,Q1.push(C==112?a()[m>>>2>>>0]:C==106?xr[m>>>3]:C==105?i()[m>>>2>>>0]:p()[m>>>3>>>0]),m+=F?8:4}return Q1};function _f(l,m,C){return l>>>=0,m=Th(m>>>0,C>>>0),L1[l](...m)}function gf(l,m,C){return l>>>=0,m=Th(m>>>0,C>>>0),L1[l](...m)}var wf=()=>{},yf=()=>Date.now();function bf(l,m){return St(Fr(l>>>0,m>>>0))}var Eh,Mf=()=>{throw To+=1,"unwind"};function vf(){return 4294901760}Eh=()=>performance.timeOrigin+performance.now();var xf=()=>navigator.hardwareConcurrency;function Tf(){return Kn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Ef(l){l>>>=0;var m=r().length;if(l<=m||4294901760=C;C*=2){var F=m*(1+.2/C);F=Math.min(F,l+100663296);var G=Math;F=Math.max(l,F);e:{G=(G.min.call(G,4294901760,F+(65536-F%65536)%65536)-jt.buffer.byteLength+65535)/65536;try{jt.grow(G),Yr();var ye=1;break e}catch{}ye=void 0}if(ye)return!0}return!1}var l1=()=>(Kn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Vu={},Ph=l=>{l.forEach(m=>{l1()})};function Pf(){var l=Error().stack.toString().split(` `);return l[0]=="Error"&&l.shift(),Ph(l),Vu.Qb=l1(),Vu.fc=l,Vu.Qb}function Cf(l,m,C){if(l>>>=0,m>>>=0,Vu.Qb==l)var F=Vu.fc;else(F=Error().stack.toString().split(` `))[0]=="Error"&&F.shift(),Ph(F);for(var G=3;F[G]&&l1()!=l;)++G;for(l=0;l>>2>>>0]=l1();return l}var Y1,J1={},Ch=()=>{if(!Y1){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 J1)J1[l]===void 0?delete m[l]:m[l]=J1[l];var C=[];for(l in m)C.push(`${l}=${m[l]}`);Y1=C}return Y1};function kh(l,m){if(D)return $r(18,1,l,m);l>>>=0,m>>>=0;var C=0;return Ch().forEach((F,G)=>{var ye=m+C;for(G=a()[l+4*G>>>2>>>0]=ye,ye=0;ye>>0]=F.charCodeAt(ye);t()[G>>>0]=0,C+=F.length+1}),0}function $h(l,m){if(D)return $r(19,1,l,m);l>>>=0,m>>>=0;var C=Ch();a()[l>>>2>>>0]=C.length;var F=0;return C.forEach(G=>F+=G.length+1),a()[m>>>2>>>0]=F,0}function Sh(l){return D?$r(20,1,l):52}function Ah(l,m,C,F){return D?$r(21,1,l,m,C,F):52}function Ih(l,m,C,F){return D?$r(22,1,l,m,C,F):70}var kf=[null,[],[]];function Oh(l,m,C,F){if(D)return $r(23,1,l,m,C,F);m>>>=0,C>>>=0,F>>>=0;for(var G=0,ye=0;ye>>2>>>0],Ye=a()[m+4>>>2>>>0];m+=8;for(var vt=0;vt>>0],Rt=kf[l];Pt===0||Pt===10?((l===1?Dt:St)(qp(Rt,0)),Rt.length=0):Rt.push(Pt)}G+=Ye}return a()[F>>>2>>>0]=G,0}var Fh=[31,29,31,30,31,30,31,31,30,31,30,31],Dh=[31,28,31,30,31,30,31,31,30,31,30,31],$f=(l,m)=>{t().set(l,m>>>0)};function Lh(l,m,C,F){function G(ze,ar,Dr){for(ze=typeof ze=="number"?ze.toString():ze||"";ze.lengthQh?-1:0Po-ze.getDate())){ze.setDate(ze.getDate()+ar);break}ar-=Po-ze.getDate()+1,ze.setDate(1),11>Dr?ze.setMonth(Dr+1):(ze.setMonth(0),ze.setFullYear(ze.getFullYear()+1))}return Dr=new Date(ze.getFullYear()+1,0,4),ar=Ye(new Date(ze.getFullYear(),0,4)),Dr=Ye(Dr),0>=je(ar,ze)?0>=je(Dr,ze)?ze.getFullYear()+1:ze.getFullYear():ze.getFullYear()-1}l>>>=0,m>>>=0,C>>>=0,F>>>=0;var Pt=a()[F+40>>>2>>>0];for(var Rt in F={lc:i()[F>>>2>>>0],kc:i()[F+4>>>2>>>0],Ib:i()[F+8>>>2>>>0],Mb:i()[F+12>>>2>>>0],Jb:i()[F+16>>>2>>>0],Db:i()[F+20>>>2>>>0],vb:i()[F+24>>>2>>>0],Cb:i()[F+28>>>2>>>0],sc:i()[F+32>>>2>>>0],jc:i()[F+36>>>2>>>0],mc:Pt?Fr(Pt):""},C=Fr(C),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"})C=C.replace(new RegExp(Rt,"g"),Pt[Rt]);var lr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),_r="January February March April May June July August September October November December".split(" ");for(Rt in Pt={"%a":ze=>lr[ze.vb].substring(0,3),"%A":ze=>lr[ze.vb],"%b":ze=>_r[ze.Jb].substring(0,3),"%B":ze=>_r[ze.Jb],"%C":ze=>ye((ze.Db+1900)/100|0,2),"%d":ze=>ye(ze.Mb,2),"%e":ze=>G(ze.Mb,2," "),"%g":ze=>vt(ze).toString().substring(2),"%G":vt,"%H":ze=>ye(ze.Ib,2),"%I":ze=>((ze=ze.Ib)==0?ze=12:12{for(var ar=0,Dr=0;Dr<=ze.Jb-1;ar+=(fa(ze.Db+1900)?Fh:Dh)[Dr++]);return ye(ze.Mb+ar,3)},"%m":ze=>ye(ze.Jb+1,2),"%M":ze=>ye(ze.kc,2),"%n":()=>` `,"%p":ze=>0<=ze.Ib&&12>ze.Ib?"AM":"PM","%S":ze=>ye(ze.lc,2),"%t":()=>" ","%u":ze=>ze.vb||7,"%U":ze=>ye(Math.floor((ze.Cb+7-ze.vb)/7),2),"%V":ze=>{var ar=Math.floor((ze.Cb+7-(ze.vb+6)%7)/7);if(2>=(ze.vb+371-ze.Cb-2)%7&&ar++,ar)ar==53&&((Dr=(ze.vb+371-ze.Cb)%7)==4||Dr==3&&fa(ze.Db)||(ar=1));else{ar=52;var Dr=(ze.vb+7-ze.Cb-1)%7;(Dr==4||Dr==5&&fa(ze.Db%400-1))&&ar++}return ye(ar,2)},"%w":ze=>ze.vb,"%W":ze=>ye(Math.floor((ze.Cb+7-(ze.vb+6)%7)/7),2),"%y":ze=>(ze.Db+1900).toString().substring(2),"%Y":ze=>ze.Db+1900,"%z":ze=>{var ar=0<=(ze=ze.jc);return ze=Math.abs(ze)/60,(ar?"+":"-")+("0000"+(ze/60*100+ze%60)).slice(-4)},"%Z":ze=>ze.mc,"%%":()=>"%"},C=C.replace(/%%/g,"\0\0"),Pt)C.includes(Rt)&&(C=C.replace(new RegExp(Rt,"g"),Pt[Rt](F)));return Rt=function(ze){var ar=Array(j1(ze)+1);return Yp(ze,ar,0,ar.length),ar}(C=C.replace(/\0\0/g,"%")),Rt.length>m?0:($f(Rt,l),Rt.length-1)}function Sf(l,m,C,F){return Lh(l>>>0,m>>>0,C>>>0,F>>>0)}D||function(){for(var l=d.numThreads-1;l--;)Vp();e1.unshift(()=>{Uu++,function(m){D?m():Promise.all(Hn.map(Wp)).then(m)}(()=>Ip())})}();for(var zh=Array(256),d1=0;256>d1;++d1)zh[d1]=String.fromCharCode(d1);dh=zh,qn=d.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},d.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},yn.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>yn.length/2-5-V1.length;var Af=[R1,Rp,Gp,Xp,Qp,Jp,Zp,eh,th,rh,sh,nh,oh,ih,ah,lh,vh,xh,kh,$h,Sh,Ah,Ih,Oh],Bt=function(){function l(C,F){return Bt=C.exports,Bt=function(){var G=Bt,ye={};for(let[je,Ye]of Object.entries(G))ye[je]=typeof Ye=="function"?(...vt)=>{o1.push(je);try{return Ye(...vt)}finally{Cr||(o1.pop(),nn&&Qn===1&&o1.length===0&&(Qn=0,To+=1,n1(Kh),typeof Fibers<"u"&&Fibers.tc()))}}:Ye;return ye}(),Bt=function(){var G=Bt,ye=Ye=>vt=>Ye(vt)>>>0,je=Ye=>()=>Ye()>>>0;return(G=Object.assign({},G)).Da=ye(G.Da),G.gb=je(G.gb),G.ib=ye(G.ib),G.emscripten_main_runtime_thread_id=je(G.emscripten_main_runtime_thread_id),G.tb=ye(G.tb),G.ub=je(G.ub),G}(),Np.push(Bt.jb),ju.unshift(Bt.Ca),Lt=F,Ip(),Bt}var m=zp();if(Uu++,d.instantiateWasm)try{return d.instantiateWasm(m,l)}catch(C){St(`Module.instantiateWasm callback failed with error: ${C}`),k(C)}return D1||=d.locateFile?Op("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",Pe):Pe+"ort-wasm-simd-threaded.jsep.wasm":new URL(s("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),s.b).href,function(C,F){var G=D1;return Ze||typeof WebAssembly.instantiateStreaming!="function"||Op(G)||Fp(G)||typeof fetch!="function"?Lp(G,C,F):fetch(G,{credentials:"same-origin"}).then(ye=>WebAssembly.instantiateStreaming(ye,C).then(F,function(je){return St(`wasm streaming compile failed: ${je}`),St("falling back to ArrayBuffer instantiation"),Lp(G,C,F)}))}(m,function(C){l(C.instance,C.module)}).catch(k),{}}(),Bh=l=>(Bh=Bt.Da)(l),Rh=()=>(Rh=Bt.Ea)();d._OrtInit=(l,m)=>(d._OrtInit=Bt.Fa)(l,m),d._OrtGetLastError=(l,m)=>(d._OrtGetLastError=Bt.Ga)(l,m),d._OrtCreateSessionOptions=(l,m,C,F,G,ye,je,Ye,vt,Pt)=>(d._OrtCreateSessionOptions=Bt.Ha)(l,m,C,F,G,ye,je,Ye,vt,Pt),d._OrtAppendExecutionProvider=(l,m)=>(d._OrtAppendExecutionProvider=Bt.Ia)(l,m),d._OrtAddFreeDimensionOverride=(l,m,C)=>(d._OrtAddFreeDimensionOverride=Bt.Ja)(l,m,C),d._OrtAddSessionConfigEntry=(l,m,C)=>(d._OrtAddSessionConfigEntry=Bt.Ka)(l,m,C),d._OrtReleaseSessionOptions=l=>(d._OrtReleaseSessionOptions=Bt.La)(l),d._OrtCreateSession=(l,m,C)=>(d._OrtCreateSession=Bt.Ma)(l,m,C),d._OrtReleaseSession=l=>(d._OrtReleaseSession=Bt.Na)(l),d._OrtGetInputOutputCount=(l,m,C)=>(d._OrtGetInputOutputCount=Bt.Oa)(l,m,C),d._OrtGetInputName=(l,m)=>(d._OrtGetInputName=Bt.Pa)(l,m),d._OrtGetOutputName=(l,m)=>(d._OrtGetOutputName=Bt.Qa)(l,m),d._OrtFree=l=>(d._OrtFree=Bt.Ra)(l),d._OrtCreateTensor=(l,m,C,F,G,ye)=>(d._OrtCreateTensor=Bt.Sa)(l,m,C,F,G,ye),d._OrtGetTensorData=(l,m,C,F,G)=>(d._OrtGetTensorData=Bt.Ta)(l,m,C,F,G),d._OrtReleaseTensor=l=>(d._OrtReleaseTensor=Bt.Ua)(l),d._OrtCreateRunOptions=(l,m,C,F)=>(d._OrtCreateRunOptions=Bt.Va)(l,m,C,F),d._OrtAddRunConfigEntry=(l,m,C)=>(d._OrtAddRunConfigEntry=Bt.Wa)(l,m,C),d._OrtReleaseRunOptions=l=>(d._OrtReleaseRunOptions=Bt.Xa)(l),d._OrtCreateBinding=l=>(d._OrtCreateBinding=Bt.Ya)(l),d._OrtBindInput=(l,m,C)=>(d._OrtBindInput=Bt.Za)(l,m,C),d._OrtBindOutput=(l,m,C,F)=>(d._OrtBindOutput=Bt._a)(l,m,C,F),d._OrtClearBoundOutputs=l=>(d._OrtClearBoundOutputs=Bt.$a)(l),d._OrtReleaseBinding=l=>(d._OrtReleaseBinding=Bt.ab)(l),d._OrtRunWithBinding=(l,m,C,F,G)=>(d._OrtRunWithBinding=Bt.bb)(l,m,C,F,G),d._OrtRun=(l,m,C,F,G,ye,je,Ye)=>(d._OrtRun=Bt.cb)(l,m,C,F,G,ye,je,Ye),d._OrtEndProfiling=l=>(d._OrtEndProfiling=Bt.db)(l),d._JsepOutput=(l,m,C)=>(d._JsepOutput=Bt.eb)(l,m,C),d._JsepGetNodeName=l=>(d._JsepGetNodeName=Bt.fb)(l);var u1,_a=()=>(_a=Bt.gb)(),on=d._free=l=>(on=d._free=Bt.hb)(l),c1=d._malloc=l=>(c1=d._malloc=Bt.ib)(l),Z1=(l,m,C,F,G,ye)=>(Z1=Bt.lb)(l,m,C,F,G,ye),Nh=()=>(Nh=Bt.mb)(),jh=(l,m,C,F,G)=>(jh=Bt.nb)(l,m,C,F,G),ep=l=>(ep=Bt.ob)(l),p1=l=>(p1=Bt.pb)(l),Uh=()=>(Uh=Bt.qb)(),Wh=(l,m)=>(Wh=Bt.rb)(l,m),h1=l=>(h1=Bt.sb)(l),tp=l=>(tp=Bt.tb)(l),rp=()=>(rp=Bt.ub)(),Vh=d.dynCall_ii=(l,m)=>(Vh=d.dynCall_ii=Bt.wb)(l,m),Gh=l=>(Gh=Bt.xb)(l),Kh=()=>(Kh=Bt.yb)(),Hh=l=>(Hh=Bt.zb)(l),qh=()=>(qh=Bt.Ab)();function Xh(){0rp(),d.stackRestore=l=>h1(l),d.stackAlloc=l=>tp(l),d.setValue=function(l,m,C="i8"){switch(C.endsWith("*")&&(C="*"),C){case"i1":case"i8":t()[l>>>0]=m;break;case"i16":n()[l>>>1>>>0]=m;break;case"i32":i()[l>>>2>>>0]=m;break;case"i64":xr[l>>>3]=BigInt(m);break;case"float":u()[l>>>2>>>0]=m;break;case"double":p()[l>>>3>>>0]=m;break;case"*":a()[l>>>2>>>0]=m;break;default:Kn(`invalid type for setValue: ${C}`)}},d.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return t()[l>>>0];case"i16":return n()[l>>>1>>>0];case"i32":return i()[l>>>2>>>0];case"i64":return xr[l>>>3];case"float":return u()[l>>>2>>>0];case"double":return p()[l>>>3>>>0];case"*":return a()[l>>>2>>>0];default:Kn(`invalid type for getValue: ${m}`)}},d.UTF8ToString=Fr,d.stringToUTF8=ma,d.lengthBytesUTF8=j1,Wu=function l(){u1||Xh(),u1||(Wu=l)},Xh(),d.PTR_SIZE=4,S}),br=Sr,globalThis.self?.name==="em-pthread"&&Sr()}),ns,Bs,Cs,an,Ot,Rs,ys,ks,bs=b(()=>{Je(),ns=import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Bs=typeof location>"u"?void 0:location.origin,Cs=(e,t)=>{try{let r=t??ns;return(r?new URL(e,r):new URL(e)).origin===Bs}catch{return!1}},an=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Ot=(tr(),x(nt)).default,Rs=async()=>{if(!ns)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Cs(ns))return[void 0,Ot()];let e=await an(ns);return[e,Ot(e)]},ys=(Hr(),x(Tr)).default,ks=async(e,t,r)=>[void 0,ys]}),$s,Jr,ls,Ms,Ns,os,ot,dt,kt=b(()=>{bs(),Jr=!1,ls=!1,Ms=!1,Ns=()=>{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}},os=()=>{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}},ot=async e=>{if(Jr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ms)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let t=e.initTimeout,r=e.numThreads;if(!os())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ns();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o=="string"?o:void 0,a=o?.mjs,u=a?.href??a,p=o?.wasm,h=p?.href??p,k=e.wasmBinary,[d,S]=await ks(u,i,r>1),L=!1,z=[];if(t>0&&z.push(new Promise(D=>{setTimeout(()=>{L=!0,D()},t)})),z.push(new Promise((D,re)=>{let te={numThreads:r};k?te.wasmBinary=k:(h||i)&&(te.locateFile=(V,ie)=>h??(i??ie)+V),S(te).then(V=>{ls=!1,Jr=!0,$s=V,D(),d&&URL.revokeObjectURL(d)},V=>{ls=!1,Ms=!0,re(V)})})),await Promise.race(z),L)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},dt=()=>{if(Jr&&$s)return $s;throw new Error("WebAssembly is not initialized yet.")}}),cr,js,sr,Us=b(()=>{kt(),cr=(e,t)=>{let r=dt(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},js=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i=="object")js(i,a+".",r,n);else if(typeof i=="string"||typeof i=="number")n(a,i.toString());else if(typeof i=="boolean")n(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},sr=e=>{let t=dt(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?"i32":"i64")),a=t.getValue(o+n,"*"),u=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}}}),Ss,Yn=b(()=>{kt(),Us(),Ss=e=>{let t=dt(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=cr(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&sr("Can't create run options."),e?.extra!==void 0&&js(e.extra,"",new WeakSet,(a,u)=>{let p=cr(a,n),h=cr(u,n);t._OrtAddRunConfigEntry(r,p,h)!==0&&sr(`Can't set a run config entry: ${a} - ${u}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}}),Mn,Ws,vn,As,xn,Jn=b(()=>{kt(),Us(),Mn=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}`)}},Ws=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},vn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},As=(e,t,r)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let a=n?.deviceType;if(a){let u=cr("deviceType",r),p=cr(a,r);dt()._OrtAddSessionConfigEntry(e,u,p)!==0&&sr(`Can't set a session config entry: 'deviceType' - ${a}.`)}}break;case"webgpu":if(o="JS",typeof n!="string"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let u=cr("preferredLayout",r),p=cr(a.preferredLayout,r);dt()._OrtAddSessionConfigEntry(e,u,p)!==0&&sr(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=cr(o,r);dt()._OrtAppendExecutionProvider(e,i)!==0&&sr(`Can't append execution provider: ${o}.`)}},xn=e=>{let t=dt(),r=0,n=[],o=e||{};vn(o);try{let i=Mn(o.graphOptimizationLevel??"all"),a=Ws(o.executionMode??"sequential"),u=typeof o.logId=="string"?cr(o.logId,n):0,p=o.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=o.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof o.optimizedModelFilePath=="string"?cr(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,u,p,h,k),r===0&&sr("Can't create session options."),o.executionProviders&&As(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let d=cr("enableGraphCapture",n),S=cr(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,d,S)!==0&&sr(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[d,S]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof S!="number"||!Number.isInteger(S)||S<0)throw new Error(`free dimension override value must be a non-negative integer: ${S}`);let L=cr(d,n);t._OrtAddFreeDimensionOverride(r,L,S)!==0&&sr(`Can't set a free dimension override: ${d} - ${S}.`)}return o.extra!==void 0&&js(o.extra,"",new WeakSet,(d,S)=>{let L=cr(d,n),z=cr(S,n);t._OrtAddSessionConfigEntry(r,L,z)!==0&&sr(`Can't set a session config entry: ${d} - ${S}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&sr("Can't release session options."),n.forEach(a=>t._free(a)),i}}}),Is,hs,Zr,ln,Vs,dn,Gs,un,Ft=b(()=>{Is=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}`)}},hs=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}`)}},Zr=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},ln=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Vs=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}`)}},dn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Gs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",un=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),cn,Tn=b(()=>{Je(),cn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let p=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw u}let a=0;for(;;){let{done:u,value:p}=await o.read();if(u)break;let h=p.byteLength;new Uint8Array(i,a,h).set(p),a+=h}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),En,Pn,Os,Cn,pn,kn,nr,es=b(()=>{Ft(),En=["V","I","W","E","F"],Pn=(e,t)=>{console.log(`[${En[e]},${new Date().toISOString()}]${t}`)},pn=(e,t)=>{Os=e,Cn=t},kn=(e,t)=>{let r=Vs(e),n=Vs(Os);r>=n&&Pn(r,typeof t=="function"?t():t)},nr=(...e)=>{Cn&&kn(...e)}}),hn,$n=b(()=>{Ft(),hn=(e,t)=>new(ln(t))(e)}),Ks=b(()=>{}),Sn,xe,y,Y,le,we,Ie,Ke,ht,mt=b(()=>{es(),Ks(),Sn=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),xe=[],y=e=>Math.ceil(Number(e)/16)*16,Y=e=>{for(let t=0;tle++,Ie=async(e,t,r,n)=>{let o=y(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let u=i.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(u,0,r)),p}else return new Uint8Array(u.slice(0,r))}finally{i.destroy()}},Ke=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 Sn)xe.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let r=t.buffer,n=t.byteOffset,o=t.byteLength,i=y(o),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(Number(a.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${o}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=u.getMappedRange();new Uint8Array(p).set(new Uint8Array(r,n,o)),u.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(u,0,a.gpuData.buffer,0,i),this.backend.device.queue.submit([h.finish()]),u.destroy(),nr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=y(r.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,o)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[1])return nr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else n=we();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),nr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),nr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Y(e),n,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||i){let u=(o?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let a={id:we(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:Number(e)}),nr("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,r=this.storageCache.get(t);if(!r){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return nr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(e,t){let r=this.storageCache.get(Number(e));if(!r)throw new Error("data does not exist");await Ie(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Sn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(nr("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ht=(...e)=>new Ke(...e)}),Mt,qe,It=b(()=>{Mt=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},qe=e=>new Mt(e)}),Xt,gr,Ce,Er,jr,Rr,ds,zt=b(()=>{Xt=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},gr=class{static calcShape(e,t,r=!1){let n=e.length,o=t.length;if(n===0)return t;if(o===0)return e;let i=Math.max(e.length,t.length),a=new Array(i);if(r){if(n<2||o<2)return;let u=Xt.calcMatMulShape([e[n-2],e[n-1]],[t[o-2],t[o-1]]);if(u===void 0)return;[a[i-2],a[i-1]]=u}for(let u=r?3:1;u<=i;u++){let p=n-u<0?1:e[n-u],h=o-u<0?1:t[o-u];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)a[i-u]=Math.max(p,h);else{if(k>1)return;a[i-u]=0}}return a}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let o=1;o<=r;o++)if(e[r-o]!==1&&e[r-o]!==t[n-o])return!1;return!0}},Ce=class f1{static size(t){return f1.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return f1.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return f1.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},Er=class Gu{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||a[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,u){if(u){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Ft(),zt(),Lr=64,ms=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Zt=(e,t=1)=>{let r=ms(e,t);return typeof r=="string"?r:r[0]},dr=(e,t=1)=>{let r=ms(e,t);return typeof r=="string"?r:r[1]},Tt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Ce.computeStrides(r)})}),t},or=e=>e%4===0?4:e%2===0?2:1,fs=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Ar=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Gr=(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,yt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Pr=(e,t,r,n,o)=>{let i=typeof r=="number",a=i?r:r.length,u=[...new Array(a).keys()],p=a<2?"u32":a<=4?`vec${a}`:`array`,h=ms(t,o),k=typeof h=="string"?h:h[1],d=typeof h=="string"?h:h[0],S={indices:p,value:k,storage:d,tensor:t},L=it=>typeof it=="string"?it:`${it}u`,z={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},D=i?"uniforms.":"",re=`${D}${e}_shape`,te=`${D}${e}_strides`,V="";for(let it=0;it ${S.indices} { var indices: ${S.indices}; var current = offset; ${V} return indices; }`,pe=it=>(z.offsetToIndices=!0,a<2?it:`o2i_${e}(${it})`),be=[];if(a>=2)for(let it=a-1;it>=0;it--)be.push(`${yt(te,it,a)} * (indices[${it}])`);let De=a<2?"":` fn i2o_${e}(indices: ${S.indices}) -> u32 { return ${be.join("+")}; }`,Pe=it=>(z.indicesToOffset=!0,a<2?it:`i2o_${e}(${it})`),Ze=(...it)=>a===0?"0u":`${S.indices}(${it.map(L).join(",")})`,ct=(it,Et)=>a<2?`${it}`:`${yt(it,Et,a)}`,Ct=(it,Et,hr)=>a<2?`${it}=${hr};`:`${yt(it,Et,a)}=${hr};`,Dt={},St=(it,Et)=>{z.broadcastedIndicesToOffset=!0;let hr=`${Et.name}broadcastedIndicesTo${e}Offset`;if(hr in Dt)return`${hr}(${it})`;let vr=[];for(let xr=a-1;xr>=0;xr--){let gn=Et.indicesGet("outputIndices",xr+Et.rank-a);vr.push(`${ct(te,xr)} * (${gn} % ${ct(re,xr)})`)}return Dt[hr]=`fn ${hr}(outputIndices: ${Et.type.indices}) -> u32 { return ${vr.length>0?vr.join("+"):"0u"}; }`,`${hr}(${it})`},bt=(it,Et)=>(()=>{if(S.storage===S.value)return`${e}[${it}]=${Et};`;if(S.storage==="vec2"&&S.value==="i32")return`${e}[${it}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(S.storage==="vec2"&&S.value==="u32")return`${e}[${it}]=vec2(u32(${Et}), 0u);`;if(S.storage==="u32"&&S.value==="vec4")return`${e}[${it}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${S.storage} and value type ${S.value} yet`)})(),Gt=it=>(()=>{if(S.storage===S.value)return`${e}[${it}]`;if(S.storage==="vec2"&&S.value==="i32")return`i32(${e}[${it}].x)`;if(S.storage==="vec2"&&S.value==="u32")return`u32(${e}[${it}].x)`;if(S.storage==="u32"&&S.value==="vec4")return`vec4(bool(${e}[${it}] & 0xFFu), bool(${e}[${it}] & 0xFF00u), bool(${e}[${it}] & 0xFF0000u), bool(${e}[${it}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${S.storage} and value type ${S.value} yet`)})(),jt=a<2?"":` fn get_${e}ByIndices(indices: ${S.indices}) -> ${k} { return ${Gt(`i2o_${e}(indices)`)}; }`,Lt=a<2?"":(()=>{let it=u.map(hr=>`d${hr}: u32`).join(", "),Et=u.map(hr=>`d${hr}`).join(", ");return` fn get_${e}(${it}) -> ${k} { return get_${e}ByIndices(${Ze(Et)}); }`})(),rr=(...it)=>{if(it.length!==a)throw new Error(`indices length must be ${a}`);let Et=it.map(L).join(",");return a===0?Gt("0u"):a===1?Gt(Et[0]):(z.get=!0,z.getByIndices=!0,z.indicesToOffset=!0,`get_${e}(${Et})`)},Yt=it=>a<2?Gt(it):(z.getByIndices=!0,z.indicesToOffset=!0,`get_${e}ByIndices(${it})`),qt=a<2?"":` fn set_${e}ByIndices(indices: ${S.indices}, value: ${k}) { ${bt(`i2o_${e}(indices)`,"value")} }`,Qr=a<2?"":(()=>{let it=u.map(hr=>`d${hr}: u32`).join(", "),Et=u.map(hr=>`d${hr}`).join(", ");return` fn set_${e}(${it}, value: ${k}) { set_${e}ByIndices(${Ze(Et)}, value); }`})();return{impl:()=>{let it=[],Et=!1;return z.offsetToIndices&&(it.push(ie),Et=!0),z.indicesToOffset&&(it.push(De),Et=!0),z.broadcastedIndicesToOffset&&(Object.values(Dt).forEach(hr=>it.push(hr)),Et=!0),z.set&&(it.push(Qr),Et=!0),z.setByIndices&&(it.push(qt),Et=!0),z.get&&(it.push(Lt),Et=!0),z.getByIndices&&(it.push(jt),Et=!0),!i&&Et&&it.unshift(`const ${re} = ${S.indices}(${r.join(",")});`,`const ${te} = ${S.indices}(${Ce.computeStrides(r).join(",")});`),it.join(` `)},type:S,offsetToIndices:pe,indicesToOffset:Pe,broadcastedIndicesToOffset:St,indices:Ze,indicesGet:ct,indicesSet:Ct,set:(...it)=>{if(it.length!==a+1)throw new Error(`indices length must be ${a}`);let Et=it[a];if(typeof Et!="string")throw new Error("value must be string");let hr=it.slice(0,a).map(L).join(",");return a===0?bt("0u",Et):a===1?bt(hr[0],Et):(z.set=!0,z.setByIndices=!0,z.indicesToOffset=!0,`set_${e}(${hr}, ${Et})`)},setByOffset:bt,setByIndices:(it,Et)=>a<2?bt(it,Et):(z.setByIndices=!0,z.indicesToOffset=!0,`set_${e}ByIndices(${it}, ${Et});`),get:rr,getByOffset:Gt,getByIndices:Yt,usage:n,name:e,strides:te,shape:re,rank:a}},Oe=(e,t,r,n=1)=>Pr(e,t,r,"input",n),ft=(e,t,r,n=1)=>Pr(e,t,r,"output",n),ts=(e,t,r)=>Pr(e,t,r,"atomicOutput",1),Hs=(e,t,r,n=1)=>Pr(e,t,r,"internal",n),Zn=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Lr){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=o?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,a=o?`let global_idx = global_id.x; let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) fn main(${i}) { ${a} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let o=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${o}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},wa=(e,t)=>new Zn(e,t)}),ya,Co,ko,ba,Ma,$o,rs,eo,va,Fs=b(()=>{Ft(),zt(),It(),Wt(),ya=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Co=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,ko=(e,t)=>Ce.sortBasedOnPerm(e,Co(e.length,t)),ba=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,o=Co(n,t),i=ko(e.dims,o),a=e.dims,u=i,p=n<2||$o(o,e.dims),h;if(p)return h=z=>{let D=Oe("input",r,a,4),re=ft("output",r,u,4);return` ${z.registerUniform("output_size","u32").declareVariables(D,re)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let z=Ce.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(z/64/4)},programUniforms:[{type:12,data:Math.ceil(z/4)}]}},getShaderSource:h};let{newShape:k,newPerm:d}=Ma(e.dims,o),S=Ce.areEqual(d,[2,3,1]),L=Ce.areEqual(d,[3,1,2]);if(k.length===2||S||L){a=S?[k[0],k[1]*k[2]]:L?[k[0]*k[1],k[2]]:k,u=[a[1],a[0]];let z=16;return h=D=>{let re=Oe("a",r,a.length),te=ft("output",r,u.length);return` ${D.registerUniform("output_size","u32").declareVariables(re,te)} var tile : array, ${z}>; ${D.mainStart([z,z,1])} let stride = (uniforms.output_shape[1] - 1) / ${z} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${z}u + local_id.x; let input_row = workgroup_id_x * ${z}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${re.getByIndices(`${re.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${z}u + local_id.x; let output_row = workgroup_id_y * ${z}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${te.setByIndices(`${te.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let D=Ce.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/z),y:Math.ceil(u[0]/z)},programUniforms:[{type:12,data:D},...Tt(a,u)]}},getShaderSource:h}}return h=z=>{let D=Oe("a",r,a.length),re=ft("output",r,u.length);return` ${z.registerUniform("output_size","u32").declareVariables(D,re)} ${ba(o,n,D,re)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${re.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${re.setByOffset("global_idx",D.getByIndices("aIndices"))} }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let z=Ce.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:[{type:12,data:z},...Tt(a,u)]}},getShaderSource:h}},eo=(e,t)=>{ya(e.inputs),e.compute(rs(e.inputs[0],t.perm))},va=e=>qe({perm:e.perm})}),xa,Ta,Ea,Pa,Ca,So,qs,ka,Ku,$a,_s,Sa,Ao,Aa,Ia,Oa,Fa,Da,to,La,za,Hu=b(()=>{Ft(),zt(),Wt(),Bo(),Fs(),xa={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"},Ta={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"},Ea={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Pa={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ca=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},qs=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!ka(e,t)){for(let n=0;nr.push(n))}return r},$a=(e,t,r,n,o,i,a)=>{let u=r[0].dims,p=Ce.size(i),h=Ce.size(a),k=Oe("_A",r[0].dataType,u),d=ft("output",o,i),S=64;p===1&&(S=256);let L=` var aBestValues : array; `,z=D=>` ${D.registerUniform("reduceSize","u32").declareVariables(k,d)} ${L} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${D.mainStart(S)} let outputIndex = global_idx / ${S}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${Ea[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${S}) { let candidate = f32(${k.getByOffset("offset + k")}); bestValue = ${xa[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${S}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Ta[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${d.setByOffset("outputIndex",`${n==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${Pa[n]})`}`)}; } }`;return{name:e,shaderCache:{hint:`${t};${S}`,inputDependencies:["type"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},_s=(e,t,r,n)=>{let o=e.inputs.length===1?r:so(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((L,z)=>z));let a=Ce.normalizeAxes(i,e.inputs[0].dims.length),u=a,p=e.inputs[0],h=Ku(u,e.inputs[0].dims.length);h.length>0&&(p=e.compute(rs(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=Ca(u.length,p.dims.length));let[k,d]=So(p.dims,u),S=k;o.keepDims&&(S=qs(k,a)),e.compute($a(t,o.cacheKey,[p],n,e.inputs[0].dataType,S,d),{inputs:[p]})},Sa=(e,t)=>{_s(e,"ReduceMeanShared",t,"mean")},Ao=(e,t)=>{_s(e,"ReduceL1Shared",t,"l1")},Aa=(e,t)=>{_s(e,"ReduceL2Shared",t,"l2")},Ia=(e,t)=>{_s(e,"ReduceLogSumExpShared",t,"logSumExp")},Oa=(e,t)=>{_s(e,"ReduceMaxShared",t,"max")},Fa=(e,t)=>{_s(e,"ReduceMinShared",t,"min")},Da=(e,t)=>{_s(e,"ReduceProdShared",t,"prod")},to=(e,t)=>{_s(e,"ReduceSumShared",t,"sum")},La=(e,t)=>{_s(e,"ReduceSumSquareShared",t,"sumSquare")},za=(e,t)=>{_s(e,"ReduceLogSumShared",t,"logSum")}}),is,Ba,ro,so,us,Ra,Io,Na,ja,Oo,Ua,Wa,Fo,Va,Ga,as,Ka,Ha,Do,qa,Xa,Lo,Qa,Ya,zo,Ja,Bo=b(()=>{Ft(),zt(),It(),Wt(),Hu(),is=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.")},Ba=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ro=(e,t,r,n,o,i,a=!1,u=!1)=>{let p=[],h=r[0].dims,k=h.length,d=Ce.normalizeAxes(o,k),S=!u&&d.length===0;h.forEach((D,re)=>{S||d.indexOf(re)>=0?a&&p.push(1):p.push(D)});let L=p.length,z=Ce.size(p);return{name:e,shaderCache:t,getShaderSource:D=>{let re=[],te=Oe("_A",r[0].dataType,k),V=ft("output",i,L),ie=n(te,V,d),pe=ie[2];for(let be=0,De=0;be=0?(a&&De++,pe=`for(var j${be}: u32 = 0; j${be} < ${h[be]}; j${be}++) { ${ie[2].includes("last_index")?`let last_index = j${be};`:""} ${te.indicesSet("input_indices",be,`j${be}`)} ${pe} }`):(re.push(`${te.indicesSet("input_indices",be,V.indicesGet("output_indices",De))};`),De++);return` ${D.registerUniform("output_size","u32").declareVariables(te,V)} ${D.mainStart()} ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${te.type.indices}; let output_indices = ${V.offsetToIndices("global_idx")}; ${re.join(` `)} ${ie[0]} // init ops for reduce max/min ${ie[1]} ${pe} ${ie[3]} ${ie.length===4?V.setByOffset("global_idx","value"):ie.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:[{type:12,data:z},...Tt(h,p)]})}},so=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),qe({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},us=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:so(o,r);e.compute(ro(t,{hint:i.cacheKey,inputDependencies:["rank"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?Ba:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},Ra=(e,t)=>{is(e.inputs),us(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Io=(e,t)=>{is(e.inputs),us(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Na=(e,t)=>{is(e.inputs),us(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},ja=(e,t)=>{is(e.inputs),us(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Oo=(e,t)=>{is(e.inputs),us(e,"ReduceMax",t,(r,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(r.indicesSet("input_indices",a,0));return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},Ua=(e,t)=>{is(e.inputs),us(e,"ReduceMean",t,(r,n,o)=>{let i=1;for(let a=0;a=0||o.length===0)&&(i*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${i});`]})},Wa=(e,t)=>{is(e.inputs),us(e,"ReduceMin",t,(r,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},Fo=(e,t)=>{is(e.inputs),us(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Va=(e,t)=>{is(e.inputs),us(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Ga=(e,t)=>{is(e.inputs),us(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},as=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},Ka=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ua(e,t):Sa(e,t)},Ha=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Io(e,t):Ao(e,t)},Do=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Na(e,t):Aa(e,t)},qa=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ja(e,t):Ia(e,t)},Xa=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Oo(e,t):Oa(e,t)},Lo=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wa(e,t):Fa(e,t)},Qa=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):Da(e,t)},Ya=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Va(e,t):to(e,t)},zo=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ga(e,t):La(e,t)},Ja=(e,t)=>{as(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ra(e,t):za(e,t)}}),no,Za,el,oo,qu=b(()=>{Ft(),It(),Bo(),no=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.")},Za=(e,t)=>{no(e.inputs);let r=(n,o,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",o.setByOffset("global_idx","best_index")]};e.compute(ro("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},el=(e,t)=>{no(e.inputs);let r=(n,o,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",o.setByOffset("global_idx","best_index")]};e.compute(ro("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},oo=e=>qe(e)}),tl,An,rl,sl,Ro,In,nl,No,jo=b(()=>{Ft(),zt(),Ks(),Wt(),tl=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],u=e[5];if(a&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=r.dims[0],h=r.dims[1],k=r.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=o.dims[0]/3,S=d,L=S;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ie of t.qkvHiddenSizes)if(ie%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=t.qkvHiddenSizes[0],S=t.qkvHiddenSizes[1],L=t.qkvHiddenSizes[2]}let z=h;if(d!==S)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+S+L)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let D=0;if(a){if(S!==L)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==S/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(D=a.dims[3])}let re=z+D,te=-1,V=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==h||u.dims[3]!==re)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:D,kvSequenceLength:z,totalSequenceLength:re,maxSequenceLength:te,inputHiddenSize:k,hiddenSize:d,vHiddenSize:L,headSize:Math.floor(d/t.numHeads),vHeadSize:Math.floor(L/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:V,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},An=(e,t,r)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } `:` ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; `,rl=(e,t,r,n,o,i,a,u)=>{let p=or(a?1:i),h=64,k=i/p;k{let V=ft("x",e.dataType,e.dims,p),ie=[V],pe=a?Oe("seq_lens",a.dataType,a.dims):void 0;pe&&ie.push(pe);let be=u?Oe("total_sequence_length_input",u.dataType,u.dims):void 0;be&&ie.push(be);let De=dr(e.dataType),Pe=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${te.registerUniforms(Pe).declareVariables(...ie)} ${te.mainStart([h,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${An(pe,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 = ${z}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${z}(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 = ${z}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${z}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${h}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${V.type.value}(${De}(1.0) / ${De}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${z}(x[offset + i]); x[offset + i] = ${V.type.value}(exp(f32input - max_value) / sum); } } ${a?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${V.type.value}(${De}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${L};${p}`,inputDependencies:D},getShaderSource:re,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/h),y:o,z:t*r},programUniforms:S})}},sl=(e,t,r,n,o,i,a,u,p)=>{let h=a+i.kvSequenceLength,k=[i.batchSize,i.numHeads,i.sequenceLength,h],d=e>1&&n,S=i.kvNumHeads?i.kvNumHeads:i.numHeads,L=d?[i.batchSize,S,h,i.headSize]:void 0,z=i.nReps?i.nReps:1,D=i.scale===0?1/Math.sqrt(i.headSize):i.scale,re=or(i.headSize),te=i.headSize/re,V=12,ie={x:Math.ceil(h/V),y:Math.ceil(i.sequenceLength/V),z:i.batchSize*i.numHeads},pe=[{type:12,data:i.sequenceLength},{type:12,data:te},{type:12,data:h},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:D},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:z}],be=d&&n&&Ce.size(n.dims)>0,De=["type","type"];be&&De.push("type"),o&&De.push("type"),u&&De.push("type"),p&&De.push("type");let Pe=[{dims:k,dataType:t.dataType,gpuDataType:0}];d&&Pe.push({dims:L,dataType:t.dataType,gpuDataType:0});let Ze=ct=>{let Ct=Oe("q",t.dataType,t.dims,re),Dt=Oe("key",r.dataType,r.dims,re),St=[Ct,Dt];if(be){let qt=Oe("past_key",n.dataType,n.dims,re);St.push(qt)}o&&St.push(Oe("attention_bias",o.dataType,o.dims));let bt=u?Oe("seq_lens",u.dataType,u.dims):void 0;bt&&St.push(bt);let Gt=p?Oe("total_sequence_length_input",p.dataType,p.dims):void 0;Gt&&St.push(Gt);let jt=ft("output",t.dataType,k),Lt=[jt];d&&Lt.push(ft("present_key",t.dataType,L,re));let rr=dr(1,re),Yt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${V}u; var tileQ: array<${Ct.type.storage}, ${V*V}>; var tileK: array<${Ct.type.storage}, ${V*V}>; ${ct.registerUniforms(Yt).declareVariables(...St,...Lt)} ${ct.mainStart([V,V,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${z===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${z===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; ${An(bt,Gt,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${be&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${rr}(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&&d?` 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]; }`} ${d?`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 += ${rr}(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(re){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: ${re}`)}})()}; output[outputIdx] = ${jt.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${re};${o!==void 0};${n!==void 0};${e}`,inputDependencies:De},getRunData:()=>({outputs:Pe,dispatchGroup:ie,programUniforms:pe}),getShaderSource:Ze}},Ro=(e,t,r,n,o,i,a=void 0,u=void 0)=>{let p=i+o.kvSequenceLength,h=o.nReps?o.nReps:1,k=o.vHiddenSize*h,d=e>1&&n,S=o.kvNumHeads?o.kvNumHeads:o.numHeads,L=d?[o.batchSize,S,p,o.headSize]:void 0,z=[o.batchSize,o.sequenceLength,k],D=12,re={x:Math.ceil(o.vHeadSize/D),y:Math.ceil(o.sequenceLength/D),z:o.batchSize*o.numHeads},te=[{type:12,data:o.sequenceLength},{type:12,data:p},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:k},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:h}],V=d&&n&&Ce.size(n.dims)>0,ie=["type","type"];V&&ie.push("type"),a&&ie.push("type"),u&&ie.push("type");let pe=[{dims:z,dataType:t.dataType,gpuDataType:0}];d&&pe.push({dims:L,dataType:t.dataType,gpuDataType:0});let be=De=>{let Pe=Oe("probs",t.dataType,t.dims),Ze=Oe("v",r.dataType,r.dims),ct=[Pe,Ze];V&&ct.push(Oe("past_value",n.dataType,n.dims));let Ct=a?Oe("seq_lens",a.dataType,a.dims):void 0;a&&ct.push(Ct);let Dt=u?Oe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&ct.push(Dt);let St=[ft("output",t.dataType,z)];d&&St.push(ft("present_value",t.dataType,L));let bt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${D}u; var tileQ: array<${Pe.type.value}, ${D*D}>; var tileV: array<${Pe.type.value}, ${D*D}>; ${De.registerUniforms(bt).declareVariables(...ct,...St)} ${De.mainStart([D,D,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; ${An(Ct,Dt,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${V&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${Pe.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${V&&d?` 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]; }`} ${d?` 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:ie},getRunData:()=>({outputs:pe,dispatchGroup:re,programUniforms:te}),getShaderSource:be}},In=(e,t,r,n,o,i,a,u,p,h,k=void 0,d=void 0)=>{let S=Math.min(e.outputCount,1+(a?1:0)+(u?1:0)),L=S>1?h.pastSequenceLength:0,z=L+h.kvSequenceLength,D=p&&Ce.size(p.dims)>0?p:void 0,re=[t,r];S>1&&a&&Ce.size(a.dims)>0&&re.push(a),D&&re.push(D),k&&re.push(k),d&&re.push(d);let te=e.compute(sl(S,t,r,a,D,h,L,k,d),{inputs:re,outputs:S>1?[-1,1]:[-1]})[0];e.compute(rl(te,h.batchSize,h.numHeads,L,h.sequenceLength,z,k,d),{inputs:k&&d?[te,k,d]:[te],outputs:[]});let V=[te,n];S>1&&u&&Ce.size(u.dims)>0&&V.push(u),k&&V.push(k),d&&V.push(d),e.compute(Ro(S,te,n,u,h,L,k,d),{inputs:V,outputs:S>1?[0,2]:[0]})},nl=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,u={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],k=d=>{let S=ft("output_q",p[0].dataType,r),L=ft("output_k",p[0].dataType,r),z=ft("output_v",p[0].dataType,r),D=Oe("input",p[0].dataType,p[0].dims),re=Oe("weight",p[1].dataType,p[1].dims),te=Oe("bias",p[2].dataType,p[2].dims),V=D.type.storage,ie=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${a}u; var tileInput: array<${V}, ${a*a}>; var tileWeightQ: array<${V}, ${a*a}>; var tileWeightK: array<${V}, ${a*a}>; var tileWeightV: array<${V}, ${a*a}>; ${d.registerUniforms(ie).declareVariables(D,re,te,S,L,z)} ${d.mainStart([a,a,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${V}(0); var valueK = ${V}(0); var valueV = ${V}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},No=(e,t)=>{let r=tl(e.inputs,t),[n,o,i]=nl(e,r);return In(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),ol,Uo,il,al,ll=b(()=>{Ge(),Ft(),zt(),It(),Wt(),ol=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((u,p)=>{if(u!==n[p])throw new Error(`${i}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Uo=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?or(i[i.length-1]):1,u=o==="NHWC"&&i.length>1?a:1,p=Ce.size(i)/a,h=n,k=h?i.length:i,d=Oe("x",e[0].dataType,e[0].dims,a),S=Oe("scale",e[1].dataType,e[1].dims,u),L=Oe("bias",e[2].dataType,e[2].dims,u),z=Oe("inputMean",e[3].dataType,e[3].dims,u),D=Oe("inputVar",e[4].dataType,e[4].dims,u),re=ft("y",e[0].dataType,k,a),te=()=>{let ie="";if(n)ie=`let cOffset = ${i.length===1?"0u":o==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(o==="NCHW")ie=` ${re.indicesSet("outputIndices","0","0")} let cOffset = ${re.indicesToOffset("outputIndices")};`;else{ie=`var cIndices = ${S.type.indices}(0); cIndices[0] = outputIndices[${i.length-1}];`;for(let pe=1;pe` const epsilon = ${r}; ${ie.registerUniform("outputSize","u32").declareVariables(d,S,L,z,D,re)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${re.offsetToIndices(`global_idx * ${a}`)}; ${te()} let scale = ${S.getByOffset("cOffset")}; let bias = ${L.getByOffset("cOffset")}; let inputMean = ${z.getByOffset("cOffset")}; let inputVar = ${D.getByOffset("cOffset")}; let x = ${d.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${re.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Tt(i)]:[{type:12,data:p}]})}},il=e=>qe(e),al=(e,t)=>{let{inputs:r,outputCount:n}=e,o=il({...t,outputCount:n});if(E.webgpu.validateInputContent&&ol(r,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Uo(r,o))}}),dl,ul,Wo,Xu=b(()=>{zt(),Wt(),dl=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")},ul=e=>{let t=e[0].dims,r=e[0].dims[2],n=Ce.size(t)/4,o=e[0].dataType,i=Oe("input",o,t,4),a=Oe("bias",o,[r],4),u=Oe("residual",o,t,4),p=ft("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` const channels = ${r}u / 4; ${h.declareVariables(i,a,u,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${i.getByOffset("global_idx")} + ${a.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; ${p.setByOffset("global_idx","value")} }`}},Wo=e=>{dl(e.inputs),e.compute(ul(e.inputs))}}),cl,ir,pl,hl,ml,fl,Vo,_l,gl,Go,wl,yl,Ko,bl,Ml,Ho,On,vl,Fn,xl,Tl,qo,El,Pl,Xo,Cl,kl,$l,Sl,Qo,Al,Il,Ol,Fl,Yo,Jo,Dl,Zo,ei,ti,Ll,zl,Bl,Rl,ri,si=b(()=>{Ft(),zt(),It(),Wt(),cl=(e,t,r,n,o,i,a)=>{let u=Math.ceil(t/4),p="";typeof o=="string"?p=`${o}(a)`:p=o("a");let h=Oe("inputData",r,[u],4),k=ft("outputData",n,[u],4),d=[{name:"vec_size",type:"u32"}];return a&&d.push(...a),` ${e.registerUniforms(d).declareVariables(h,k)} ${i??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${k.setByOffset("global_idx",p)} }`},ir=(e,t,r,n,o,i=e.dataType,a,u)=>{let p=[{type:12,data:Math.ceil(Ce.size(e.dims)/4)}];return a&&p.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:h=>cl(h,Ce.size(e.dims),e.dataType,i,r,n,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(Ce.size(h[0].dims)/64/4)},programUniforms:p})}},pl=e=>{e.compute(ir(e.inputs[0],"Abs","abs"))},hl=e=>{e.compute(ir(e.inputs[0],"Acos","acos"))},ml=e=>{e.compute(ir(e.inputs[0],"Acosh","acosh"))},fl=e=>{e.compute(ir(e.inputs[0],"Asin","asin"))},Vo=e=>{e.compute(ir(e.inputs[0],"Asinh","asinh"))},_l=e=>{e.compute(ir(e.inputs[0],"Atan","atan"))},gl=e=>{e.compute(ir(e.inputs[0],"Atanh","atanh"))},Go=e=>qe(e),wl=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ir(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},yl=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return qe({min:t,max:r})},Ko=(e,t)=>{let r=t||yl(e.inputs),n=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},bl=e=>{e.compute(ir(e.inputs[0],"Ceil","ceil"))},Ml=e=>{e.compute(ir(e.inputs[0],"Cos","cos"))},Ho=e=>{e.compute(ir(e.inputs[0],"Cosh","cosh"))},On=e=>qe(e),vl=(e,t)=>{let r=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},Fn=(e="f32")=>` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; const r3: ${e} = 1.421413741; const r4: ${e} = -1.453152027; const r5: ${e} = 1.061405429; fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,xl=e=>{let t=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Fn(t)))},Tl=e=>{e.compute(ir(e.inputs[0],"Exp","exp"))},qo=e=>{e.compute(ir(e.inputs[0],"Floor","floor"))},El=e=>{let t=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Fn(t)))},Pl=(e,t)=>{let r=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Xo=e=>{e.compute(ir(e.inputs[0],"Not",t=>`!${t}`))},Cl=e=>{e.compute(ir(e.inputs[0],"Neg",t=>`-${t}`))},kl=e=>{e.compute(ir(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},$l=e=>{let t=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Sl=e=>{e.compute(ir(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Qo=e=>qe(e),Al=(e,t)=>{let r=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Il=e=>{e.compute(ir(e.inputs[0],"Sin","sin"))},Ol=e=>{e.compute(ir(e.inputs[0],"Sinh","sinh"))},Fl=e=>{e.compute(ir(e.inputs[0],"Sqrt","sqrt"))},Yo=e=>{e.compute(ir(e.inputs[0],"Tan","tan"))},Jo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Dl=e=>{e.compute(ir(e.inputs[0],"Tanh",Jo))},Zo=(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 ${Jo("v")}; } `,ei=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,ti=e=>{let t=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"FastGelu",ei,Zo(t),void 0,e.inputs[0].dataType))},Ll=(e,t)=>{let r=dr(e.inputs[0].dataType);return e.compute(ir(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},zl=e=>{e.compute(ir(e.inputs[0],"Log","log"))},Bl=(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})`,ri=(e,t)=>{let r=dr(e.inputs[0].dataType);e.compute(ir(e.inputs[0],"QuickGelu",Rl,Bl(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Nl,ni,jl,Qu=b(()=>{zt(),Wt(),si(),Nl=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")},ni=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Oe("input",e[0].dataType,e[0].dims,4),n=Oe("bias",e[0].dataType,[e[0].dims[2]],4),o=ft("output",e[0].dataType,t,4),i=Ce.size(t)/4,a=Zt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:u=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${u.declareVariables(r,n,o)} ${Fn(a)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes(i)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${o.setByOffset("global_idx","valueLeft * geluRight")} }`}},jl=e=>{Nl(e.inputs),e.compute(ni(e.inputs))}}),oi,Ul,cs,ii,Wl,Vl,ai,Gl,Kl,io,Hl,ql,li,Xl=b(()=>{Ft(),zt(),Wt(),oi=(e,t,r,n,o,i,a,u,p,h,k,d)=>{let S,L;typeof u=="string"?S=L=(V,ie)=>`${u}((${V}),(${ie}))`:typeof u=="function"?S=L=u:(S=u.scalar,L=u.vector);let z=ft("outputData",k,n.length,4),D=Oe("aData",p,t.length,4),re=Oe("bData",h,r.length,4),te;if(o)if(i){let V=Ce.size(t)===1,ie=Ce.size(r)===1,pe=t.length>0&&t[t.length-1]%4===0,be=r.length>0&&r[r.length-1]%4===0;V||ie?te=z.setByOffset("global_idx",L(V?`${D.type.value}(${D.getByOffset("0")}.x)`:D.getByOffset("global_idx"),ie?`${re.type.value}(${re.getByOffset("0")}.x)`:re.getByOffset("global_idx"))):te=` let outputIndices = ${z.offsetToIndices("global_idx * 4u")}; let offsetA = ${D.broadcastedIndicesToOffset("outputIndices",z)}; let offsetB = ${re.broadcastedIndicesToOffset("outputIndices",z)}; ${z.setByOffset("global_idx",L(a||pe?D.getByOffset("offsetA / 4u"):`${D.type.value}(${D.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||be?re.getByOffset("offsetB / 4u"):`${re.type.value}(${re.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else te=z.setByOffset("global_idx",L(D.getByOffset("global_idx"),re.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let V=(ie,pe,be="")=>{let De=`aData[indexA${pe}][componentA${pe}]`,Pe=`bData[indexB${pe}][componentB${pe}]`;return` let outputIndices${pe} = ${z.offsetToIndices(`global_idx * 4u + ${pe}u`)}; let offsetA${pe} = ${D.broadcastedIndicesToOffset(`outputIndices${pe}`,z)}; let offsetB${pe} = ${re.broadcastedIndicesToOffset(`outputIndices${pe}`,z)}; let indexA${pe} = offsetA${pe} / 4u; let indexB${pe} = offsetB${pe} / 4u; let componentA${pe} = offsetA${pe} % 4u; let componentB${pe} = offsetB${pe} % 4u; ${ie}[${pe}] = ${be}(${S(De,Pe)}); `};k===9?te=` var data = vec4(0); ${V("data",0,"u32")} ${V("data",1,"u32")} ${V("data",2,"u32")} ${V("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:te=` ${V("outputData[global_idx]",0)} ${V("outputData[global_idx]",1)} ${V("outputData[global_idx]",2)} ${V("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(D,re,z)} ${d??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${te} }`},Ul=(e,t,r,n,o,i,a=r.dataType)=>{let u=r.dims.map(D=>Number(D)??1),p=n.dims.map(D=>Number(D)??1),h=!Ce.areEqual(u,p),k=u,d=Ce.size(u),S=!1,L=!1,z=[h];if(h){let D=gr.calcShape(u,p,!1);if(!D)throw new Error("Can't perform binary op on the given tensors");k=D.slice(),d=Ce.size(k);let re=Ce.size(u)===1,te=Ce.size(p)===1,V=u.length>0&&u[u.length-1]%4===0,ie=p.length>0&&p[p.length-1]%4===0;z.push(re),z.push(te),z.push(V),z.push(ie);let pe=1;for(let be=1;beD.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:D=>oi(D,u,p,k,S,h,L,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:k,dataType:a}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(Ce.size(k)/4)},...Tt(u,p,k)]})}},cs=(e,t,r,n,o,i)=>{e.compute(Ul(t,o??"",e.inputs[0],e.inputs[1],r,n,i))},ii=e=>{cs(e,"Add",(t,r)=>`${t}+${r}`)},Wl=e=>{cs(e,"Div",(t,r)=>`${t}/${r}`)},Vl=e=>{cs(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},ai=e=>{cs(e,"Mul",(t,r)=>`${t}*${r}`)},Gl=e=>{let t=Oe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;cs(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Kl=e=>{cs(e,"Sub",(t,r)=>`${t}-${r}`)},io=e=>{cs(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Hl=e=>{cs(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},ql=e=>{cs(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},li=e=>{cs(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Ql,di,Yl,Jl,Zl,ui,Yu=b(()=>{Ft(),zt(),It(),Wt(),Ql=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,u)=>{if(u!==r){if(a.dataType!==o)throw new Error("input tensors should be one type");if(a.dims.length!==i)throw new Error("input tensors should have the same shape");a.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},di=(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; }`,Yl=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=Ce.size(r),i=new Array(e.length),a=new Array(e.length),u=0,p=[],h=[],k=[{type:12,data:o}];for(let D=0;D`uniforms.sizeInConcatAxis${D}`).join(","),z=D=>` ${(()=>{D.registerUniform("outputSize","u32");for(let re=0;re(${L}); ${S} -= sizeInConcatAxis[inputIndex - 1u]; } ${Yl(a,d)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:k}),getShaderSource:z}},Zl=(e,t)=>{let r=e.inputs,n=r[0].dims,o=Ce.normalizeAxis(t.axis,n.length);Ql(r,o);let i=n.slice();i[o]=r.reduce((u,p)=>u+(p.dims.length>o?p.dims[o]:0),0);let a=r.filter(u=>Ce.size(u.dims)>0);e.compute(Jl(a,o,i,r[0].dataType),{inputs:a})},ui=e=>qe({axis:e.axis})}),Xs,Qs,Ds,ci,Ys=b(()=>{Ft(),zt(),Xs=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Qs=(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})},Ds=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},ci=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=e?.activation_params||[Rr,ds];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}}),Ur,ed,pi=b(()=>{Ur=(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.`)}},ed=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),hi,Ju=b(()=>{hi=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)); } `}),Dn,ao,mi=b(()=>{Ft(),zt(),Wt(),Ys(),Dn=(e,t,r,n,o)=>{let i=n-r;return` ${Array.from({length:r}).map((a,u)=>` if (${yt(t.shape,u,t.rank)} != 1) { ${t.indicesSet(e,u,yt(o,u+i,n))} } else { ${t.indicesSet(e,u,0)} }`).join("")} `},ao=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,u=e[1].dims,p=a[a.length-2],h=u[u.length-1],k=a[a.length-1],d=or(h),S=or(k),L=or(p),z=Ce.size(r)/d/L,D=e.length>2,re=n?n.slice(0,-2):r.slice(0,-2),te=[Ce.size(re),p,h],V=[{type:12,data:z},{type:12,data:p},{type:12,data:h},{type:12,data:k}];Qs(t,V),V.push(...Tt(re,a,u)),D&&V.push(...Tt(e[2].dims)),V.push(...Tt(te));let ie=pe=>{let be=Hs("batch_dims",e[0].dataType,re.length),De=Oe("a",e[0].dataType,a.length,S),Pe=Oe("b",e[1].dataType,u.length,d),Ze=ft("output",e[0].dataType,te.length,d),ct=Zt(Ze.type.tensor),Ct=Xs(t,Ze.type.value,ct),Dt=[De,Pe],St="";if(D){let jt=o?d:1;Dt.push(Oe("bias",e[2].dataType,e[2].dims.length,jt)),St=`${o?`value += bias[col / ${jt}];`:`value += ${Ze.type.value}(bias[row + i]);`}`}let bt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ds(t,bt);let Gt=()=>{let jt=`var a_data: ${De.type.value};`;for(let Lt=0;Lt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${S}) { ${Gt()} } for (var i = 0u; i < ${L}u; i++) { var value = values[i]; ${St} ${Ct} let cur_indices = ${Ze.type.indices}(batch, row + i, col); let offset = ${Ze.indicesToOffset("cur_indices")}; ${Ze.setByOffset(`offset / ${d}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${d};${S};${L};${o}`,inputDependencies:D?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:V}),getShaderSource:ie}}}),td,fi,_i,gi,wi,yi,rd,lo,bi=b(()=>{Ft(),zt(),Wt(),Ys(),mi(),pi(),td=(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":""}); `,fi=(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];"} }`,_i=(e,t,r="f32",n,o=!1,i=32,a=!1,u=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=o?p:i,d=o?i:p,S=k/t[0],L=i/t[1];if(!((o&&S===4&&e[1]===4||!o&&(S===3||S===4))&&k%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${S} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${S} must be 3 or 4. tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${k/S}>, ${d}>; var mm_Bsub: array, ${h/e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${S}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${a?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${p}; let num_tiles = ${a?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${L}; 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; ${td(o,n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${L}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${S===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${fi(o,S)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},gi=(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":""}); `,wi=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",yi=(e,t,r="f32",n,o=!1,i=32,a=!1,u=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],d=o?h:i,S=o?i:h;if(!(S%t[1]===0&&d%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${S} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let L=S/t[1],z=d/t[0],D=i/t[1],re=p?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${k}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${S}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) { ${gi(o,n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${h}; let tileRowA = i32(localId.y) * ${L}; let tileColA = i32(localId.x) * ${z}; let tileRowB = i32(localId.y) * ${D}; // 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 < ${L}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${z}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${gi(o,n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${D}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${wi(o)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${S}>; var mm_Bsub : array, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${a?"0":"i32(globalId.z)"}; ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${a?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; var acc : array, rowPerThread>; ${re} } `},rd=(e,t,r,n,o=!1)=>{let[i,a,u,p]=n,h=Zt(n[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ur(e,h)} { var value = ${Ur(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${a.type.indices}; ${Dn("aIndices",a,a.rank-2,i.rank,"batchIndices")} ${a.indicesSet("aIndices",a.rank-2,"u32(row)")} ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")} value = ${a.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ur(e,h)} { var value = ${Ur(e,h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${u.type.indices}; ${Dn("bIndices",u,u.rank-2,i.rank,"batchIndices")} ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} value = ${u.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ur(e,h)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${o?"bias[colIn]":`${Ur(e,h)}(bias[row])`};`:""} ${r} ${p.setByIndices("vec3(coords)","value")} } } `},lo=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,u=e[1].dims,p=a.slice(0,-2),h=u.slice(0,-2),k=n?n.slice(0,-2):r.slice(0,-2),d=Ce.size(k),S=a[a.length-2],L=a[a.length-1],z=u[u.length-1],D=L%4===0&&z%4===0,re=S<=8?[4,1,1]:[4,4,1],te=[8,8,1],V=[Math.ceil(z/te[0]/re[0]),Math.ceil(S/te[1]/re[1]),Math.ceil(d/te[2]/re[2])],ie=D?4:1,pe=[...p,S,L/ie],be=pe.length,De=[...h,L,z/ie],Pe=De.length,Ze=[d,S,z/ie],ct=[{type:6,data:S},{type:6,data:z},{type:6,data:L}];Qs(t,ct),ct.push(...Tt(k,pe,De));let Ct=["rank","rank"],Dt=e.length>2;Dt&&(ct.push(...Tt(e[2].dims)),Ct.push("rank")),ct.push(...Tt(Ze));let St=bt=>{let Gt=k.length,jt=Hs("batchDims",e[0].dataType,Gt,1),Lt=Zt(e[0].dataType),rr=Oe("a",e[0].dataType,be,ie),Yt=Oe("b",e[1].dataType,Pe,ie),qt=ft("result",e[0].dataType,Ze.length,ie),Qr=[rr,Yt];if(Dt){let xr=o?ie:1;Qr.push(Oe("bias",e[2].dataType,e[2].dims.length,xr))}let it=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ds(t,it);let Et=Zt(qt.type.tensor),hr=Xs(t,qt.type.value,Et),vr=rd(ie,Dt,hr,[jt,rr,Yt,qt],o);return` ${bt.registerUniforms(it).registerInternalVariables(jt).declareVariables(...Qr,qt)} ${vr} ${D?_i(re,te,Lt,jt):yi(re,te,Lt,jt)} `};return{name:"MatMul",shaderCache:{hint:`${re};${t.activation};${D};${o}`,inputDependencies:Ct},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:V[0],y:V[1],z:V[2]},programUniforms:ct}),getShaderSource:St}}}),uo,sd,Zu=b(()=>{Ft(),es(),Wt(),Ys(),pi(),Ju(),bi(),uo=(e,t,r,n,o=!1,i,a=4,u=4,p=4,h="f32")=>{let k=ct=>{switch(ct){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 ${ct} is not supported.`)}},d=ct=>{switch(ct){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 ${ct} is not supported.`)}},S=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,L=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,z=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",D=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",re=e?"row":"col",te=e?"col":"row",V=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${re} / outWidth; let outCol = ${re} % outWidth; let WRow = ${te} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${te} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${te} % inChannels; var resData = ${Ur(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 < ${z} && xCol >= 0 && xCol < ${D}) { ${S} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${k(a)} } return resData;`,ie=e?t&&n?` let col = colIn * ${a}; ${V}`:` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${V} } return ${Ur(a,h)}(0.0);`:n&&r?` let col = colIn * ${a}; ${V}`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${V} } return ${Ur(a,h)}(0.0);`,pe=`${d(u)}`,be=Ur(p,h),De=Ur(e?a:u,h),Pe=Ur(e?u:a,h),Ze=Xs(i,be,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${De} { ${e?ie:pe} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Pe} { ${e?pe:ie} } 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])"}; ${L} ${ed(o)} ${Ze} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},sd=(e,t,r,n,o,i,a,u,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],d=r[0],S=h?r[2]:r[3],L=h?r[1]:r[2],z=h?r[3]:r[1],D=h&&(k%4===0||k%3===0)&&z%4===0,re=h?z:S*L,te=h?S*L:z,V=[8,8,1],ie=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(re/V[0]/ie[0]),Math.ceil(te/V[1]/ie[1]),Math.ceil(d/V[2]/ie[2])];nr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${pe}`);let be=D?h&&k%4!==0?3:4:1,De=V[1]*ie[1],Pe=V[0]*ie[0],Ze=Math.max(V[0]*be,V[1]),ct=n%De===0,Ct=o%Pe===0,Dt=i%Ze===0,St=D?[be,4,4]:[1,1,1],bt=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Qs(t,bt),bt.push(...Tt(e[0].dims,e[1].dims));let Gt=["rank","rank"];a&&(bt.push(...Tt(e[2].dims)),Gt.push("rank")),bt.push(...Tt(r));let jt=Lt=>{let rr=[{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}];Ds(t,rr);let Yt=D?4:1,qt=Zt(e[0].dataType),Qr=` fn setOutputAtIndex(flatIndex : i32, value : ${D?`vec4<${qt}>`:qt}) { result[flatIndex] = ${D?`vec4<${qt}>`:qt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${D?`vec4<${qt}>`:qt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${D?"/ 4":""}, value); }`,it=Oe("x",e[0].dataType,e[0].dims.length,be===3?1:be),Et=Oe("w",e[1].dataType,e[1].dims.length,Yt),hr=[it,Et],vr=ft("result",e[0].dataType,r.length,Yt);if(a){let xr=Oe("bias",e[2].dataType,e[2].dims.length,Yt);hr.push(xr),Qr+=` fn getBiasByOutputCoords(coords : vec4) -> ${D?`vec4<${qt}>`:qt} { return bias[coords.${h?"w":"y"}${D?"/ 4":""}]; }`}return` ${hi("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${Lt.registerUniforms(rr).declareVariables(...hr,vr)} ${Qr} ${uo(h,ct,Ct,Dt,a,t,St[0],St[1],St[2],qt)} ${D?_i(ie,V,qt,void 0,!h,Ze):yi(ie,V,qt,void 0,!h,Ze,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${be};${D};${ct};${Ct};${Dt};${De};${Pe};${Ze}`,inputDependencies:Gt},getRunData:()=>({outputs:[{dims:p?p(r):r,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:bt}),getShaderSource:jt}}}),nd,Mi,Ln,vi,xi,od,Ti,id,ec=b(()=>{Ft(),es(),zt(),Wt(),Ys(),pi(),nd=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Ln=(e,t)=>t<=1?e:e+(e-1)*(t-1),vi=(e,t,r,n=1)=>{let o=Ln(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},xi=(e,t,r,n,o)=>{o==null&&(o=vi(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},od=(e,t,r,n,o,i,a,u,p,h)=>{let k,d,S,L;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let z=xi([t,r,n,1],[u,p,h],1,[o,i,a],e);d=z[0],S=z[1],L=z[2]}else if(Array.isArray(e)){if(!e.every((D,re,te)=>D===te[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let z=xi([t,r,n,1],[u,p,h],1,[o,i,a],e[0]);d=z[0],S=z[1],L=z[2]}else if(e==="SAME_UPPER"){d=Math.ceil(t/o),S=Math.ceil(r/i),L=Math.ceil(n/a);let z=(d-1)*o+u-t,D=(S-1)*i+p-r,re=(L-1)*a+h-n,te=Math.floor(z/2),V=z-te,ie=Math.floor(D/2),pe=D-ie,be=Math.floor(re/2),De=re-be;k={top:ie,bottom:pe,left:be,right:De,front:te,back:V}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:d,outHeight:S,outWidth:L}},Ti=(e,t,r,n,o,i=!1,a="channelsLast")=>{let u,p,h,k,d;if(a==="channelsLast")[u,p,h,k,d]=e;else if(a==="channelsFirst")[u,d,p,h,k]=e;else throw new Error(`Unknown dataFormat ${a}`);let[S,,L,z,D]=t,[re,te,V]=Mi(r),[ie,pe,be]=Mi(n),De=Ln(L,ie),Pe=Ln(z,pe),Ze=Ln(D,be),{padInfo:ct,outDepth:Ct,outHeight:Dt,outWidth:St}=od(o,p,h,k,re,te,V,De,Pe,Ze),bt=i?S*d:S,Gt=[0,0,0,0,0];return a==="channelsFirst"?Gt=[u,bt,Ct,Dt,St]:a==="channelsLast"&&(Gt=[u,Ct,Dt,St,bt]),{batchSize:u,dataFormat:a,inDepth:p,inHeight:h,inWidth:k,inChannels:d,outDepth:Ct,outHeight:Dt,outWidth:St,outChannels:bt,padInfo:ct,strideDepth:re,strideHeight:te,strideWidth:V,filterDepth:L,filterHeight:z,filterWidth:D,effectiveFilterDepth:De,effectiveFilterHeight:Pe,effectiveFilterWidth:Ze,dilationDepth:ie,dilationHeight:pe,dilationWidth:be,inShape:e,outShape:Gt,filterShape:t}},id=(e,t,r,n,o,i)=>{let a=i==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],p={x:r.map((re,te)=>te)},h=[Math.ceil(nd(p.x.map(re=>r[re]))/u[0]),1,1];nr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,d=Ce.size(r),S=[{type:12,data:d},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Qs(t,S),S.push(...Tt(e[0].dims,e[1].dims));let L=["rank","rank"],z=e.length===3;z&&(S.push(...Tt(e[2].dims)),L.push("rank")),S.push(...Tt(r));let D=re=>{let te=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Ds(t,te);let V=1,ie=Zt(e[0].dataType),pe=Oe("x",e[0].dataType,e[0].dims.length,k),be=Oe("W",e[1].dataType,e[1].dims.length,V),De=[pe,be],Pe=ft("result",e[0].dataType,r.length,V),Ze="";if(z){let Dt=Oe("bias",e[2].dataType,e[2].dims.length,V);De.push(Dt),Ze+=` fn getBiasByOutputCoords(coords : array) -> ${ie} { return bias[${a?yt("coords",4,5):yt("coords",1,5)}]; }`}let ct=Ur(k,ie),Ct=Xs(t,ct,ie);return` ${Ze} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${pe.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")}; } ${re.registerUniforms(te).declareVariables(...De,Pe)} ${re.mainStart()} ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Pe.offsetToIndices("global_idx")}; let batch = ${yt("coords",0,pe.rank)}; let d2 = ${a?yt("coords",pe.rank-1,pe.rank):yt("coords",1,pe.rank)}; let xFRCCorner = vec3(${a?yt("coords",1,pe.rank):yt("coords",2,pe.rank)}, ${a?yt("coords",2,pe.rank):yt("coords",3,pe.rank)}, ${a?yt("coords",3,pe.rank):yt("coords",4,pe.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${a?yt("uniforms.x_shape",1,pe.rank):yt("uniforms.x_shape",2,pe.rank)}; let xShapeZ = ${a?yt("uniforms.x_shape",2,pe.rank):yt("uniforms.x_shape",3,pe.rank)}; let xShapeW = ${a?yt("uniforms.x_shape",3,pe.rank):yt("uniforms.x_shape",4,pe.rank)}; let xShapeU = ${a?yt("uniforms.x_shape",4,pe.rank):yt("uniforms.x_shape",1,pe.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); } } } } ${z?"value = value + getBiasByOutputCoords(coords)":""}; ${Ct} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${k};${z}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:S}),getShaderSource:D}}}),ad,ld,dd=b(()=>{Ft(),zt(),Wt(),Ys(),ad=(e,t,r,n)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",a=e[0].dims,u=e[1].dims,p=t.format==="NHWC",h=p?r[3]:r[1],k=h/t.group,d=p&&k>=4?or(h):1,S=Ce.size(r)/d,L=[{type:12,data:S},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:k}];Qs(t,L),L.push(...Tt(a,[u[0],u[1],u[2],u[3]/d]));let z=o?["rank","rank","rank"]:["rank","rank"];L.push(...Tt([r[0],r[1],r[2],r[3]/d]));let D=re=>{let te=ft("output",e[0].dataType,r.length,d),V=Zt(te.type.tensor),ie=Xs(t,te.type.value,V),pe=Oe("x",e[0].dataType,a.length),be=Oe("w",e[1].dataType,u.length,d),De=[pe,be];o&&De.push(Oe("b",e[2].dataType,e[2].dims,d));let Pe=[{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"}];Ds(t,Pe);let Ze=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 = ${pe.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 = ${pe.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${be.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${re.registerUniforms(Pe).declareVariables(...De,te)} ${re.mainStart()} ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${te.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${p?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${d} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; var value: ${te.type.value} = ${te.type.value}(0); ${Ze} ${i} ${ie} ${te.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${d}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:L}),getShaderSource:D}},ld=(e,t,r,n)=>{let o=e.length>2,i=or(r[3]),a=or(r[2]),u=Ce.size(r)/i/a,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],k=[r[0],r[1],r[2],r[3]/i],d=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Qs(t,d),d.push(...Tt(p,h,k));let S=(a-1)*t.strides[1]+h[1],L=z=>{let D=ft("output",e[0].dataType,k.length,i),re=Zt(D.type.tensor),te=Xs(t,D.type.value,re),V=Oe("x",e[0].dataType,p.length,i),ie=Oe("w",e[1].dataType,h.length,i),pe=[V,ie];o&&pe.push(Oe("b",e[2].dataType,e[2].dims,i));let be=o?"value += b[output_channel];":"",De=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ds(t,De),` ${z.registerUniforms(De).declareVariables(...pe,D)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${a}u; let col = (index1 % width1) * ${a}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${V.type.value}, ${S}>; var values: array<${D.type.value}, ${a}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${S}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${V.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${V.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${ie.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} ${te} ${D.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${a};${S};${h[0]};${h[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:L}}}),ud,co,Ei,po,Pi,ho,cd,pd,mo,tc=b(()=>{zt(),Zu(),ec(),bi(),dd(),Ys(),mi(),Fs(),ud=(e,t,r,n,o,i)=>{let a=e[0],u=e.slice(i?1:2,i?3:4),p=u.length,h=t[0],k=t.slice(2).map((S,L)=>S+(S-1)*(r[L]-1)),d=u.map((S,L)=>S+n[L]+n[L+p]).map((S,L)=>Math.floor((S-k[L]+o[L])/o[L]));return d.splice(0,0,a),d.splice(i?3:1,0,h),d},co=[2,3,1,0],Ei=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},po=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=ci(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,u=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},ho=(e,t,r,n)=>{let o=r.format==="NHWC",i=ud(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let De=[t[0]];if(o){let Pe=e.kernelCustomData.wT??e.compute(rs(t[1],co),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Pe),De.push(Pe)}else De.push(t[1]);t.length===3&&De.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(ld(De,r,i,n),{inputs:De}):e.compute(ad(De,r,i,n),{inputs:De});return}let a=t.length===3,u=t[0].dims[o?1:2],p=t[0].dims[o?2:3],h=t[0].dims[o?3:1],k=t[1].dims[2],d=t[1].dims[3],S=i[o?1:2],L=i[o?2:3],z=i[o?3:1],D=o&&k===u&&d===p&&r.pads[0]===0&&r.pads[1]===0;if(D||k===1&&d===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let De=i[0],Pe,Ze,ct,Ct=[];if(o){let bt=e.kernelCustomData.wT??e.compute(rs(t[1],co),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=bt),D){let Gt=u*p*h;Pe=t[0].reshape([1,De,Gt]),Ze=bt.reshape([1,Gt,z]),ct=[1,De,z]}else Pe=t[0].reshape([De,u*p,h]),Ze=bt.reshape([1,h,z]),ct=[De,S*L,z];Ct.push(Pe),Ct.push(Ze)}else Pe=t[0].reshape([De,h,u*p]),Ze=t[1].reshape([1,z,h]),ct=[De,z,S*L],Ct.push(Ze),Ct.push(Pe);a&&Ct.push(t[2]);let Dt=ct[2],St=Ct[0].dims[Ct[0].dims.length-1];Dt<8&&St<8?e.compute(ao(Ct,r,i,ct,o,n),{inputs:Ct}):e.compute(lo(Ct,r,i,ct,o,n),{inputs:Ct});return}let re=!0,te=e.kernelCustomData.wT??e.compute(rs(t[1],co),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let V=[t[0],te];a&&V.push(t[2]);let ie=o?S*L:z,pe=o?z:S*L,be=k*d*h;e.compute(sd(V,r,i,ie,pe,be,a,re,n),{inputs:V})},cd=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),u=[1].concat(t.kernelShape),p=po({...t,pads:o,strides:i,dilations:a,kernelShape:u},n);ho(e,n,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},pd=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",o=po(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,a=Ti(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(id(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},mo=(e,t)=>{if(Ei(e.inputs,t),e.inputs[0].dims.length===3)cd(e,t);else if(e.inputs[0].dims.length===5)pd(e,e.inputs,t);else{let r=po(t,e.inputs);ho(e,e.inputs,r)}}}),hd,rc=b(()=>{Ft(),es(),zt(),Wt(),hd=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=t.format==="NHWC",a=t.group,u=e[1].dims,p=u[2]/a,h=u[3],k=i?or(h):1,d=Ce.size(o)/k,S=[Math.ceil(d/64),1,1];nr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${S}`);let L=["rank","rank"],z=[t.strides[0],t.strides[1]],D=[t.kernelShape[i?1:2],t.kernelShape[i?2:3]],re=[t.dilations[0],t.dilations[1]],te=[D[0]+(t.dilations[0]<=1?0:(t.kernelShape[i?1:2]-1)*(t.dilations[0]-1)),D[1]+(t.dilations[1]<=1?0:(t.kernelShape[i?2:3]-1)*(t.dilations[1]-1))],V=[te[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),te[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],ie=[{type:12,data:d},{type:12,data:z},{type:12,data:D},{type:12,data:re},{type:12,data:te},{type:6,data:V},{type:12,data:p},{type:12,data:h},...Tt(e[0].dims,e[1].dims)];n&&(ie.push(...Tt(e[2].dims)),L.push("rank")),ie.push(...Tt(o));let pe=be=>{let De=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:z.length},{name:"filter_dims",type:"u32",length:D.length},{name:"dilations",type:"u32",length:D.length},{name:"effective_filter_dims",type:"u32",length:te.length},{name:"pads",type:"i32",length:V.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Pe=Zt(e[0].dataType),Ze=i?1:2,ct=i?2:3,Ct=i?3:1,Dt=Oe("W",e[1].dataType,e[1].dims.length,k),St=Oe("Dy",e[0].dataType,e[0].dims.length),bt=[St,Dt];n&&bt.push(Oe("bias",e[2].dataType,[o[Ct]].length,k));let Gt=ft("result",e[0].dataType,o.length,k),jt=` let outputIndices = ${Gt.offsetToIndices(`global_idx * ${k}`)}; let batch = ${Gt.indicesGet("outputIndices",0)}; let d1 = ${Gt.indicesGet("outputIndices",Ct)}; let r = ${Gt.indicesGet("outputIndices",Ze)}; let c = ${Gt.indicesGet("outputIndices",ct)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${Gt.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 = (${Pe}(dyRCorner) + ${Pe}(wR)) / ${Pe}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${Pe}(uniforms.Dy_shape[${Ze}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${Pe}(dyCCorner) + ${Pe}(wC)) / ${Pe}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${Pe}(uniforms.Dy_shape[${ct}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${i?St.get("batch","idyR","idyC","inputChannel"):St.get("batch","inputChannel","idyR","idyC")}; let w_offset = ${Dt.indicesToOffset(`${Dt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${Dt.getByOffset(`w_offset / ${k}`)}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd${n?` + bias[d1 / ${k}]`:""}; ${Gt.setByOffset("global_idx","value")}; `;return` ${be.registerUniforms(De).declareVariables(...bt,Gt)} ${be.mainStart()} ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${jt}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}`,inputDependencies:L},getRunData:()=>({dispatchGroup:{x:S[0],y:S[1],z:S[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:ie}),getShaderSource:pe}}}),md,fd,_d,fo,gd,wd,_o,yd,bd,Js=b(()=>{rc(),Ys(),Fs(),md=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,fd=(e,t,r,n,o)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=i,r[o]=e-i):t==="SAME_LOWER"&&(r[n]=e-i,r[o]=i)},_d=(e,t,r,n,o,i,a,u,p,h)=>{let k=e.length-2,d=h.length===0;p.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,S)=>d*S,1)===0){r.length=0;for(let d=2;dd+S,0)===0){let d=t[0].dims.length-2;p=new Array(d).fill(1)}let h=e.strides.slice();if(h.reduce((d,S)=>d+S,0)===0){let d=t[0].dims.length-2;h=new Array(d).fill(1)}_d(u,r,p,e.autoPad,e.group,o,h,n,a,i);let k=Object.assign({},e);return Object.assign(k,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:p,strides:h}),k},gd=e=>{let t=ci(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,u=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,d=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:k,outputShape:d,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},wd=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((a,u)=>a+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((a,u)=>a+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((a,u)=>a+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((a,u)=>a+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},_o=(e,t,r,n)=>{let o=e.kernelCustomData.wT??e.compute(rs(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let i=[t[0],o];t.length===3&&i.push(t[2]),e.compute(hd(i,r,n),{inputs:i})},yd=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let p=fo({...t,pads:u,strides:a,dilations:i,kernelShape:o},n);_o(e,n,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},bd=(e,t)=>{if(wd(e.inputs,t),e.inputs[0].dims.length===3)yd(e,t);else{let r=fo(t,e.inputs);_o(e,e.inputs,r)}}}),Md,vd,xd,sc=b(()=>{Ft(),zt(),It(),Wt(),Md=(e,t,r,n)=>{let o=Ce.size(t),i=t.length,a=Oe("input",e,i),u=ft("output",e,i),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=Ce.normalizeAxis(p,i),k=d=>{let S=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,L=yt("uniforms.input_shape","uniforms.axis",i),z=n.reverse?S+(n.exclusive?" + 1":""):"0",D=n.reverse?L:S+(n.exclusive?"":" + 1");return` ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,u)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${u.offsetToIndices("global_idx")}; var sum = ${u.type.value}(0); let first : i32 = ${z}; let last : i32 = ${D}; for (var i : i32 = first; i < last; i++) { ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${a.getByIndices("inputIndices")}; } ${u.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:h},...Tt(t,t)]}),getShaderSource:k}},vd=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(Md(n,r,o,t),{inputs:[0]})},xd=e=>{let t=e.exclusive===1,r=e.reverse===1;return qe({exclusive:t,reverse:r})}}),Ci,Td,Ed,Pd,Cd,ki=b(()=>{Ft(),zt(),It(),Wt(),Ci=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.")},Td=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,u,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([r,n,o,i]=e.dims,a=k?[r,n,o,h,h,i/h**2]:[r,n,o,i/h**2,h,h],u=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=k?[r,h,h,i/h**2,n,o]:[r,i/h**2,h,h,n,o],u=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(a),S=d.dims.length,L=e.dataType,z=Oe("a",L,S),D=ft("output",L,S),re=te=>` ${te.registerUniform("output_size","u32").declareVariables(z,D)} ${Td(u,S,z,D)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${D.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${D.setByOffset("global_idx",z.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:te=>{let V=p?[r,n*h,o*h,i/h**2]:[r,i/h**2,n*h,o*h],ie=Ce.size(V),pe=d.dims,be=Ce.sortBasedOnPerm(pe,u);return{outputs:[{dims:V,dataType:te[0].dataType}],dispatchGroup:{x:Math.ceil(ie/64)},programUniforms:[{type:12,data:ie},...Tt(pe,be)]}},getShaderSource:re}},Pd=(e,t)=>{Ci(e.inputs),e.compute(Ed(e.inputs[0],t))},Cd=e=>qe({blocksize:e.blocksize,mode:e.mode,format:e.format})}),go,zn,$i,Bn,kd,$d,Sd,Si,wo,Ad,Id,nc=b(()=>{Ft(),zt(),It(),Wt(),go="[a-zA-Z]|\\.\\.\\.",zn="("+go+")+",$i="^"+zn+"$",Bn="("+zn+",)*"+zn,kd="^"+Bn+"$",$d=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Sd=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(kd)))throw new Error("Invalid LHS term");if(r.split(",").forEach((o,i)=>{let a=e[i].dims.slice();if(!o.match(RegExp($i)))throw new Error("Invalid LHS term");let u=this.processTerm(o,!0,a,i);this.lhs.push(u)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([o,i])=>i.count===1||o==="...").map(([o])=>o).join("");else if(!n.match(RegExp(zn)))throw new Error("Invalid RHS");n.match(RegExp(go,"g"))?.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(o);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let o=r.length,i=!1,a=[],u=0;if(!e.match(RegExp($i))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(go,"g")),h=new $d(n);return p?.forEach((k,d)=>{if(k==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let S=o-p.length+1;if(S<0)throw new Error("Ellipsis out of bounds");if(a=r.slice(u,u+S),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let L=0;Le+"_max",wo=(e,t,r,n)=>{let o=e.map(h=>h.length).map((h,k)=>Oe(`input${k}`,t,h)),i=Ce.size(n),a=ft("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),p=h=>{let k=[],d="var prod = 1.0;",S="var sum = 0.0;",L="sum += prod;",z=[],D=[],re=[],te=[],V=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((pe,be)=>{if(r.rhs.symbolToIndices.has(be)){let De=r.rhs.symbolToIndices.get(be)?.[0];De!==void 0&&r.lhs.forEach((Pe,Ze)=>{if(pe.inputIndices.includes(Ze)){let ct=Pe.symbolToIndices.get(be);if(ct===void 0)throw new Error("Invalid symbol error");ct.forEach(Ct=>{k.push(`${o[Ze].indicesSet(`input${Ze}Indices`,Ct,a.indicesGet("outputIndices",De))}`)})}})}else r.lhs.forEach((De,Pe)=>{if(pe.inputIndices.includes(Pe)){let Ze=De.symbolToIndices.get(be);if(Ze===void 0)throw new Error("Invalid symbol error");Ze.forEach(ct=>{z.push(`${o[Pe].indicesSet(`input${Pe}Indices`,ct,`${be}`)}`)}),te.push(`prod *= ${o[Pe].getByIndices(`input${Pe}Indices`)};`)}}),D.push(`for(var ${be}: u32 = 0; ${be} < uniforms.${Si(be)}; ${be}++) {`),re.push("}")});let ie=V?[...k,`let sum = ${o.map((pe,be)=>pe.getByIndices(`input${be}Indices`)).join(" * ")};`]:[...k,S,...D,...z,d,...te,L,...re];return` ${h.registerUniforms(u.map(pe=>({name:`${Si(pe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,a)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${a.offsetToIndices("global_idx")}; ${o.map((pe,be)=>`var input${be}Indices: ${o[be].type.indices};`).join(` `)} ${ie.join(` `)}; ${a.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(d=>r.symbolToInfo.has(d)).map(d=>({type:12,data:r.symbolToInfo.get(d)?.dimValue||0}));h.push({type:12,data:i});let k=e.map((d,S)=>[...Tt(d)]).reduce((d,S)=>d.concat(S),h);return k.push(...Tt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:k}},getShaderSource:p}},Ad=(e,t)=>{let r=new Sd(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(wo(o,e.inputs[0].dataType,r,n))},Id=e=>{let t=e.equation.replace(/\s+/g,"");return qe({equation:t})}}),oc,Ai,Od,Fd,mn,ic=b(()=>{Ft(),zt(),Wt(),oc=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?Ai(e,t):Ai(t,e),Fd=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Od(t,r),o=e[0].dataType,i=o===9||Ce.size(t)===1,a=o===9||t.length>0&&t[t.length-1]%4===0?4:1,u=i||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(Ce.size(n)/u),h=d=>{let S=Oe("input",o,t.length,a),L=ft("output",o,n.length,u),z;if(o===9){let D=(re,te,V="")=>` let outputIndices${te} = ${L.offsetToIndices(`outputOffset + ${te}u`)}; let offset${te} = ${S.broadcastedIndicesToOffset(`outputIndices${te}`,L)}; let index${te} = offset${te} / 4u; let component${te} = offset${te} % 4u; ${re}[${te}] = ${V}(${S.getByOffset(`index${te}`)}[component${te}]); `;z=` let outputOffset = global_idx * ${u}; var data = vec4(0); ${D("data",0,"u32")} ${D("data",1,"u32")} ${D("data",2,"u32")} ${D("data",3,"u32")} ${L.setByOffset("global_idx","data")} }`}else z=` let outputIndices = ${L.offsetToIndices(`global_idx * ${u}`)}; let inputOffset = ${S.broadcastedIndicesToOffset("outputIndices",L)}; let data = ${L.type.value}(${S.getByOffset(`inputOffset / ${a}`)}); ${L.setByOffset("global_idx","data")} }`;return` ${d.registerUniform("vec_size","u32").declareVariables(S,L)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${z}`},k=[{type:12,data:p},...Tt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${a}${u}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},mn=e=>{oc(e.inputs),e.compute(Fd(e.inputs),{inputs:[0]})}}),Dd,Ld,ac=b(()=>{Ft(),zt(),Wt(),si(),Dd=e=>{let t=e[0].dataType,r=Ce.size(e[0].dims),n=Ce.size(e[1].dims),o=n%4===0,i=a=>{let u=Oe("x",t,[1],4),p=Oe("bias",t,[1],4),h=ft("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=L=>` let bias${L}_offset: u32 = (global_idx * 4 + ${L}) % uniforms.bias_size; let bias${L} = ${p.getByOffset(`bias${L}_offset / 4`)}[bias${L}_offset % 4];`,S=o?` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(k).declareVariables(u,p,h)} ${Zo(dr(t))} ${a.mainStart(Lr)} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${u.getByOffset("global_idx")}; ${S} let x_in = x + bias; ${h.setByOffset("global_idx",ei("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Lr/4)}})}},Ld=e=>{e.inputs.length<2||Ce.size(e.inputs[1].dims)===0?ti(e):e.compute(Dd(e.inputs))}}),zd,yo,lc,Bd,dc=b(()=>{Ft(),zt(),It(),Wt(),zd=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},yo=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=Ce.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let u=r[i],p=e[0].dataType===9?4:1,h=Math.ceil(Ce.size(a)/p),k=[{type:12,data:h},{type:6,data:u},{type:12,data:i},...Tt(e[0].dims,e[1].dims,a)],d=S=>{let L=Oe("data",e[0].dataType,e[0].dims.length,p),z=Oe("inputIndices",e[1].dataType,e[1].dims.length),D=ft("output",e[0].dataType,a.length,p),re=V=>{let ie=n.length,pe=`var indicesIndices${V} = ${z.type.indices}(0);`;for(let be=0;be1?`indicesIndices${V}[${be}]`:`indicesIndices${V}`} = ${a.length>1?`outputIndices${V}[uniforms.axis + ${be}]`:`outputIndices${V}`};`;pe+=` var idx${V} = ${z.getByIndices(`indicesIndices${V}`)}; if (idx${V} < 0) { idx${V} = idx${V} + uniforms.axisDimLimit; } var dataIndices${V} : ${L.type.indices}; `;for(let be=0,De=0;be1?`dataIndices${V}[${be}]`:`dataIndices${V}`} = u32(idx${V});`,De+=ie):(pe+=`${o>1?`dataIndices${V}[${be}]`:`dataIndices${V}`} = ${a.length>1?`outputIndices${V}[${De}]`:`outputIndices${V}`};`,De++);return pe},te;if(e[0].dataType===9){let V=(ie,pe,be="")=>` let outputIndices${pe} = ${D.offsetToIndices(`outputOffset + ${pe}u`)}; ${re(pe)}; let offset${pe} = ${L.indicesToOffset(`dataIndices${pe}`)}; let index${pe} = offset${pe} / 4u; let component${pe} = offset${pe} % 4u; ${ie}[${pe}] = ${be}(${L.getByOffset(`index${pe}`)}[component${pe}]); `;te=` let outputOffset = global_idx * ${p}; var value = vec4(0); ${V("value",0,"u32")} ${V("value",1,"u32")} ${V("value",2,"u32")} ${V("value",3,"u32")} ${D.setByOffset("global_idx","value")} `}else te=` let outputIndices = ${D.offsetToIndices("global_idx")}; ${re("")}; let value = ${L.getByIndices("dataIndices")}; ${D.setByOffset("global_idx","value")}; `;return` ${S.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(L,z,D)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${te} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:d}},lc=e=>qe({axis:e.axis}),Bd=(e,t)=>{let r=e.inputs;zd(r),e.compute(yo(e.inputs,t))}}),Rd,Nd,jd,Ud=b(()=>{Ft(),zt(),Wt(),Rd=(e,t,r,n,o,i,a,u,p)=>{let h=[{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:12,data:r},{type:12,data:a},{type:12,data:u},{type:12,data:p}],k=[i];h.push(...Tt(t.dims,k));let d=S=>{let L=Oe("indices_data",t.dataType,t.dims.length),z=ft("input_slice_offsets_data",12,1,1),D=[L,z],re=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:r.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${S.registerUniforms(re).declareVariables(...D)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} } ${r.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${r.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h}),getShaderSource:d},{inputs:[t],outputs:[-1]})[0]},Nd=(e,t)=>{let r=e.inputs,n=r[0].dims,o=r[0].dataType,i=r[1].dims,a=i[i.length-1],u=Ce.sizeToDimension(i,i.length-1),p=Ce.sizeFromDimension(n,t.batchDims+a),h=Ce.sizeToDimension(n,t.batchDims),k=Ce.sizeFromDimension(n,t.batchDims),d=u/h,S=new Array(a),L=p;for(let pe=0;pen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let re=i.slice(0,-1).concat(n.slice(D)),te=Ce.size(re),V=[{type:12,data:te},{type:12,data:p},...Tt(r[0].dims,z.dims,re)],ie=pe=>{let be=Oe("data",r[0].dataType,r[0].dims.length),De=Oe("slice_offsets",12,z.dims.length),Pe=ft("output",r[0].dataType,re.length);return` ${pe.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(be,De,Pe)} ${pe.mainStart()} ${pe.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:re,dataType:o}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:V}),getShaderSource:ie},{inputs:[r[0],z]})},jd=e=>({batchDims:e.batch_dims,cacheKey:""})}),Wd,Vd,Ii,Gd,uc=b(()=>{Ft(),zt(),It(),Wt(),Wd=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Ce.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((u,p)=>p===r?Math.ceil(u/n)===i.dims[p]:u===i.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==i.dims.length||!a.dims.map((u,p)=>u===i.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Vd=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=Ce.normalizeAxis(t.gatherAxis,o),a=Ce.normalizeAxis(t.quantizeAxis,o),u=r.slice(0);u.splice(i,1,...n);let p=Ce.size(u),h=e[2].dataType,k=e[0].dataType===22,d=[{type:12,data:p},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...Tt(...e.map((L,z)=>L.dims),u)],S=L=>{let z=Oe("data",e[0].dataType,e[0].dims.length),D=Oe("inputIndices",e[1].dataType,e[1].dims.length),re=Oe("scales",e[2].dataType,e[2].dims.length),te=e.length>3?Oe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,V=ft("output",h,u.length),ie=[z,D,re];te&&ie.push(te);let pe=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${L.registerUniforms(pe).declareVariables(...ie,V)} ${L.mainStart()} let output_indices = ${V.offsetToIndices("global_idx")}; var indices_indices = ${D.type.indices}(0); ${n.length>1?` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${V.indicesGet("output_indices","uniforms.gather_axis + i")}; ${D.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${V.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${z.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${V.indicesGet("output_indices","i")}; ${z.indicesSet("data_indices","i","index")}; } var index_from_indices = ${D.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[i]}; } ${z.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { let index = ${V.indicesGet("output_indices",`i + ${n.length} - 1`)}; ${z.indicesSet("data_indices","i","index")}; } let data_offset = ${z.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${z.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${re.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${re.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${re.getByIndices("scale_indices")}; ${te?` let zero_point_indices = scale_indices; let zero_point_offset = ${te.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${te.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${dr(h)}(quantized_data - zero_point) * scale; ${V.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((L,z)=>z!==1).map(L=>L.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(L,z)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:d}),getShaderSource:S}},Ii=(e,t)=>{let r=e.inputs;Wd(r,t),e.compute(Vd(e.inputs,t))},Gd=e=>qe({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Oi,Kd,Hd,bo,cc=b(()=>{Ft(),zt(),It(),Wt(),Oi=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.`)},Kd=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,u=Ce.normalizeAxis(t.axis,o),p=r[u],h=i.slice(0),k=Ce.size(h),d=Oe("input",n,o),S=Oe("indicesInput",a,i.length),L=ft("output",n,h.length),z=[{type:12,data:k},{type:6,data:p},{type:12,data:u}];return z.push(...Tt(r,i,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:z}),getShaderSource:D=>` ${D.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,S,L)} ${D.mainStart()} ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${L.offsetToIndices("global_idx")}; var idx = ${S.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${d.type.indices}(outputIndices); ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${d.getByIndices("inputIndices")}; ${L.setByOffset("global_idx","value")}; }`}},Hd=e=>qe({axis:e.axis}),bo=(e,t)=>{let r=e.inputs;Oi(r),e.compute(Kd(e.inputs,t))}}),qd,Xd,Qd,Fi,Di=b(()=>{Ft(),zt(),Wt(),qd=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")},Xd=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=jr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[o,i];if(!u)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(i/p),k=Math.ceil(o/p),d=!0,S=Ce.size(u),L=[{type:12,data:d?h:S},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],z=["type","type"];e.length===3&&(L.push(...Tt(e[2].dims)),z.push("rank")),L.push(...Tt(u));let D=te=>{let V="";t.transA&&t.transB?V="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?V="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?V="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(V="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let ie=t.alpha===1?"":"value *= uniforms.alpha;",pe=Oe("a",e[0].dataType,e[0].dims),be=Oe("b",e[1].dataType,e[1].dims),De=pe.type.value,Pe=null,Ze=[pe,be];e.length===3&&(Pe=Oe("c",e[2].dataType,e[2].dims.length),Ze.push(Pe));let ct=ft("output",e[0].dataType,u.length);Ze.push(ct);let Ct=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${te.registerUniforms(Ct).declareVariables(...Ze)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${De}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${V} } ${ie} ${Pe!=null?`let cOffset = ${Pe.broadcastedIndicesToOffset("vec2(m, n)",ct)}; value += ${De}(uniforms.beta) * ${Pe.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},re=te=>{let V=Oe("a",e[0].dataType,e[0].dims),ie=Oe("b",e[1].dataType,e[1].dims),pe=null,be=[V,ie];e.length===3&&(pe=Oe("c",e[2].dataType,e[2].dims.length),be.push(pe));let De=ft("output",e[0].dataType,u.length);be.push(De);let Pe=[{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"}],Ze="",ct="";t.transA&&t.transB?(ct=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${V.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${ie.type.value}(0); } `,Ze="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(ct=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${V.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${ie.type.value}(0); } `,Ze="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(ct=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${V.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${ie.type.value}(0); } `,Ze="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(ct=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${V.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${ie.type.value}(0); } `,Ze="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Ct=t.alpha===1?"":"value *= uniforms.alpha;";return` ${te.registerUniforms(Pe).declareVariables(...be)} var tile_a: array, ${p}>; var tile_b: array, ${p}>; ${te.mainStart([p,p,1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; let num_tiles = (uniforms.K - 1) / ${p} + 1; var k_start = 0u; var value = ${De.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${ct} k_start = k_start + ${p}; workgroupBarrier(); for (var k: u32 = 0u; k < ${p}; k++) { ${Ze} } workgroupBarrier(); } ${Ct} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${pe!=null?`let cOffset = ${pe.broadcastedIndicesToOffset("vec2(m, n)",De)}; value += ${De.type.value}(uniforms.beta) * ${pe.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return d?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:L}),getShaderSource:re}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:L}),getShaderSource:D}},Qd=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Fi=(e,t)=>{qd(e.inputs),e.compute(Xd(e.inputs,t))}}),vs,xs,Zs,Ls,Yd,Jd,Li,Zd,eu,zi,pc,hc,Bi,Ri,mc=b(()=>{Ft(),zt(),It(),Wt(),[vs,xs,Zs,Ls]=[0,1,2,3],Yd=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")},Jd=` 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; } `,Li=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; } `,Zd=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)); `} } `,eu=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); }`:""} `,zi=(e,t,r)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { var pixel = ${t}(0); var indices = vec4(0); indices[${vs}] = batch; indices[${xs}] = channel;`+(()=>{switch(r.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${Zs}] = u32(r); indices[${Ls}] = u32(c); } `;case"border":return` indices[${Zs}] = u32(clamp(r, 0, H - 1)); indices[${Ls}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${Zs}] = gs_reflect(r, border[1], border[3]); indices[${Ls}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,pc=(e,t,r)=>(()=>{switch(r.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${vs}], indices[${xs}], 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[${vs}], indices[${xs}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${vs}], indices[${xs}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${vs}], indices[${xs}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${vs}], indices[${xs}], 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[${vs}], indices[${xs}], border); } } let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,hc=(e,t)=>{let r=Oe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Oe("grid",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[vs,xs,Zs,Ls]=[0,3,1,2]);let a=ft("output",e[0].dataType,i.length),u=r.type.value,p=Ce.size(i),h=[{type:12,data:p},...Tt(e[0].dims,n,i)],k=d=>` ${d.registerUniform("output_size","u32").declareVariables(r,o,a)} ${Jd} ${Li(u)} ${Zd(t)} ${eu(t)} ${zi(r,u,t)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${Zs}]); let W_in = i32(uniforms.x_shape[${Ls}]); ${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[${vs}], indices[${Zs}], indices[${Ls}]); let nxy = ${o.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${pc(a,u,t)} }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let S=Ce.size(i);return{outputs:[{dims:i,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:h}},getShaderSource:k}},Bi=(e,t)=>{Yd(e.inputs),e.compute(hc(e.inputs,t))},Ri=e=>qe({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),qr,Ni,tu,ji,Ui,Rn,ru,Wi=b(()=>{Ft(),zt(),It(),Ks(),jo(),Wt(),Fs(),qr=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Ni=(e,t)=>{let r=e[0],n=qr(e,1),o=qr(e,2),i=qr(e,3),a=qr(e,4),u=qr(e,5),p=qr(e,6),h=qr(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=r.dims[0],d=r.dims[1],S=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],L=d,z=0,D=0,re=Math.floor(S/t.numHeads);if(p&&h&&Ce.size(p.dims)&&Ce.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==re)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==re)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');z=p.dims[2],D=p.dims[2]}else if(p&&Ce.size(p.dims)||h&&Ce.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te;if(n&&Ce.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');te=2,L=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==re)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');te=5,L=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==re)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');te=0,L=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}if(i&&Ce.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let V=z+L,ie=0;if(a&&Ce.size(a.dims)>0){ie=8;let Pe=a.dims;throw Pe.length===1?Pe[0]===k?ie=1:Pe[0]===3*k+2&&(ie=3):Pe.length===2&&Pe[0]===k&&Pe[1]===V&&(ie=5),ie===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let pe=!1,be=S;if(o&&Ce.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(L!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');be=o.dims[2]}else{if(L!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');be=o.dims[1]*o.dims[3],pe=!0}}let De=!1;if(a&&Ce.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Ce.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==k||u.dims[1]!==t.numHeads||u.dims[2]!==d||u.dims[3]!==V)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:d,pastSequenceLength:z,kvSequenceLength:L,totalSequenceLength:V,maxSequenceLength:D,inputHiddenSize:0,hiddenSize:S,vHiddenSize:be,headSize:re,vHeadSize:Math.floor(be/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ie,scale:t.scale,broadcastResPosBias:De,passPastInKv:pe,qkvFormat:te}},tu=e=>qe({...e}),ji=qe({perm:[0,2,1,3]}),Ui=(e,t,r,n,o,i,a)=>{let u=[n,o,i],p=Ce.size(u),h=[{type:12,data:p},{type:12,data:a},{type:12,data:i}],k=d=>{let S=ft("qkv_with_bias",t.dataType,u),L=Oe("qkv",t.dataType,u),z=Oe("bias",r.dataType,u),D=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${d.registerUniforms(D).declareVariables(L,z,S)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,r],outputs:[-1]})[0]},Rn=(e,t,r,n,o,i,a,u)=>{let p=i;if(a&&Ce.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=Ui(e,i,a,t,n,r*o,u),p=p.reshape([t,n,r,o]),r===1||n===1?p:e.compute(rs(p,ji.perm),{inputs:[p],outputs:[-1]})[0]}else return i.dims.length===3&&(p=i.reshape([t,n,r,o])),r===1||n===1?p:e.compute(rs(p,ji.perm),{inputs:[p],outputs:[-1]})[0]},ru=(e,t)=>{let r=Ni(e.inputs,t),n=e.inputs[0],o=qr(e.inputs,1),i=qr(e.inputs,2),a=qr(e.inputs,3),u=qr(e.inputs,4),p=qr(e.inputs,5),h=qr(e.inputs,6),k=qr(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let d=o&&i&&o.dims.length===4&&i.dims.length===4,S=Rn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(d)return In(e,S,o,i,u,void 0,h,k,p,r);if(!o||!i)throw new Error("key and value must be provided");let L=Rn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),z=Rn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);In(e,S,L,z,u,void 0,h,k,p,r)}}),su,nu,ou,iu,Vi,au,lu,du=b(()=>{Ft(),zt(),It(),Wt(),su=e=>{if(!e||e.length<1)throw new Error("too few inputs")},nu=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),qe({numOutputs:n,axis:t.axis,splitSizes:r})},ou=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${yt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,iu=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Ce.size(r),o=e[0].dataType,i=Ce.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),u=Oe("input",o,r.length),p=new Array(t.numOutputs),h=[],k=[],d=0,S=[{type:12,data:n}];for(let z=0;z` ${z.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(u,...a)} ${ou(p.length)} ${iu(a)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${u.offsetToIndices("global_idx")}; var index = ${u.indicesGet("indices",i)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${yt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; ${u.indicesSet("indices",i,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:L,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:S})}},au=(e,t)=>{su(e.inputs);let r=e.inputs.length===1?t:nu(e.inputs,t);e.compute(Vi(e.inputs,r),{inputs:[0]})},lu=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qe({axis:t,numOutputs:n,splitSizes:r})}}),uu,Gi,Ki,cu,pu=b(()=>{It(),jo(),Wi(),du(),Fs(),uu=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,p=r.dims[0],h=r.dims[1],k=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],d=h,S=0,L=!n||n.dims.length===0,z=Math.floor(L?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);L&&(k=z*t.numHeads);let D=i&&i.dims.length!==0,re=a&&a.dims.length!==0;if(D&&i.dims.length===4&&i.dims[0]===p&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===z)throw new Error("BSNH pastKey/pastValue is not supported");if(D&&re){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');S=i.dims[2]}else if(D||re)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');d=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}let V=0,ie=!1,pe=t.kvNumHeads?z*t.kvNumHeads:k;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');pe=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');pe=o.dims[1]*o.dims[3],ie=!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:S,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:pe,headSize:z,vHeadSize:Math.floor(pe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:V,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ie,qkvFormat:te}},Gi=qe({perm:[0,2,1,3]}),Ki=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(rs(n,Gi.perm),{inputs:[n],outputs:[-1]})[0]),n},cu=(e,t)=>{let r=uu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=r.kvNumHeads?r.kvNumHeads:r.numHeads,d=qe({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,k*r.headSize,k*r.headSize]}),[S,L,z]=!o&&!i?e.compute(Vi([n],d),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],D=Rn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,S,void 0,0);In(e,D,Ki(e,L,r),Ki(e,z,r),void 0,void 0,a,u,void 0,r,p,h)}}),Hi,hu,fr,fc,_1=b(()=>{Ft(),zt(),Fs(),Wt(),Hi=(e,t,r,n,o,i,a,u)=>{let p=or(i),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,d=o*a,S=64;d===1&&(S=256);let L=[o,a,i/p],z=[o,a,2],D=["rank","type","type"],re=[];re.push(...Tt(L,z));let te=V=>{let ie=Oe("x",t.dataType,3,p),pe=Oe("scale",r.dataType,r.dims),be=Oe("bias",n.dataType,n.dims),De=ft("output",1,3,2),Pe=[ie,pe,be,De];return` var workgroup_shared : array<${k}, ${S}>; const workgroup_size = ${S}u; ${V.declareVariables(...Pe)} ${V.mainStart(S)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${h}(0); var squared_sum = ${h}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${h}(${ie.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${k}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${Gr("workgroup_shared[0][0]",p)} / f32(hight * ${p}); let squared_sum_final = ${Gr("workgroup_shared[0][1]",p)} / f32(hight * ${p}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${u};${S}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:z,dataType:1}],dispatchGroup:{x:d},programUniforms:re}),getShaderSource:te},{inputs:[t,r,n],outputs:[-1]})[0]},hu=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],u=n[1],p=Ce.sizeFromDimension(n,i),h=or(p),k=Ce.size(o)/h,d=Hi(e,t[0],t[1],t[2],a,p,u,r.epsilon),S=[a,u,p/h],L=[a,u],z=["type","none"],D=re=>{let te=Oe("x",t[0].dataType,S.length,h),V=Oe("scale_shift",1,L.length,2),ie=ft("output",t[0].dataType,S.length,h),pe=[te,V,ie];return` ${re.registerUniform("output_size","u32").declareVariables(...pe)} ${re.mainStart()} ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ie.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${V.getByIndices("vec2(batch, channel)")}; let value = ${te.getByOffset("global_idx")} * ${ie.type.value}(scale_shift.x) + ${ie.type.value}(scale_shift.y); ${ie.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...Tt(S,L,S)]}),getShaderSource:D},{inputs:[t[0],d]})},fr=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],u=Ce.sizeFromDimension(n,1)/a,p=or(a),h=Ce.size(o)/p,k=[{type:12,data:u},{type:12,data:Math.floor(a/p)}],d=["type","type"],S=!1,L=[0,n.length-1];for(let te=0;ten[L[V]])),D=Hi(e,z,t[1],t[2],i,u,a,r.epsilon),re=te=>{let V=Zt(t[0].dataType),ie=p===1?"vec2f":`mat${p}x2f`,pe=Pe=>{let Ze=Pe===0?"x":"y",ct=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${V}(${ct}(scale.${Ze}))`;case 2:return`vec2<${V}>(${ct}(scale[0].${Ze}, scale[1].${Ze}))`;case 4:return`vec4<${V}>(${ct}(scale[0].${Ze}, scale[1].${Ze}, scale[2].${Ze}, scale[3].${Ze}))`;default:throw new Error(`Not supported compoents ${p}`)}},be=Oe("input",t[0].dataType,t[0].dims,p),De=ft("output",t[0].dataType,o,p);return` @group(0) @binding(0) var input : array<${be.type.storage}>; @group(0) @binding(1) var scale_input : array<${ie}>; @group(0) @binding(2) var output : array<${De.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${te.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${pe(0)}, ${pe(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:re},{inputs:[t[0],D]})},fc=(e,t)=>{t.format==="NHWC"?fr(e,e.inputs,t):hu(e,e.inputs,t)}}),_c,qi,mu,gc=b(()=>{Ft(),zt(),Wt(),_c=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},qi=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],u=o,p=Ce.normalizeAxis(t.axis,o.length),h=Ce.sizeToDimension(o,p),k=Ce.sizeFromDimension(o,p),d=Ce.size(i.dims),S=a?Ce.size(a.dims):0;if(d!==k||a&&S!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. Size of scale and bias (if provided) must match this. Got scale size of ${d} and bias size of ${S}`);let L=[];for(let be=0;be1,V=r>2,ie=be=>{let De=Zt(e[0].dataType),Pe=[Oe("x",e[0].dataType,e[0].dims,z),Oe("scale",i.dataType,i.dims,z)];a&&Pe.push(Oe("bias",a.dataType,a.dims,z)),Pe.push(ft("output",e[0].dataType,u,z)),te&&Pe.push(ft("mean_data_output",1,L)),V&&Pe.push(ft("inv_std_output",1,L));let Ze=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${be.registerUniforms(Ze).declareVariables(...Pe)} ${be.mainStart()} ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${fs("f32",z)}; var mean_square_vector = ${fs("f32",z)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Ar(De,z,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Gr("mean_vector",z)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Gr("mean_square_vector",z)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Ar(De,z,"x[j + offset]")}; let f32scale = ${Ar(De,z,"scale[j]")}; output[j + offset] = ${Pe[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale ${a?`+ ${Ar(De,z,"bias[j]")}`:""} ); } ${te?"mean_data_output[global_idx] = mean":""}; ${V?"inv_std_output[global_idx] = inv_std_dev":""}; }`},pe=[{dims:u,dataType:e[0].dataType}];return te&&pe.push({dims:L,dataType:1}),V&&pe.push({dims:L,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${z};${r};${n}`,inputDependencies:D},getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:re}),getShaderSource:ie}},mu=(e,t)=>{_c(e.inputs),e.compute(qi(e.inputs,t,e.outputCount))}}),fu,_u,gu=b(()=>{zt(),mi(),bi(),fu=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.")},_u=e=>{fu(e.inputs);let t=gr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(ao(e.inputs,{activation:""},t));else{let o=t[t.length-2],i=Ce.size(e.inputs[0].dims.slice(0,-2)),a=Ce.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let u=e.inputs[0].reshape([1,i,n]),p=e.inputs[1].reshape([1,n,r]),h=[1,i,r],k=[u,p];e.compute(lo(k,{activation:""},t,h),{inputs:k})}else e.compute(lo(e.inputs,{activation:""},t))}}}),Xi,wc,wu,yu,Qi,g1=b(()=>{Ft(),zt(),It(),Wt(),Xi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!Ce.areEqual(a.dims,[t.n,o,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Ce.size(u)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(Ce.size(p)!==h)throw new Error("zeroPoints input size error.")}},wc=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,u=r.slice(0,n-2),p=Ce.size(u),h=e[1].dims[2]/4,k=e[0].dataType,d=or(t.k),S=or(h),L=or(a),z=u.concat([o,a]),D=o>1&&a/L%2===0?2:1,re=Ce.size(z)/L/D,te=64,V=[],ie=[p,o,i/d],pe=Ce.convertShape(e[1].dims).slice();pe.splice(-1,1,h/S),V.push(...Tt(ie)),V.push(...Tt(pe)),V.push(...Tt(e[2].dims)),e.length===4&&V.push(...Tt(Ce.convertShape(e[3].dims)));let be=[p,o,a/L];V.push(...Tt(be));let De=Pe=>{let Ze=ie.length,ct=Oe("a",e[0].dataType,Ze,d),Ct=Oe("b",12,pe.length,S),Dt=Oe("scales",e[2].dataType,e[2].dims.length),St=[ct,Ct,Dt],bt=e.length===4?Oe("zero_points",12,e[3].dims.length):void 0;bt&&St.push(bt);let Gt=be.length,jt=ft("output",e[0].dataType,Gt,L),Lt=Zt(e[0].dataType),rr=(()=>{switch(d){case 1:return`array<${Lt}, 8>`;case 2:return`mat4x2<${Lt}>`;case 4:return`mat2x4<${Lt}>`;default:throw new Error(`${d}-component is not supported.`)}})(),Yt=()=>{let it=` // reuse a data var input_offset = ${ct.indicesToOffset(`${ct.type.indices}(batch, row, word_offset)`)}; var a_data: ${rr}; for (var j: u32 = 0; j < ${8/d}; j++) { a_data[j] = ${ct.getByOffset("input_offset")}; input_offset++; } `;for(let Et=0;Et> 4) & b_mask); b_quantized_values = ${rr}(${Array.from({length:4},(hr,vr)=>`${Lt}(b_value_lower[${vr}]), ${Lt}(b_value_upper[${vr}])`).join(", ")}); b_dequantized_values = ${d===1?`${rr}(${Array.from({length:8},(hr,vr)=>`(b_quantized_values[${vr}] - ${bt?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${rr}(${Array(8).fill(`${bt?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; workgroup_shared[local_id.x * ${D} + ${Math.floor(Et/L)}]${L>1?`[${Et%L}]`:""} += ${Array.from({length:8/d},(hr,vr)=>`${d===1?`a_data[${vr}] * b_dequantized_values[${vr}]`:`dot(a_data[${vr}], b_dequantized_values[${vr}])`}`).join(" + ")}; `;return it},qt=()=>{let it=` var col_index = col * ${L}; ${bt?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Lt}(8);`} `;for(let Et=0;Et> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${bt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${Et} = ${Lt}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return it},Qr=()=>{let it=`col_index = col * ${L};`;for(let Et=0;Et; var b_value_upper: vec4; var b_quantized_values: ${rr}; var b_dequantized_values: ${rr};`,it};return` var workgroup_shared: array<${jt.type.value}, ${D*te}>; ${Pe.declareVariables(...St,jt)} ${Pe.mainStart([te,1,1])} let output_indices = ${jt.offsetToIndices(`(global_idx / ${te}) * ${D}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${te}) { //process one block var word_offset: u32 = block * ${t.blockSize/d}; ${qt()} for (var word: u32 = 0; word < ${h}; word += ${S}) { ${Qr()} for (var i: u32 = 0; i < ${S}; i++) { ${Yt()} word_offset += ${8/d}; } } } workgroupBarrier(); if (local_id.x < ${D}) { var output_value: ${jt.type.value} = ${jt.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${te}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${D}; } ${jt.setByIndices(`${jt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${d};${S};${L};${D};${te}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:z,dataType:k}],dispatchGroup:{x:re},programUniforms:V}),getShaderSource:De}},wu=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,u=r.slice(0,n-2),p=Ce.size(u),h=e[1].dims[2]/4,k=e[0].dataType,d=or(t.k),S=or(h),L=u.concat([o,a]),z=128,D=a%8===0?8:a%4===0?4:1,re=z/D,te=re*S*8,V=te/d,ie=te/t.blockSize,pe=Ce.size(L)/D,be=[],De=[p,o,i/d],Pe=Ce.convertShape(e[1].dims).slice();Pe.splice(-1,1,h/S),be.push(...Tt(De)),be.push(...Tt(Pe)),be.push(...Tt(e[2].dims)),e.length===4&&be.push(...Tt(Ce.convertShape(e[3].dims)));let Ze=[p,o,a];be.push(...Tt(Ze));let ct=Ct=>{let Dt=De.length,St=Oe("a",e[0].dataType,Dt,d),bt=Oe("b",12,Pe.length,S),Gt=Oe("scales",e[2].dataType,e[2].dims.length),jt=[St,bt,Gt],Lt=e.length===4?Oe("zero_points",12,e[3].dims.length):void 0;Lt&&jt.push(Lt);let rr=Ze.length,Yt=ft("output",e[0].dataType,rr),qt=Zt(e[0].dataType),Qr=()=>{switch(d){case 1:return` let a_data0 = vec4<${qt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${qt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${qt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${qt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` var sub_a: array<${St.type.value}, ${V}>; var inter_results: array, ${D}>; ${Ct.declareVariables(...jt,Yt)} ${Ct.mainStart([re,D,1])} let output_indices = ${Yt.offsetToIndices(`workgroup_index * ${D}`)}; 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) / ${ie} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${V}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${V}; a_offset += ${z}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${St.getByIndices(`${St.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${St.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${ie} + local_id.x; ${Lt?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${Lt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${qt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${qt}(8);`} let scale = ${Gt.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${bt.getByIndices(`${bt.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/d}; for (var i: u32 = 0; i < ${S}; i++) { ${Qr()} let b_value = ${S===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${qt}>(${Array.from({length:4},(it,Et)=>`${qt}(b_value_lower[${Et}]), ${qt}(b_value_upper[${Et}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${qt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(it,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; word_offset += ${8/d}; } workgroupBarrier(); } if (local_idx < ${D}) { var output_value: ${Yt.type.value} = ${Yt.type.value}(0); for (var b = 0u; b < ${re}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Yt.setByIndices(`${Yt.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${d};${S};${re};${D}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:L,dataType:k}],dispatchGroup:{x:pe},programUniforms:be}),getShaderSource:ct}},yu=(e,t)=>{Xi(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(wu(e.inputs,t)):e.compute(wc(e.inputs,t))},Qi=e=>qe(e)}),yc,bu,Mu,vu,xu,Tu,Eu,Pu,Cu,bc=b(()=>{Ft(),zt(),Wt(),yc=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].")}},bu=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${yt("uniforms.pads",o,r)}; if (k < 0) { break; } if (k >= i32(${yt("uniforms.x_shape",o,t)})) { break; } offset += k * i32(${yt("uniforms.x_strides",o,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `},Mu=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${yt("uniforms.pads",o,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${yt("uniforms.x_shape",o,t)}) - 1); k = k % _2n_1; if(k >= i32(${yt("uniforms.x_shape",o,t)})) { k = _2n_1 - k; } } offset += k * i32(${yt("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},vu=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${yt("uniforms.pads",o,r)}; if (k < 0) { k = 0; } if (k >= i32(${yt("uniforms.x_shape",o,t)})) { k = i32(${yt("uniforms.x_shape",o,t)}) - 1; } offset += k * i32(${yt("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},xu=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${yt("uniforms.pads",o,r)}; if (k < 0) { k += i32(${yt("uniforms.x_shape",o,t)}]); } if (k >= i32(${yt("uniforms.x_shape",o,t)})) { k -= i32(${yt("uniforms.x_shape",o,t)}); } offset += k * i32(${yt("uniforms.x_strides",o,t)}); `;return` var offset = 0; var k = 0; ${n} value = x[offset]; `},Tu=(e,t,r)=>{switch(r.mode){case 0:return bu(e,t,r.pads.length);case 1:return Mu(e,t,r.pads.length);case 2:return vu(e,t,r.pads.length);case 3:return xu(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Eu=(e,t)=>{let r=Ce.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=Ce.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...Tt(e[0].dims,r));let u=["rank"],p=h=>{let k=ft("output",e[0].dataType,r.length),d=Oe("x",e[0].dataType,n.length),S=d.type.value,L=Tu(k,n.length,t),z=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&z.push({name:"constant_value",type:a?S:"f32"}),` ${h.registerUniforms(z).declareVariables(d,k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${k.offsetToIndices("global_idx")}; var value = ${S}(0); ${L} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Ce.size(r)/64)},programUniforms:i}),getShaderSource:p}},Pu=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let p=0;pi[Number(p)]=Number(u));let a=[];return i.forEach(u=>a.push(u)),{mode:t.mode,value:n,pads:a}}else return t},Cu=(e,t)=>{yc(e.inputs);let r=Pu(e.inputs,t);e.compute(Eu(e.inputs,r),{inputs:[0]})}}),Nn,Yi,Ji,ku,Zi,$u,Su,ea,ta,Au,Mc,Iu,vc,xc,Ou,Tc,Ec,Pc,Cc,w1=b(()=>{Ge(),Ft(),zt(),Wt(),Nn=e=>{if(E.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Yi=(e,t,r)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),u=t.strides.slice(),p=i?t.dilations.slice():[],h=t.pads.slice();Er.adjustPoolAttributes(r,o,a,u,p,h);let k=Er.computePoolOutputShape(r,o,u,p,a,h,t.autoPad),d=Object.assign({},t);i?Object.assign(d,{kernelShape:a,strides:u,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:a,strides:u,pads:h,cacheKey:t.cacheKey});let S=k.slice();return S.push(S.splice(1,1)[0]),[d,n?S:k]},Ji=(e,t)=>{let r=t.format==="NHWC",n=Ce.size(e),o=Ce.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],d=!!(h+k);i.push({type:12,data:u},{type:12,data:p},{type:12,data:h},{type:12,data:k}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let S=!1;if(t.kernelShape.length===2){let L=t.kernelShape[t.kernelShape.length-2],z=t.strides[t.strides.length-2],D=t.pads[t.pads.length/2-2],re=t.pads[t.pads.length-2];S=!!(D+re),i.push({type:12,data:L},{type:12,data:z},{type:12,data:D},{type:12,data:re}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,d,S]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Ce.computeStrides(t.kernelShape);i.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[i,a,!!p,!1,!1]}},ku=(e,t,r,n,o,i,a,u,p,h,k,d)=>{let S=o.format==="NHWC",L=t.type.value,z=ft("output",t.type.tensor,n);if(o.kernelShape.length<=2){let D="",re="",te="",V=r-(S?2:1);if(k?D=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${V}] = indices[${V}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${V}] < 0 || xIndices[${V}] >= uniforms.x_shape[${V}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:D=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${V}] = indices[${V}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`,o.kernelShape.length===2){let ie=r-(S?3:2);d?re=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ie}] = indices[${ie}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ie}] < 0 || xIndices[${ie}] >= uniforms.x_shape[${ie}]) { pad += i32(uniforms.kw); continue; } `:re=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ie}] = indices[${ie}] * uniforms.sh - uniforms.phStart + j; `,te=` } `}return` ${e.registerUniforms(p).declareVariables(t,z)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${z.offsetToIndices("global_idx")}; var xIndices = ${z.offsetToIndices("global_idx")}; var value = ${L}(${u}); var pad = 0; ${re} ${D} ${te} ${a} output[global_idx] = value; }`}else{if(S)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let D=o.kernelShape.length,re=o.pads.length,te="";return h?te=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:te=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} `,` ${e.registerUniforms(p).declareVariables(t,z)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${z.offsetToIndices("global_idx")}; var xIndices = ${z.offsetToIndices("global_idx")}; var offsets: array; var value = ${L}(${u}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${D-1}u; j++) { offsets[j] = offset / ${yt("uniforms.kernelStrides","j",D)}; offset -= offsets[j] * ${yt("uniforms.kernelStrides","j",D)}; } offsets[${D-1}] = offset; isPad = false; for (var j = ${r-D}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${yt("uniforms.strides",`j - ${r-D}u`,D)} + offsets[j - ${r-D}u] - ${yt("uniforms.pads","j - 2u",re)}; ${te} } ${a} output[global_idx] = value; }`}},Zi=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,$u=e=>`${Zi(e)};${e.countIncludePad}`,Su=e=>`${Zi(e)};${e.storageOrder};${e.dilations}`,ea=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}),ta=(e,t,r,n)=>{let[o,i]=Yi(t,n,r),a=Oe("x",t.dataType,t.dims.length),u=a.type.value,p="value += x_val;",h="";o.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[k,d,S,L,z]=Ji(i,o);k.push(...Tt(t.dims,i));let D=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${S};${L};${z}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Ce.size(i)/64)},programUniforms:k}),getShaderSource:re=>ku(re,a,t.dims.length,i.length,o,p,h,0,d,S,L,z)}},Au=e=>{let t=e.count_include_pad!==0,r=ea(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:$u(n)}},Mc=(e,t)=>{Nn(e.inputs),e.compute(ta("AveragePool",e.inputs[0],!1,t))},Iu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},vc=e=>{let t=e.format;return{format:t,...Iu,cacheKey:t}},xc=(e,t)=>{Nn(e.inputs),e.compute(ta("GlobalAveragePool",e.inputs[0],!0,t))},Ou=(e,t,r,n)=>{let[o,i]=Yi(t,n,r),a=` value = max(x_val, value); `,u="",p=Oe("x",t.dataType,t.dims.length),h=["rank"],[k,d,S,L,z]=Ji(i,o);return k.push(...Tt(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${S};${L};${z}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Ce.size(i)/64)},programUniforms:k}),getShaderSource:D=>ku(D,p,t.dims.length,i.length,o,a,u,t.dataType===10?-65504:-1e5,d,S,L,z)}},Tc=(e,t)=>{Nn(e.inputs),e.compute(Ou("MaxPool",e.inputs[0],!1,t))},Ec=e=>{let t=e.storage_order,r=e.dilations,n=ea(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:r,...n,cacheKey:""};return{...o,cacheKey:Su(o)}},Pc=e=>{let t=e.format;return{format:t,...Iu,cacheKey:t}},Cc=(e,t)=>{Nn(e.inputs),e.compute(Ou("GlobalMaxPool",e.inputs[0],!0,t))}}),kc,$c,Sc,Ac,y1=b(()=>{Ft(),zt(),It(),Wt(),kc=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},$c=(e,t)=>{let r=Ce.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,u=Ce.size(i),p=n===3||n===2,h=p?[Math.ceil(Ce.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,d=e.length>2?e[2]:void 0,S=d?p?[Math.ceil(Ce.size(d.dims)/4)]:d.dims:void 0,L=k.length===0||k.length===1&&k[0]===1,z=L===!1&&k.length===1,D=or(u),re=L&&(!p||D===4),te=re?D:1,V=re&&!p?D:1,ie=Oe("input",p?12:n,h.length,V),pe=Oe("scale",a,k.length),be=d?Oe("zero_point",p?12:n,S.length):void 0,De=ft("output",a,i.length,te),Pe=[ie,pe];be&&Pe.push(be);let Ze=[h,k];d&&Ze.push(S);let ct=[{type:12,data:u/te},{type:12,data:r},{type:12,data:t.blockSize},...Tt(...Ze,i)],Ct=Dt=>{let St=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Dt.registerUniforms(St).declareVariables(...Pe,De)} ${Dt.mainStart()} ${Dt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${De.offsetToIndices("global_idx")}; // Set input x ${p?` let input = ${ie.getByOffset("global_idx / 4")}; let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${te===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ie.getByOffset("global_idx")};`}; // Set scale input ${L?`let scale_value= ${pe.getByOffset("0")}`:z?` let scale_index = ${De.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${pe.getByOffset("scale_index")};`:` var scale_indices: ${pe.type.indices} = output_indices; let index = ${pe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${pe.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${pe.getByIndices("scale_indices")};`}; // Set zero-point input ${be?L?p?` let zero_point_input = ${be.getByOffset("0")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${be.getByOffset("0")}`:z?p?` let zero_point_index = ${De.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${be.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${De.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${be.getByOffset("zero_point_index")};`:p?` let zero_point_offset = ${pe.indicesToOffset("scale_indices")}; let zero_point_input = ${be.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${be.getByIndices("scale_indices")};`:`let zero_point_value = ${p?o?"i32":"u32":ie.type.value}(0);`}; // Compute and write output ${De.setByOffset("global_idx",`${De.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:be?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Ct,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(u/te/64),y:1,z:1},programUniforms:ct})}},Sc=(e,t)=>{kc(e.inputs,t),e.compute($c(e.inputs,t))},Ac=e=>qe({axis:e.axis,blockSize:e.blockSize})}),Ic,Oc,Fc,b1=b(()=>{Ge(),Ft(),Wt(),Ic=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error("Range these inputs' contents are invalid.")},Oc=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,u=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...Tt(i)],p=h=>{let k=ft("output",n,i.length),d=k.type.value,S=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` ${h.registerUniforms(S).declareVariables(k)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u})}},Fc=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),E.webgpu.validateInputContent&&Ic(t,r,n),e.compute(Oc(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Dc,Lc,zc,Bc,M1=b(()=>{Ft(),zt(),It(),Wt(),Dc=(e,t,r,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ var oldValue = 0; loop { let newValueF32 =`,i=`; let newValue = bitcast(newValueF32); let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); if res.exchanged { break; } oldValue = res.old_value; } }`;switch(e){case"none":return`${t}=${r};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:` ${o}bitcast<${n}>(oldValue) + (${r})${i}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:` ${o}max(bitcast(oldValue), (${r}))${i}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${o}min(bitcast<${n}>(oldValue), (${r}))${i}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${r}))${i}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Lc=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r,i=1,a=Math.ceil(Ce.size(n)/i),u=n[n.length-1],p=Ce.sizeFromDimension(r,u),h=[{type:12,data:a},{type:12,data:u},{type:12,data:p},...Tt(e[1].dims,e[2].dims,o)],k=d=>{let S=Oe("indices",e[1].dataType,e[1].dims.length),L=Oe("updates",e[2].dataType,e[2].dims.length,i),z=t.reduction!=="none"&&t.reduction!==""?ts("output",e[0].dataType,o.length):ft("output",e[0].dataType,o.length,i);return` ${d.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(S,L,z)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var data_offset = 0u; let indices_start = uniforms.last_index_dimension * global_idx; let indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${e[0].dims.length===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[i - indices_start]; let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim)); } for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; ${Dc(t.reduction,"output[data_offset + i]","value",z.type.value)} } }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:k}},zc=e=>qe({reduction:e.reduction}),Bc=(e,t)=>{e.compute(Lc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Rc,Nc,jc,Uc,Wc,Vc,Gc,Kt,Fu,Nr,Wr,Vr,en,Kc,Du,Lu,g,f,H,Te=b(()=>{Ft(),zt(),It(),Wt(),Rc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Nc=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},jc=(e,t,r,n,o,i)=>{let[a,u,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(k=>i.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Rc(n,t),t.axes.length>0&&Nc(n,t.axes,h).forEach((k,d)=>n[d]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>o.push(Number(k))),o.length!==0&&o.length!==h&&r>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Uc=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Wc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Vc=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},Gc=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Kt=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},Fu=(e,t,r,n,o)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${yt("uniforms.scales","i",n)}; var roi_low = ${yt("uniforms.roi","i",o)}; var roi_hi = ${yt("uniforms.roi",`i + ${t.length}`,o)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${yt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${yt("uniforms.output_shape","i",r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,Nr=(e,t,r,n,o,i,a)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${yt("uniforms.scales","i",o)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${yt("uniforms.roi","i",i)}; var roi_hi = ${yt("uniforms.roi",`i + ${r.length}`,i)}; var input_shape_i = ${yt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${yt("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; }`,Wr=(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 >= ${yt("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Vr=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",en=(e,t,r,n,o)=>{let[i,a,u,p]=r.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, ${r[a]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; ${Vr(e,p,i,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${a}]; var col:${h} = originalIndices[${u}]; ${n?`if (row < 0 || row > (${r[a]} - 1) || col < 0 || col > (${r[u]} - 1)) { return ${o}; }`:""}; row = max(0, min(row, ${r[a]} - 1)); col = max(0, min(col, ${r[u]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${i}])`:"0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},Kc=(e,t,r,n,o,i,a,u,p,h)=>{let k=r.length===2,[d,S]=k?[0,1]:[2,3],L=e.type.value,z=D=>{let re=D===d?"row":"col";return` fn ${re}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${L} { var output_index = ${t.indicesGet("output_indices",D)}; var originalIdx: ${L} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[D]}, ${n[D]}, ${r[D]}, ${i[D]}, ${i[D]} + ${r.length}); var fractOriginalIdx: ${L} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${u} && (originalIdx < 0 || originalIdx > (${r[D]} - 1))) { return ${p}; } var data: array<${L}, 4> = array<${L}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${re}: ${L} = originalIdx + ${L}(i); if (${re} < 0 || ${re} >= ${r[D]}) { ${h?`coefs[i + 1] = 0.0; continue;`:u?`return ${p};`:`${re} = max(0, min(${re}, ${r[D]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",D,`u32(${re})`)}; data[i + 1] = ${D===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${z(d)}; ${z(S)}; fn getCubicInterpolationCoefs(s: ${L}) -> array<${L}, 4> { var absS = abs(s); var coeffs: array<${L}, 4> = array<${L}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${L} = 1.0 - absS; var twoMinusAbsS: ${L} = 2.0 - absS; var onePlusAbsS: ${L} = 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<${L}, 4>, coefs: array<${L}, 4>) -> ${L} { var coefsSum: ${L} = 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}) -> ${L} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Du=(e,t,r,n,o)=>{let[i,a,u,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",a,`max(0, min(depth, ${r[a]} - 1))`)}; ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)}; ${Vr(e,h,i,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${k} = originalIndices[${a}]; var height:${k} = originalIndices[${u}]; var width:${k} = originalIndices[${p}]; ${n?`if (depth < 0 || depth > (${r[a]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[p]} - 1)) { return ${o}; }`:""}; depth = max(0, min(depth, ${r[a]} - 1)); height = max(0, min(height, ${r[u]} - 1)); width = max(0, min(width, ${r[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 = ${r.length>3?`u32(originalIndices[${h}])`:"0"}; var batch: u32 = ${r.length>3?`u32(originalIndices[${i}])`:"0"}; var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${k} = abs(depth - ${k}(depth1)); var dx2: ${k} = abs(${k}(depth2) - depth); var dy1: ${k} = abs(height - ${k}(height1)); var dy2: ${k} = abs(${k}(height2) - height); var dz1: ${k} = abs(width - ${k}(width1)); var dz2: ${k} = abs(${k}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},Lu=(e,t,r,n,o,i)=>{let a=e.dims,u=Vc(i,t.axes,a.length),p=Gc(a,n,o,t.axes),h=n.slice();n.length===0&&(h=a.map((V,ie)=>V===0?1:p[ie]/V),t.keepAspectRatioPolicy!=="stretch"&&(p=Kt(a,h,t)));let k=ft("output",e.dataType,p.length),d=Oe("input",e.dataType,a.length),S=Ce.size(p),L=a.length===p.length&&a.every((V,ie)=>V===p[ie]),z=t.coordinateTransformMode==="tf_crop_and_resize",D=t.extrapolationValue,re=d.type.value,te=V=>` ${L?"":` ${Uc(t.coordinateTransformMode,re)}; ${(()=>{switch(t.mode){case"nearest":return` ${Wr(d,a)}; ${Wc(t.nearestMode,r,re)}; ${Nr(d,k,a,p,h.length,u.length,z)}; `;case"linear":return` ${Fu(k,a,p,h.length,u.length)}; ${(()=>{if(a.length===2||a.length===4)return`${en(d,k,a,z,D)}`;if(a.length===3||a.length===5)return`${Du(d,k,a,z,D)}`;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`${Kc(d,k,a,p,h,u,t.cubicCoeffA,z,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${V.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",u.length).declareVariables(d,k)} ${V.mainStart()} ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${L?"output[global_idx] = input[global_idx];":` let output_indices = ${k.offsetToIndices("global_idx")}; var input_indices: ${d.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${d.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?h:""}|${o.length>0?o:""}|${u.length>0?u:""}|${L}|${a}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},{type:1,data:h},{type:1,data:u},...Tt(a,p)]})}},g=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},f=(e,t)=>{let r=[],n=[],o=[],i=g(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");jc(e.inputs,t,i,r,n,o),e.compute(Lu(e.inputs[0],t,i,r,n,o),{inputs:[0]})},H=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,u=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return qe({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:u,mode:p,nearestMode:h})}}),$e,Fe,et,rt=b(()=>{Ft(),zt(),It(),Wt(),$e=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!Ce.areEqual(n.dims,[])&&!Ce.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!Ce.areEqual(o.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=r.dims[0],h=r.dims[r.dims.length-2],k=o.dims[0],d=Ce.sizeFromDimension(r.dims,1)/h,S=u===0?o.dims[1]*2:d/a;if(u>S)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(S/2!==o.dims[1]&&u/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Fe=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],u=Ce.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=u/p,k=e[2].dims[1],d=o===0?k*2:h/n,S=new Array(a,p,h/d,d-k),L=Ce.computeStrides(S),z=[{type:1,data:i},{type:12,data:S},{type:12,data:L},...e[0].dims.length===3?new Array({type:12,data:[u,h,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,d,p*d,1]}):[],...Tt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],D=re=>{let te=Oe("input",e[0].dataType,e[0].dims.length),V=Oe("position_ids",e[1].dataType,e[1].dims.length),ie=Oe("cos_cache",e[2].dataType,e[2].dims.length),pe=Oe("sin_cache",e[3].dataType,e[3].dims.length),be=ft("output",e[0].dataType,e[0].dims.length);return re.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:S.length},{name:"global_strides",type:"u32",length:L.length},{name:"input_output_strides",type:"u32",length:L.length}]),` ${re.declareVariables(te,V,ie,pe,be)} ${re.mainStart(Lr)} let half_rotary_emb_dim = uniforms.${ie.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${re.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${V.broadcastedIndicesToOffset("bsnh.xy",ft("",V.type.tensor,2))}; let position_id = u32(${V.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${te.getByOffset("i")} * ${ie.get("position_id","bsnh[3]")} - ${te.getByOffset("j")} * ${pe.get("position_id","bsnh[3]")}; ${be.setByOffset("i","re")} let im = ${te.getByOffset("i")} * ${pe.get("position_id","bsnh[3]")} + ${te.getByOffset("j")} * ${ie.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",te.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:qe({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:D,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Ce.size(S)/Lr)},programUniforms:z})}},et=(e,t)=>{$e(e.inputs,t),e.compute(Fe(e.inputs,t))}}),_t,$t,Jt,Ht=b(()=>{Ft(),zt(),Wt(),_t=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},$t=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=Ce.size(i),u=i,p=a,h=i.slice(-1)[0],k=n?i.slice(0,-1).concat(1):[],d=!o&&e.length>3,S=e.length>4,L=n&&r>1,z=n&&r>2,D=r>3,re=64,te=or(h),V=[{type:12,data:p},{type:12,data:te},{type:12,data:h},{type:1,data:t.epsilon}],ie=be=>{let De=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Pe=[Oe("x",e[0].dataType,e[0].dims,te),Oe("skip",e[1].dataType,e[1].dims,te),Oe("gamma",e[2].dataType,e[2].dims,te)];d&&Pe.push(Oe("beta",e[3].dataType,e[3].dims,te)),S&&Pe.push(Oe("bias",e[4].dataType,e[4].dims,te)),Pe.push(ft("output",e[0].dataType,u,te)),L&&Pe.push(ft("mean_output",1,k)),z&&Pe.push(ft("inv_std_output",1,k)),D&&Pe.push(ft("input_skip_bias_sum",e[0].dataType,u,te));let Ze=Zt(e[0].dataType),ct=Zt(1,te);return` ${be.registerUniforms(De).declareVariables(...Pe)} var sum_shared : array<${ct}, ${re}>; var sum_squared_shared : array<${ct}, ${re}>; ${be.mainStart([re,1,1])} let ix = local_id.x; let iy = global_id.x / ${re}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${re}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${re-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${S?"bias[offset1d + i]":Ze+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${D?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Ar(Ze,te,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${re}; 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 = ${Gr("sum",te)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Gr("square_sum",te)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); ${L?"mean_output[global_idx] = mean;":""} ${z?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${o?"":`- ${Ze}(mean)`}) * ${Ze}(inv_std_dev) * gamma[offset1d + i] ${d?"+ beta[offset1d + i]":""}; } }`},pe=[{dims:u,dataType:e[0].dataType}];return r>1&&pe.push({dims:k,dataType:1}),r>2&&pe.push({dims:k,dataType:1}),r>3&&pe.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${te};${L};${z};${D}`,inputDependencies:e.map((be,De)=>"type")},getShaderSource:ie,getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:V})}},Jt=(e,t)=>{_t(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute($t(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Nt,At,Mr,Ut,Vt,pr,wr,er,zr=b(()=>{Ft(),zt(),It(),Wt(),Nt=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},At=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Mr=(e,t)=>{if(e.length>1){let r=At(e,1),n=At(e,2),o=At(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),qe({starts:r,ends:n,axes:o})}else return t},Ut=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},Vt=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${yt("uniforms.input_shape","i",r.length)}; let steps_i = ${yt("uniforms.steps","i",r.length)}; let signs_i = ${yt("uniforms.signs","i",r.length)}; let starts_i = ${yt("uniforms.starts","i",r.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,pr=(e,t)=>{let r=e[0].dims,n=Ce.size(r),o=t.axes.length>0?Ce.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=At(e,4);i.forEach(te=>te!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map((te,V)=>Ut(te,V,r,o,i)),u=t.ends.map((te,V)=>Ut(te,V,r,o,i));if(o.length!==a.length||o.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==r.length)for(let te=0;teMath.sign(te));i.forEach((te,V,ie)=>{if(te<0){let pe=(u[V]-a[V])/te,be=a[V],De=be+pe*i[V];a[V]=De,u[V]=be,ie[V]=-te}});let h=r.slice(0);o.forEach((te,V)=>{h[te]=Math.ceil((u[te]-a[te])/i[te])});let k={dims:h,dataType:e[0].dataType},d=ft("output",e[0].dataType,h.length),S=Oe("input",e[0].dataType,e[0].dims.length),L=Ce.size(h),z=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:i.length}],D=[{type:12,data:L},{type:12,data:a},{type:6,data:p},{type:12,data:i},...Tt(e[0].dims,h)],re=te=>` ${te.registerUniforms(z).declareVariables(S,d)} ${Vt(S,d,r)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${d.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${d.setByOffset("global_idx",S.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:re,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:D})}},wr=(e,t)=>{Nt(e.inputs,t);let r=Mr(e.inputs,t);e.compute(pr(e.inputs,r),{inputs:[0]})},er=e=>{let t=e.starts,r=e.ends,n=e.axes;return qe({starts:t,ends:r,axes:n})}}),Ir,kr,Or,Xr,ps=b(()=>{Ft(),zt(),It(),Fs(),Wt(),Ir=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},kr=(e,t)=>{let r=e.inputs[0],n=r.dims,o=Ce.size(n),i=n.length,a=Ce.normalizeAxis(t.axis,i),u=aZe),h[a]=i-1,h[i-1]=a,p=e.compute(rs(r,h),{inputs:[r],outputs:[-1]})[0]):p=r;let k=p.dims,d=k[i-1],S=o/d,L=or(d),z=d/L,D=64;S===1&&(D=256);let re=(Pe,Ze)=>Ze===4?`max(max(${Pe}.x, ${Pe}.y), max(${Pe}.z, ${Pe}.w))`:Ze===2?`max(${Pe}.x, ${Pe}.y)`:Ze===3?`max(max(${Pe}.x, ${Pe}.y), ${Pe}.z)`:Pe,te=Oe("x",p.dataType,p.dims,L),V=ft("result",p.dataType,p.dims,L),ie=te.type.value,pe=Zt(p.dataType)==="f32"?`var threadMax = ${ie}(-3.402823e+38f);`:`var threadMax = ${ie}(-65504.0h);`,be=Pe=>` var rowMaxShared : ${ie}; var rowSumShared : ${ie}; var threadShared : array<${ie}, ${D}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ie} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ie}) { let index = row * row_stride + col; result[index] = value; } ${Pe.registerUniform("packedCols","i32").declareVariables(te,V)} ${Pe.mainStart(D)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${D}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${pe} 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 = ${ie}(${re("threadShared[0]",L)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ie}(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 = ${ie}(${Gr("threadShared[0]",L)}); } 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); } }`,De=e.compute({name:"Softmax",shaderCache:{hint:`${L};${D}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:S},programUniforms:[{type:6,data:z}]}),getShaderSource:be},{inputs:[p],outputs:[u?-1:0]})[0];u&&e.compute(rs(De,h),{inputs:[De]})},Or=(e,t)=>{Ir(e.inputs),kr(e,t)},Xr=e=>qe({axis:e.axis})}),Mo,ss,Ts,jn,ra,sa=b(()=>{Ft(),zt(),Wt(),Mo=e=>Array.from(e.getBigInt64Array(),Number),ss=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(Mo(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")},Ts=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Mo(e[1]),o=Ts(r,n),i=Ce.size(o),a=e[0].dataType,u=Oe("input",a,r.length),p=ft("output",a,o.length),h=k=>` const inputShape = ${u.indices(...r)}; ${k.registerUniform("output_size","u32").declareVariables(u,p)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; for (var i = 0; i < ${r.length}; i++) { let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; ${u.indicesSet("input_indices","i","input_dim_value")} } ${p.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...Tt(e[0].dims,o)]}),getShaderSource:h}},ra=e=>{ss(e.inputs),e.compute(jn(e.inputs),{inputs:[0]})}}),Un,Hc,yr,Br=b(()=>{Ft(),zt(),Wt(),Un=(e,t,r,n,o)=>{let i=ft("output_data",o,r.length,4),a=Oe("a_data",t[1].dataType,t[1].dims.length,4),u=Oe("b_data",t[2].dataType,t[2].dims.length,4),p=Oe("c_data",t[0].dataType,t[0].dims.length,4),h,k=(d,S,L)=>`select(${S}, ${d}, ${L})`;if(!n)h=i.setByOffset("global_idx",k(a.getByOffset("global_idx"),u.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let d=(S,L,z="")=>{let D=`a_data[index_a${L}][component_a${L}]`,re=`b_data[index_b${L}][component_b${L}]`,te=`bool(c_data[index_c${L}] & (0xffu << (component_c${L} * 8)))`;return` let output_indices${L} = ${i.offsetToIndices(`global_idx * 4u + ${L}u`)}; let offset_a${L} = ${a.broadcastedIndicesToOffset(`output_indices${L}`,i)}; let offset_b${L} = ${u.broadcastedIndicesToOffset(`output_indices${L}`,i)}; let offset_c${L} = ${p.broadcastedIndicesToOffset(`output_indices${L}`,i)}; let index_a${L} = offset_a${L} / 4u; let index_b${L} = offset_b${L} / 4u; let index_c${L} = offset_c${L} / 4u; let component_a${L} = offset_a${L} % 4u; let component_b${L} = offset_b${L} % 4u; let component_c${L} = offset_c${L} % 4u; ${S}[${L}] = ${z}(${k(D,re,te)}); `};o===9?h=` var data = vec4(0); ${d("data",0,"u32")} ${d("data",1,"u32")} ${d("data",2,"u32")} ${d("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` ${d("output_data[global_idx]",0)} ${d("output_data[global_idx]",1)} ${d("output_data[global_idx]",2)} ${d("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(p,a,u,i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`},Hc=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(Ce.areEqual(t,r)&&Ce.areEqual(r,n)),a=t,u=Ce.size(t);if(i){let h=gr.calcShape(gr.calcShape(t,r,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");a=h,u=Ce.size(a)}let p=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Un(h,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:p},...Tt(n,t,r,a)]})}},yr=e=>{e.compute(Hc(e.inputs))}}),zs,fn=b(()=>{qu(),jo(),ll(),Xu(),Qu(),Xl(),Yu(),tc(),Js(),sc(),ki(),nc(),ic(),ac(),dc(),Ud(),uc(),cc(),Di(),mc(),pu(),_1(),gc(),gu(),g1(),Wi(),bc(),w1(),y1(),b1(),M1(),Bo(),Te(),rt(),Ht(),zr(),ps(),du(),sa(),Fs(),si(),Br(),zs=new Map([["Abs",[pl]],["Acos",[hl]],["Acosh",[ml]],["Add",[ii]],["ArgMax",[el,oo]],["ArgMin",[Za,oo]],["Asin",[fl]],["Asinh",[Vo]],["Atan",[_l]],["Atanh",[gl]],["Attention",[No]],["AveragePool",[Mc,Au]],["BatchNormalization",[al]],["BiasAdd",[Wo]],["BiasSplitGelu",[jl]],["Cast",[wl,Go]],["Ceil",[bl]],["Clip",[Ko]],["Concat",[Zl,ui]],["Conv",[mo,Pi]],["ConvTranspose",[bd,gd]],["Cos",[Ml]],["Cosh",[Ho]],["CumSum",[vd,xd]],["DepthToSpace",[Pd,Cd]],["DequantizeLinear",[Sc,Ac]],["Div",[Wl]],["Einsum",[Ad,Id]],["Elu",[vl,On]],["Equal",[Vl]],["Erf",[xl]],["Exp",[Tl]],["Expand",[mn]],["FastGelu",[Ld]],["Floor",[qo]],["FusedConv",[mo,Pi]],["Gather",[Bd,lc]],["GatherElements",[bo,Hd]],["GatherBlockQuantized",[Ii,Gd]],["GatherND",[Nd,jd]],["Gelu",[El]],["Gemm",[Fi,Qd]],["GlobalAveragePool",[xc,vc]],["GlobalMaxPool",[Cc,Pc]],["Greater",[io]],["GreaterOrEqual",[ql]],["GridSample",[Bi,Ri]],["GroupQueryAttention",[cu]],["HardSigmoid",[Al,Qo]],["InstanceNormalization",[fc]],["LayerNormalization",[mu]],["LeakyRelu",[Pl,On]],["Less",[Hl]],["LessOrEqual",[li]],["Log",[zl]],["MatMul",[_u]],["MatMulNBits",[yu,Qi]],["MaxPool",[Tc,Ec]],["Mul",[ai]],["MultiHeadAttention",[ru,tu]],["Neg",[Cl]],["Not",[Xo]],["Pad",[Cu]],["Pow",[Gl]],["QuickGelu",[ri,On]],["Range",[Fc]],["Reciprocal",[kl]],["ReduceMin",[Lo]],["ReduceMean",[Ka]],["ReduceMax",[Xa]],["ReduceSum",[Ya]],["ReduceProd",[Qa]],["ReduceL1",[Ha]],["ReduceL2",[Do]],["ReduceLogSum",[Ja]],["ReduceLogSumExp",[qa]],["ReduceSumSquare",[zo]],["Relu",[$l]],["Resize",[f,H]],["RotaryEmbedding",[et]],["ScatterND",[Bc,zc]],["Sigmoid",[Sl]],["Sin",[Il]],["Sinh",[Ol]],["Slice",[wr,er]],["SkipLayerNormalization",[Jt]],["Split",[au,lu]],["Sqrt",[Fl]],["Softmax",[Or,Xr]],["Sub",[Kl]],["Tan",[Yo]],["Tanh",[Dl]],["ThresholdedRelu",[Ll,On]],["Tile",[ra]],["Transpose",[eo,va]],["Where",[yr]]])}),_n,na=b(()=>{Ge(),es(),Wt(),_n=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,o){Xe(e.programInfo.name);let i=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let h of t)u.push({binding:u.length,resource:{buffer:h.buffer}});for(let h of r)u.push({binding:u.length,resource:{buffer:h.buffer}});o&&u.push({binding:u.length,resource:o});let p=i.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,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(),Be(e.programInfo.name)}dispose(){}build(e,t){Xe(e.name);let r=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{r.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let o=wa(t,this.backend.device.limits),i=e.getShaderSource(o),a=`${n.join(` `)} ${o.additionalImplementations} ${i}`,u=r.createShaderModule({code:a,label:e.name});nr("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let p=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Be(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&r<=o&&n<=o)return[t,r,n];let i=t*r*n,a=Math.ceil(Math.sqrt(i));if(a>o){if(a=Math.ceil(Math.cbrt(i)),a>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),oa,ia,aa,qc,la,da=b(()=>{Ge(),Ft(),es(),$n(),mt(),fn(),na(),oa=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${oa(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},aa=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},qc=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]}},la=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r},o=i=>t.features.has(i)&&r.push(i)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups")&&o("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new qc(this.device),this.adapterInfo=new aa(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ht(this),this.programManager=new _n(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,pn(e.logLevel,!!e.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Xe(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let n=0;n"u"&&(this.queryTimeBase=S);let z=Number(S-this.queryTimeBase),D=Number(L-this.queryTimeBase);if(!Number.isSafeInteger(z)||!Number.isSafeInteger(D))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:k.map(re=>({dims:re.dims,dataType:hs(re.dataType)})),outputsMetadata:d.map(re=>({dims:re.dims,dataType:hs(re.dataType)})),kernelId:i,kernelType:u,kernelName:p,programName:h,startTime:z,endTime:D});else{let re="";k.forEach((V,ie)=>{re+=`input[${ie}]: [${V.dims}] | ${hs(V.dataType)}, `});let te="";d.forEach((V,ie)=>{te+=`output[${ie}]: [${V.dims}] | ${hs(V.dataType)}, `}),console.log(`[profiling] kernel "${i}|${u}|${p}|${h}" ${re}${te}execution time: ${D-z} ns`)}tt("GPU",`${h}::${S}::${L}`)}e.unmap(),this.pendingQueries.delete(e)}),Be()}run(e,t,r,n,o,i){Xe(e.name);let a=[];for(let V=0;Vie):r;if(k.length!==u.length)throw new Error(`Output size ${k.length} must be equal to ${u.length}.`);let d=[],S=[];for(let V=0;V=i)throw new Error(`Invalid output index: ${k[V]}`);if(k[V]===-3)continue;let ie=k[V]===-1,pe=k[V]===-2,be=ie||pe?o(u[V].dataType,u[V].dims):n(k[V],u[V].dataType,u[V].dims);if(d.push(be),be.data===0)continue;let De=this.gpuDataManager.get(be.data);if(!De)throw new Error(`no GPU data for output: ${be.data}`);if(ie&&this.temporaryData.push(De),pe){let Pe=this.kernelPersistentData.get(this.currentKernelId);Pe||(Pe=[],this.kernelPersistentData.set(this.currentKernelId,Pe)),Pe.push(De)}S.push(De)}if(a.length!==t.length||S.length!==d.length){if(S.length===0)return Be(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let L;if(h){let V=0,ie=[];h.forEach(Pe=>{let Ze=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Ze.length===0)return;let ct=Pe.type===10?2:4,Ct,Dt;Pe.type===10?(Dt=Ze.length>4?16:Ze.length>2?8:Ze.length*ct,Ct=Ze.length>4?16:ct*Ze.length):(Dt=Ze.length<=2?Ze.length*ct:16,Ct=16),V=Math.ceil(V/Dt)*Dt,ie.push(V);let St=Pe.type===10?8:4;V+=Ze.length>4?Math.ceil(Ze.length/St)*Ct:Ze.length*ct});let pe=16;V=Math.ceil(V/pe)*pe;let be=new ArrayBuffer(V);h.forEach((Pe,Ze)=>{let ct=ie[Ze],Ct=typeof Pe.data=="number"?[Pe.data]:Pe.data;if(Pe.type===6)new Int32Array(be,ct,Ct.length).set(Ct);else if(Pe.type===12)new Uint32Array(be,ct,Ct.length).set(Ct);else if(Pe.type===10)new Uint16Array(be,ct,Ct.length).set(Ct);else if(Pe.type===1)new Float32Array(be,ct,Ct.length).set(Ct);else throw new Error(`Unsupported uniform type: ${hs(Pe.type)}`)});let De=this.gpuDataManager.create(V,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(De.buffer,0,be,0,V),this.gpuDataManager.release(De.id),L={offset:0,size:V,buffer:De.buffer}}let z=this.programManager.normalizeDispatchGroupSize(p),D=z[1]===1&&z[2]===1,re=ia(e,t,D),te=this.programManager.getArtifact(re);if(te||(te=this.programManager.build(e,z),this.programManager.setArtifact(re,te),nr("info",()=>`[artifact] key: ${re}, programName: ${e.name}`)),h&&te.uniformVariablesInfo){if(h.length!==te.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${te.uniformVariablesInfo.length}, got ${h.length} in program "${te.programInfo.name}".`);for(let V=0;V`[ProgramManager] run "${e.name}" (key=${re}) with ${z[0]}x${z[1]}x${z[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let V={kernelId:this.currentKernelId,programName:te.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(V),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(V)}return this.programManager.run(te,a,S,z,L),Be(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let o=zs.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let i={kernelType:e,kernelName:n,kernelEntry:o[0],attributes:[o[1],r]};this.kernels.set(t,i)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let o=n.kernelType,i=n.kernelName,a=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${i}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),nr("info",()=>`[WebGPU] Start to run kernel "[${o}] ${i}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),a(t,u[1]),0}catch(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${i}" failed. ${h}`)),1}finally{p&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${o}] ${i}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let i=o.get(t),a=this.gpuDataManager.registerExternalBuffer(r,n,i);return o.set(t,[a,r]),a}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await Ie(this,e,t);return hn(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){nr("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){nr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){nr("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}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()}}}),ua,ca,pa,Wn,zu,Bu,Xc,tn,gs=b(()=>{es(),ua=1,ca=()=>ua++,pa=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Wn=(e,t)=>{let r=pa.get(e);if(!r)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*r/8):0},zu=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 Wn(this.dataType,this.tensorShape)}destroy(){nr("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((r,n)=>r===t[n])}},Bu=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Wn(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),r&&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 nr("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()}},Xc=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=ca();return this.tensorTrackersById.set(e,new Bu(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n){nr("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){nr("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let o=ca(),i=new zu({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(o,new Bu(this,i)),this.externalTensors.add(i),o}async getCachedTensor(e,t,r,n,o){let i=this.backend.currentSessionId;for(let[p,h]of this.freeTensors.entries())if(h.sameTypeAndShape(e,t)){nr("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=i,k}let a=this.backend.currentContext;nr("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await a.createTensor({dataType:e,shape:t,dimensions:t,usage:r,writable:n,readable:o});return new zu({sessionId:i,context:a,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},tn=(...e)=>new Xc(...e)}),v1,cp,pp,im=b(()=>{Ft(),kt(),$n(),gs(),es(),v1=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),cp=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},pp=class{constructor(e){this.tensorManager=tn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],pn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>cp(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(o=>o.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){nr("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n){let o=v1.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,o,r,n)}uploadTensor(e,t){if(!dt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");nr("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return hn(r,t)}}registerMLTensor(e,t,r){let n=v1.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(this.currentContext,e,n,r);return nr("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,r,n,o,i){if(!i)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let u=i.get(a);if(!u)throw new Error(`File with name ${a} not found in preloaded files.`);if(t+r>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=u.slice(t,t+r).buffer,h;switch(o.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return nr("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`),n.constant(o,h)}flush(){}}}),hp={};T(hp,{init:()=>fp});var Qc,mp,fp,am=b(()=>{Ft(),da(),es(),zt(),im(),Qc=class rm{constructor(t,r,n,o){this.module=t,this.dataType=r,this.data=n,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Ce.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=Ce.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=Ce.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=Ce.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Ce.size(t)!==Ce.size(this.dims))throw new Error("Invalid new shape");return new rm(this.module,this.dataType,this.data,t)}},mp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,o=r/e.PTR_SIZE,i=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*o++,i));let a=Number(e.getValue(n*o++,i));this.outputCount=Number(e.getValue(n*o++,i)),this.customDataOffset=Number(e.getValue(n*o++,"*")),this.customDataSize=Number(e.getValue(n*o++,i));let u=[];for(let p=0;ptypeof a=="number"?this.inputs[a]:a)??this.inputs,n=t?.outputs??[],o=(a,u,p)=>new Qc(this.module,u,this.output(a,p),p),i=(a,u)=>{let p=Zr(a,u);if(!p)throw new Error(`Unsupported data type: ${a}`);let h=p>0?this.backend.gpuDataManager.create(p).id:0;return new Qc(this.module,a,h,u)};return this.backend.run(e,r,n,o,i,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.PTR_SIZE,o=n===4?"i32":"i64",i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,o);for(let a=0;a{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new la;await i.initialize(r,n),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,u,p,h=!1)=>{if(h)nr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(u)}, size=${Number(p)}`),i.memcpy(Number(a),Number(u));else{nr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(u)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(p));i.upload(Number(u),k)}},async(a,u,p)=>{nr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${u}, size=${p}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(u)>>>0,Number(u+p)>>>0))},(a,u,p)=>i.createKernel(a,Number(u),p,t.UTF8ToString(t._JsepGetNodeName(Number(u)))),a=>i.releaseKernel(a),(a,u,p,h)=>{nr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${u}`);let k=new mp(t,i,Number(u));return i.computeKernel(Number(a),k,h)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new pp(r);o("webnn",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,u,p,h)=>i.ensureTensor(a,u,p,h),(a,u)=>{i.uploadTensor(a,u)},async(a,u)=>i.downloadTensor(a,u)])}}}),_p,x1,T1,Vn,gp,Yc,E1,P1,C1,k1,$1,S1,wp=b(()=>{Yn(),Jn(),Ft(),kt(),Us(),Tn(),_p=(e,t)=>{dt()._OrtInit(e,t)!==0&&sr("Can't initialize onnxruntime.")},x1=async e=>{_p(e.wasm.numThreads,Vs(e.logLevel))},T1=async(e,t)=>{{let r=(am(),x(hp)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",dt(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",dt(),e)}}},Vn=new Map,gp=e=>{let t=dt(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&sr("Can't get session input/output count.");let i=n===4?"i32":"i64";return[Number(t.getValue(o,i)),Number(t.getValue(o+n,i))]}finally{t.stackRestore(r)}},Yc=e=>{let t=dt(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},E1=async(e,t)=>{let r,n,o=dt();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Yc(e);let i=0,a=0,u=0,p=[],h=[],k=[];try{if([a,p]=xn(t),t?.externalData&&o.mountExternalData){let V=[];for(let ie of t.externalData){let pe=typeof ie=="string"?ie:ie.path;V.push(cn(typeof ie=="string"?ie:ie.data).then(be=>{o.mountExternalData(pe,be)}))}await Promise.all(V)}for(let V of t?.executionProviders??[])if((typeof V=="string"?V:V.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof V!="string"){let ie=V,pe=ie?.context,be=ie?.gpuDevice,De=ie?.deviceType,Pe=ie?.powerPreference;pe?o.currentContext=pe:be?o.currentContext=await o.jsepCreateMLContext(be):o.currentContext=await o.jsepCreateMLContext({deviceType:De,powerPreference:Pe})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&sr("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[d,S]=gp(i),L=!!t?.enableGraphCapture,z=[],D=[],re=[];for(let V=0;VV==="gpu-buffer"||V==="ml-tensor")&&(u=o._OrtCreateBinding(i),u===0&&sr("Can't create IO binding."),te={handle:u,outputPreferredLocations:re,outputPreferredLocationsEncoded:re.map(V=>un(V))}),Vn.set(i,[i,h,k,te,L,!1]),[i,z,D]}catch(d){throw h.forEach(S=>o._OrtFree(S)),k.forEach(S=>o._OrtFree(S)),u!==0&&o._OrtReleaseBinding(u)!==0&&sr("Can't release IO binding."),i!==0&&o._OrtReleaseSession(i)!==0&&sr("Can't release session."),d}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&sr("Can't release session options."),p.forEach(d=>o._free(d)),o.unmountExternalData?.()}},P1=e=>{let t=dt(),r=Vn.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,u]=r;a&&(u&&t._OrtClearBoundOutputs(a.handle)!==0&&sr("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&sr("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),o.forEach(p=>t._OrtFree(p)),i.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n)!==0&&sr("Can't release session."),Vn.delete(e)},C1=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=dt(),u=a.PTR_SIZE,p=e[0],h=e[1],k=e[3],d,S;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let D=e[2].gpuBuffer;S=Zr(Is(p),h);let re=a.jsepRegisterBuffer;if(!re)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');d=re(n,o,D,S)}else if(k==="ml-tensor"){let D=e[2].mlTensor;S=Zr(Is(p),h);let re=a.jsepRegisterMLTensor;if(!re)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');d=re(D,Is(p),h)}else{let D=e[2];if(Array.isArray(D)){S=u*D.length,d=a._malloc(S),r.push(d);for(let re=0;rea.setValue(z+te*u,re,u===4?"i32":"i64"));let D=a._OrtCreateTensor(Is(p),d,S,z,h.length,un(k));D===0&&sr(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(D)}finally{a.stackRestore(L)}},k1=async(e,t,r,n,o,i)=>{let a=dt(),u=a.PTR_SIZE,p=Vn.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],d=p[2],S=p[3],L=p[4],z=p[5],D=t.length,re=n.length,te=0,V=[],ie=[],pe=[],be=[],De=a.stackSave(),Pe=a.stackAlloc(D*u),Ze=a.stackAlloc(D*u),ct=a.stackAlloc(re*u),Ct=a.stackAlloc(re*u);try{a.jsepOnRunStart?.(h),[te,V]=Ss(i);for(let bt=0;btKr*Cr,1);Yt=hs(it);let gn=S?.outputPreferredLocations[n[bt]];if(Yt==="string"){if(gn==="gpu-buffer"||gn==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Kr=[];for(let Cr=0;Cr0){let Kr=a.jsepGetBuffer;if(!Kr)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Cr=Kr(qt),Yr=Zr(it,xr);if(Yr===void 0||!dn(Yt))throw new Error(`Unsupported data type: ${Yt}`);rr=!0,St.push([Yt,vr,{gpuBuffer:Cr,download:a.jsepCreateDownloader(Cr,Yr,Yt),dispose:()=>{a._OrtReleaseTensor(Gt)!==0&&sr("Can't release tensor.")}},"gpu-buffer"])}else if(gn==="ml-tensor"&&xr>0){let Kr=a.jsepEnsureTensor;if(!Kr)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Zr(it,xr)===void 0||!Gs(Yt))throw new Error(`Unsupported data type: ${Yt}`);let Cr=await Kr(qt,it,vr,!1);rr=!0,St.push([Yt,vr,{mlTensor:Cr,download:a.jsepCreateMLTensorDownloader(qt,Yt),dispose:()=>{a.jsepReleaseTensorId(qt),a._OrtReleaseTensor(Gt)}},"ml-tensor"])}else{let Kr=ln(Yt),Cr=new Kr(xr);new Uint8Array(Cr.buffer,Cr.byteOffset,Cr.byteLength).set(a.HEAPU8.subarray(qt,qt+Cr.byteLength)),St.push([Yt,vr,Cr,"cpu"])}}finally{a.stackRestore(jt),Yt==="string"&&qt&&a._free(qt),rr||a._OrtReleaseTensor(Gt)}}return S&&!L&&(a._OrtClearBoundOutputs(S.handle)!==0&&sr("Can't clear bound outputs."),Vn.set(e,[h,k,d,S,L,!1])),St}finally{a.stackRestore(De),ie.forEach(Dt=>a._OrtReleaseTensor(Dt)),pe.forEach(Dt=>a._OrtReleaseTensor(Dt)),be.forEach(Dt=>a._free(Dt)),te!==0&&a._OrtReleaseRunOptions(te),V.forEach(Dt=>a._free(Dt))}},$1=e=>{let t=dt(),r=Vn.get(e);if(!r)throw new Error("invalid session id");let n=r[0],o=t._OrtEndProfiling(n);o===0&&sr("Can't get an profile file name."),t._OrtFree(o)},S1=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Gn,Es,ha,Ru,Nu,Jc,A1,Zc,vo,xo,yp,bp,Mp,vp,xp,Tp,Ep,Pp,Cp=b(()=>{Ge(),wp(),kt(),bs(),Gn=()=>!!E.wasm.proxy&&typeof document<"u",ha=!1,Ru=!1,Nu=!1,Zc=new Map,vo=(e,t)=>{let r=Zc.get(e);r?r.push(t):Zc.set(e,[t])},xo=()=>{if(ha||!Ru||Nu||!Es)throw new Error("worker not ready")},yp=e=>{switch(e.data.type){case"init-wasm":ha=!1,e.data.err?(Nu=!0,A1[1](e.data.err)):(Ru=!0,A1[0]()),Jc&&(URL.revokeObjectURL(Jc),Jc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Zc.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},bp=async()=>{if(!Ru){if(ha)throw new Error("multiple calls to 'initWasm()' detected.");if(Nu)throw new Error("previous call to 'initWasm()' failed.");if(ha=!0,Gn())return new Promise((e,t)=>{Es?.terminate(),Rs().then(([r,n])=>{try{Es=n,Es.onerror=i=>t(i),Es.onmessage=yp,A1=[e,t];let o={type:"init-wasm",in:E};Es.postMessage(o),Jc=r}catch(o){t(o)}},t)});try{await ot(E.wasm),await x1(E),Ru=!0}catch(e){throw Nu=!0,e}finally{ha=!1}}},Mp=async e=>{if(Gn())return xo(),new Promise((t,r)=>{vo("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:E}};Es.postMessage(n)});await T1(E,e)},vp=async e=>Gn()?(xo(),new Promise((t,r)=>{vo("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Es.postMessage(n,[e.buffer])})):Yc(e),xp=async(e,t)=>{if(Gn()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xo(),new Promise((r,n)=>{vo("create",[r,n]);let o={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Es.postMessage(o,i)})}else return E1(e,t)},Tp=async e=>{if(Gn())return xo(),new Promise((t,r)=>{vo("release",[t,r]);let n={type:"release",in:e};Es.postMessage(n)});P1(e)},Ep=async(e,t,r,n,o,i)=>{if(Gn()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return xo(),new Promise((a,u)=>{vo("run",[a,u]);let p=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:i}};Es.postMessage(h,S1(p))})}else return k1(e,t,r,n,o,i)},Pp=async e=>{if(Gn())return xo(),new Promise((t,r)=>{vo("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Es.postMessage(n)});$1(e)}}),I1,kp,$p,lm=b(()=>{Ge(),Cp(),Ft(),Je(),Tn(),I1=(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()}`)}},kp=e=>{switch(e[3]){case"cpu":return new ue(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!dn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return ue.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!Gs(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return ue.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},$p=class{async fetchModelAndCopyToWasmMemory(e){return vp(await cn(e))}async loadModel(e,t){Xe();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await xp(r,t),Be()}async dispose(){return Tp(this.sessionId)}async run(e,t,r){Xe();let n=[],o=[];Object.entries(e).forEach(d=>{let S=d[0],L=d[1],z=this.inputNames.indexOf(S);if(z===-1)throw new Error(`invalid input '${S}'`);n.push(L),o.push(z)});let i=[],a=[];Object.entries(t).forEach(d=>{let S=d[0],L=d[1],z=this.outputNames.indexOf(S);if(z===-1)throw new Error(`invalid output '${S}'`);i.push(L),a.push(z)});let u=n.map((d,S)=>I1(d,()=>`input "${this.inputNames[o[S]]}"`)),p=i.map((d,S)=>d?I1(d,()=>`output "${this.outputNames[a[S]]}"`):null),h=await Ep(this.sessionId,o,u,a,p,r),k={};for(let d=0;dF1,initializeFlags:()=>O1,wasmBackend:()=>Ap});var O1,F1,Ap,dm=b(()=>{Ge(),Cp(),lm(),bs(),O1=()=>{if((typeof E.wasm.initTimeout!="number"||E.wasm.initTimeout<0)&&(E.wasm.initTimeout=0),E.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 E.wasm.proxy!="boolean"&&(E.wasm.proxy=!1),typeof E.wasm.trace!="boolean"&&(E.wasm.trace=!1),typeof E.wasm.numThreads!="number"||!Number.isInteger(E.wasm.numThreads)||E.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)E.wasm.numThreads=1;else{let e=typeof navigator>"u"?U("node:os").cpus().length:navigator.hardwareConcurrency;E.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},F1=class{async init(e){O1(),await bp(),await Mp(e)}async createInferenceSessionHandler(e,t){let r=new $p;return await r.loadModel(e,t),Promise.resolve(r)}},Ap=new F1});Ge(),Ge(),Ge();var um="1.21.0-dev.20241205-d27fecd3d3",cm=Ae;{let e=(dm(),x(Sp)).wasmBackend;Q("webgpu",e,5),Q("webnn",e,5),Q("cpu",e,10),Q("wasm",e,10)}Object.defineProperty(E.versions,"web",{value:um,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":(Me,v,s)=>{var _;s.r(v),s.d(v,{Tensor:()=>U.Tensor,createInferenceSession:()=>de,deviceToExecutionProviders:()=>Q,isONNXProxy:()=>q,isONNXTensor:()=>N});var A=s("./src/env.js"),j=s("?2ce3"),ee=s("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"),U=s("./node_modules/onnxruntime-common/dist/esm/index.js");const b=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 M,x;const P=Symbol.for("onnxruntime");if(P in globalThis)x=globalThis[P];else if(A.apis.IS_NODE_ENV){switch(x=j??(_||(_=s.t(j,2))),process.platform){case"win32":T.push("dml");break;case"linux":process.arch==="x64"&&T.push("cuda");break}T.push("cpu"),M=["cpu"]}else x=ee,A.apis.IS_WEBNN_AVAILABLE&&T.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),A.apis.IS_WEBGPU_AVAILABLE&&T.push("webgpu"),T.push("wasm"),M=["wasm"];const R=x.InferenceSession;function Q(B=null){if(!B)return M;switch(B){case"auto":return T;case"gpu":return T.filter(O=>["webgpu","cuda","dml","webnn-gpu"].includes(O))}if(T.includes(B))return[b[B]??B];throw new Error(`Unsupported device: "${B}". Should be one of: ${T.join(", ")}.`)}let ne=null;async function de(B,O,w){ne&&await ne;const $=R.create(B,O);ne??=$;const E=await $;return E.config=w,E}function N(B){return B instanceof x.Tensor}const K=x?.env;K?.wasm&&(K.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${A.env.version}/dist/`,K.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(K.wasm.numThreads=1)),K?.webgpu&&(K.webgpu.powerPreference="high-performance");function q(){return K?.wasm?.proxy}A.env.backends.onnx=K},"./src/base/feature_extraction_utils.js":(Me,v,s)=>{s.r(v),s.d(v,{FeatureExtractor:()=>ee,validate_audio_inputs:()=>U});var _=s("./src/utils/constants.js"),A=s("./src/utils/generic.js"),j=s("./src/utils/hub.js");class ee extends A.Callable{constructor(T){super(),this.config=T}static async from_pretrained(T,M){const x=await(0,j.getModelJSON)(T,_.FEATURE_EXTRACTOR_NAME,!0,M);return new this(x)}}function U(b,T){if(!(b instanceof Float32Array||b instanceof Float64Array))throw new Error(`${T} expects input to be a Float32Array or a Float64Array, but got ${b?.constructor?.name??typeof b} 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":(Me,v,s)=>{s.r(v),s.d(v,{ImageProcessor:()=>B,post_process_instance_segmentation:()=>q,post_process_object_detection:()=>P,post_process_panoptic_segmentation:()=>K,post_process_semantic_segmentation:()=>R});var _=s("./src/utils/generic.js"),A=s("./src/utils/tensor.js"),j=s("./src/utils/maths.js");s("./src/utils/image.js");var ee=s("./src/utils/core.js"),U=s("./src/utils/hub.js"),b=s("./src/utils/constants.js");function T(O,w,$=0,E=null){const Z=O/w;let J=(0,j.bankers_round)(Z)*w;return E!==null&&J>E&&(J=Math.floor(Z)*w),J<$&&(J=Math.ceil(Z)*w),J}function M([O,w],$){return[Math.max(Math.floor(O/$),1)*$,Math.max(Math.floor(w/$),1)*$]}function x([O,w,$,E]){return[O-$/2,w-E/2,O+$/2,w+E/2]}function P(O,w=.5,$=null,E=!1){const Z=O.logits,J=O.pred_boxes,[ae,me,ge]=Z.dims;if($!==null&&$.length!==ae)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Ee=[];for(let ve=0;vew&&Re.push(Qe)}else{let Qe=(0,j.max)(Se.data)[1];if(Qe===ge-1||(We=(0,j.softmax)(Se.data),We[Qe]Ue*Le[(oe+1)%2])),fe.boxes.push(at),fe.classes.push(Qe),fe.scores.push(We[Qe])}}Ee.push(fe)}return Ee}function R(O,w=null){const $=O.logits,E=$.dims[0];if(w!==null&&w.length!==E)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Z=[];for(let J=0;JLe[Re]&&(Le[Re]=Se[Re],fe[Re]=_e)}const W=new Array(me.dims[0]);for(let _e=0;_e_e!==void 0);Z.push({segmentation:ve,labels:ce})}return Z}function Q(O,w,$,E){const Z=[],J=[],ae=[];for(let me=0;me$&&(Z.push(Ee),J.push(fe),ae.push(ve))}return[Z,J,ae]}function ne(O,w,$,E=.5,Z=.8){const J=[];let ae=0,me=0;const ge=w[$].data;for(let ve=0;ve=E&&++me;let Ee=ae>0&&me>0;return Ee&&(Ee=ae/me>Z),[Ee,J]}function de(O,w,$,E,Z,J=null,ae=null){const[me,ge]=ae??O[0].dims,Ee=new A.Tensor("int32",new Int32Array(me*ge),[me,ge]),ve=[];if(ae!==null)for(let _e=0;_efe[We]&&(Le[We]=_e,fe[We]=Re[We])}let W=0;const ce=Ee.data;for(let _e=0;_e<$.length;++_e){const Se=$[_e],[Re,We]=ne(Le,O,_e,E,Z);if(Re){++W;for(const Qe of We)ce[Qe]=W;ve.push({id:W,label_id:Se,score:w[_e]})}}return[Ee,ve]}function N(O,w,$=28,E=3136,Z=1003520){if(O<$||w<$)throw new Error(`height:${O} or width:${w} must be larger than factor:${$}`);if(Math.max(O,w)/Math.min(O,w)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(O,w)/Math.min(O,w)}`);let J=Math.round(O/$)*$,ae=Math.round(w/$)*$;if(J*ae>Z){const me=Math.sqrt(O*w/Z);J=Math.floor(O/me/$)*$,ae=Math.floor(w/me/$)*$}else if(J*aeJ?Ee=Math.floor(J*ge/Z):J>Z&&(ge=Math.floor(Z*Ee/J)),await w.resize(Ee,ge,{resample:E}))}async crop_margin(w,$=200){const E=w.clone().grayscale(),Z=(0,j.min)(E.data)[0],ae=(0,j.max)(E.data)[0]-Z;if(ae===0)return w;const me=$/255;let ge=E.width,Ee=E.height,ve=0,Le=0;const fe=E.data;for(let W=0;Wthis.preprocess(J)));return{pixel_values:(0,A.stack)(E.map(J=>J.pixel_values),0),original_sizes:E.map(J=>J.original_size),reshaped_input_sizes:E.map(J=>J.reshaped_input_size)}}static async from_pretrained(w,$){const E=await(0,U.getModelJSON)(w,b.IMAGE_PROCESSOR_NAME,!0,$);return new this(E)}}},"./src/base/processing_utils.js":(Me,v,s)=>{s.r(v),s.d(v,{Processor:()=>ee});var _=s("./src/utils/constants.js"),A=s("./src/utils/generic.js"),j=s("./src/utils/hub.js");class ee extends A.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(b,T){super(),this.config=b,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(b,T={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(b,{tokenize:!1,...T})}batch_decode(...b){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...b)}async _call(b,...T){for(const M of[this.image_processor,this.feature_extractor,this.tokenizer])if(M)return M(b,...T);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(b,T){const[M,x]=await Promise.all([this.uses_processor_config?(0,j.getModelJSON)(b,_.PROCESSOR_NAME,!0,T):{},Promise.all(this.classes.filter(P=>P in this).map(async P=>{const R=await this[P].from_pretrained(b,T);return[P.replace(/_class$/,""),R]})).then(Object.fromEntries)]);return new this(M,x)}}},"./src/configs.js":(Me,v,s)=>{s.r(v),s.d(v,{AutoConfig:()=>T,PretrainedConfig:()=>b,getKeyValueShapes:()=>U});var _=s("./src/utils/core.js"),A=s("./src/utils/hub.js");async function j(M,x){return await(0,A.getModelJSON)(M,"config.json",!0,x)}function ee(M){const x={};let P={};switch(M.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":P=ee(M.text_config);break;case"moondream1":P=ee(M.phi_config);break;case"musicgen":P=ee(M.decoder);break;case"multi_modality":P=ee(M.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"phi":case"phi3":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":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"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":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 Q=ee(M.decoder),ne="num_decoder_layers"in Q,de=(0,_.pick)(M,["model_type","is_encoder_decoder"]);return ne?(de.num_decoder_layers=Q.num_decoder_layers,de.num_decoder_heads=Q.num_decoder_heads,de.decoder_hidden_size=Q.decoder_hidden_size,de.num_encoder_layers=Q.num_encoder_layers,de.num_encoder_heads=Q.num_encoder_heads,de.encoder_hidden_size=Q.encoder_hidden_size):(de.num_layers=Q.num_layers,de.num_heads=Q.num_heads,de.hidden_size=Q.hidden_size),de}const R={...P,...(0,_.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const Q in x)R[Q]=M[x[Q]];return R}function U(M,{prefix:x="past_key_values",batch_size:P=1}={}){const R={},Q=M.normalized_config;if(Q.is_encoder_decoder&&"num_encoder_heads"in Q&&"num_decoder_heads"in Q){const ne=Q.encoder_dim_kv??Q.encoder_hidden_size/Q.num_encoder_heads,de=Q.decoder_dim_kv??Q.decoder_hidden_size/Q.num_decoder_heads,N=[P,Q.num_encoder_heads,0,ne],K=[P,Q.num_decoder_heads,0,de];for(let q=0;q{s.r(v),s.d(v,{apis:()=>de,env:()=>w});var _=s("?569f"),A=s("?3f59"),j=s("?154a");const ee="3.1.2",U=typeof window<"u"&&typeof window.document<"u",b=typeof self<"u"&&self.constructor?.name==="DedicatedWorkerGlobalScope",T=typeof self<"u"&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,x=typeof navigator<"u"&&"ml"in navigator,P=typeof process<"u",R=P&&process?.release?.name==="node",Q=!$(_),ne=!$(A),de=Object.freeze({IS_BROWSER_ENV:U,IS_WEBWORKER_ENV:b,IS_WEB_CACHE_AVAILABLE:T,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:x,IS_PROCESS_AVAILABLE:P,IS_NODE_ENV:R,IS_FS_AVAILABLE:Q,IS_PATH_AVAILABLE:ne}),N=Q&≠let K="./";if(N){const E=Object(import.meta).url;E?K=A.dirname(A.dirname(j.fileURLToPath(E))):typeof __dirname<"u"&&(K=A.dirname(__dirname))}const q=N?A.join(K,"/.cache/"):null,B="/models/",O=N?A.join(K,B):B,w={version:ee,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(U||b),localModelPath:O,useFS:Q,useBrowserCache:T,useFSCache:Q,cacheDir:q,useCustomCache:!1,customCache:null};function $(E){return Object.keys(E).length===0}},"./src/generation/configuration_utils.js":(Me,v,s)=>{s.r(v),s.d(v,{GenerationConfig:()=>A});var _=s("./src/utils/core.js");class A{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(ee){Object.assign(this,(0,_.pick)(ee,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Me,v,s)=>{s.r(v),s.d(v,{ClassifierFreeGuidanceLogitsProcessor:()=>N,ForcedBOSTokenLogitsProcessor:()=>b,ForcedEOSTokenLogitsProcessor:()=>T,LogitsProcessor:()=>j,LogitsProcessorList:()=>U,LogitsWarper:()=>ee,MinLengthLogitsProcessor:()=>Q,MinNewTokensLengthLogitsProcessor:()=>ne,NoBadWordsLogitsProcessor:()=>de,NoRepeatNGramLogitsProcessor:()=>P,RepetitionPenaltyLogitsProcessor:()=>R,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>K,TopKLogitsWarper:()=>B,TopPLogitsWarper:()=>q,WhisperTimeStampLogitsProcessor:()=>x});var _=s("./src/utils/generic.js");s("./src/utils/tensor.js");var A=s("./src/utils/maths.js");class j extends _.Callable{_call(w,$){throw Error("`_call` should be implemented in a subclass")}}class ee extends _.Callable{_call(w,$){throw Error("`_call` should be implemented in a subclass")}}class U extends _.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,$){let E=$;for(const Z of this.processors)E=Z(w,E);return E}[Symbol.iterator](){return this.processors.values()}}class b extends j{constructor(w){super(),this.bos_token_id=w}_call(w,$){for(let E=0;E=1&&J[J.length-1]>=this.timestamp_begin,me=J.length<2||J[J.length-2]>=this.timestamp_begin;if(ae&&(me?Z.subarray(this.timestamp_begin).fill(-1/0):Z.subarray(0,this.eos_token_id).fill(-1/0)),w[E].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Le=this.timestamp_begin+this.max_initial_timestamp_index;Z.subarray(Le+1).fill(-1/0)}const ge=(0,A.log_softmax)(Z),Ee=Math.log(ge.subarray(this.timestamp_begin).map(Math.exp).reduce((Le,fe)=>Le+fe)),ve=(0,A.max)(ge.subarray(0,this.timestamp_begin))[0];Ee>ve&&Z.subarray(0,this.timestamp_begin).fill(-1/0)}return $}}class P extends j{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const $=w.length,E=[];for(let J=0;J<$+1-this.no_repeat_ngram_size;++J){const ae=[];for(let me=0;me1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,$){if($.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 ${$.dims[0]} for the logits and ${w.length} for the input ids.`);const E=w.length,Z=$.slice([0,E],null),J=$.slice([E,$.dims[0]],null);for(let ae=0;ae1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(E)||E<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${E}`);this.top_p=w,this.filter_value=$,this.min_tokens_to_keep=E}}class B extends ee{constructor(w,{filter_value:$=-1/0,min_tokens_to_keep:E=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,E),this.filter_value=$}}},"./src/generation/logits_sampler.js":(Me,v,s)=>{s.r(v),s.d(v,{LogitsSampler:()=>ee});var _=s("./src/utils/generic.js"),A=s("./src/utils/tensor.js"),j=s("./src/utils/maths.js");s("./src/generation/configuration_utils.js");class ee extends _.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,P){let R=x.dims.at(-1),Q=x.data;if(P===-1)Q=Q.slice(-R);else{let ne=P*R;Q=Q.slice(ne,ne+R)}return Q}randomSelect(x){let P=0;for(let Q=0;Q1)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 U(x)}}class U extends ee{async sample(x){const P=(0,j.max)(x.data)[1];return[[BigInt(P),0]]}}class b extends ee{async sample(x){let P=x.dims.at(-1);this.generation_config.top_k>0&&(P=Math.min(this.generation_config.top_k,P));const[R,Q]=await(0,A.topk)(x,P),ne=(0,j.softmax)(R.data);return Array.from({length:this.generation_config.num_beams},()=>{const de=this.randomSelect(ne);return[Q.data[de],Math.log(ne[de])]})}}class T extends ee{async sample(x){let P=x.dims.at(-1);this.generation_config.top_k>0&&(P=Math.min(this.generation_config.top_k,P));const[R,Q]=await(0,A.topk)(x,P),ne=(0,j.softmax)(R.data);return Array.from({length:this.generation_config.num_beams},(de,N)=>[Q.data[N],Math.log(ne[N])])}}},"./src/generation/stopping_criteria.js":(Me,v,s)=>{s.r(v),s.d(v,{EosTokenCriteria:()=>U,InterruptableStoppingCriteria:()=>b,MaxLengthCriteria:()=>ee,StoppingCriteria:()=>A,StoppingCriteriaList:()=>j});var _=s("./src/utils/generic.js");class A extends _.Callable{_call(M,x){throw Error("StoppingCriteria needs to be subclassed")}}class j extends _.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof j?M=M.criteria:M instanceof A&&(M=[M]),this.criteria.push(...M)}_call(M,x){const P=new Array(M.length).fill(!1);for(const R of this.criteria){const Q=R(M,x);for(let ne=0;nex.length>=this.max_length)}}class U extends A{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,x){return M.map(P=>{const R=P.at(-1);return this.eos_token_id.some(Q=>R==Q)})}}class b extends A{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,x){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Me,v,s)=>{s.r(v),s.d(v,{BaseStreamer:()=>ee,TextStreamer:()=>b,WhisperTextStreamer:()=>T});var _=s("./src/utils/core.js"),A=s("./src/tokenizers.js"),j=s("./src/env.js");class ee{put(x){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const U=j.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class b extends ee{constructor(x,{skip_prompt:P=!1,callback_function:R=null,token_callback_function:Q=null,decode_kwargs:ne={},...de}={}){super(),this.tokenizer=x,this.skip_prompt=P,this.callback_function=R??U,this.token_callback_function=Q,this.decode_kwargs={...ne,...de},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 P=x[0];this.token_callback_function?.(P),this.token_cache=(0,_.mergeArrays)(this.token_cache,P);const R=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let Q;R.endsWith(` `)?(Q=R.slice(this.print_len),this.token_cache=[],this.print_len=0):R.length>0&&(0,A.is_chinese_char)(R.charCodeAt(R.length-1))?(Q=R.slice(this.print_len),this.print_len+=Q.length):(Q=R.slice(this.print_len,R.lastIndexOf(" ")+1),this.print_len+=Q.length),this.on_finalized_text(Q,!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,P){x.length>0&&this.callback_function?.(x),P&&this.callback_function===U&&j.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}}class T extends b{constructor(x,{skip_prompt:P=!1,callback_function:R=null,token_callback_function:Q=null,on_chunk_start:ne=null,on_chunk_end:de=null,on_finalize:N=null,time_precision:K=.02,skip_special_tokens:q=!0,decode_kwargs:B={}}={}){super(x,{skip_prompt:P,callback_function:R,token_callback_function:Q,decode_kwargs:{skip_special_tokens:q,...B}}),this.timestamp_begin=x.timestamp_begin,this.on_chunk_start=ne,this.on_chunk_end=de,this.on_finalize=N,this.time_precision=K,this.waiting_for_timestamp=!1}put(x){if(x.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const P=x[0];if(P.length===1){const R=Number(P[0])-this.timestamp_begin;if(R>=0){const Q=R*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(Q):this.on_chunk_start?.(Q),this.waiting_for_timestamp=!this.waiting_for_timestamp,x=[[]]}}return super.put(x)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(Me,v,s)=>{s.r(v),s.d(v,{ASTForAudioClassification:()=>Co,ASTModel:()=>ya,ASTPreTrainedModel:()=>Wt,AlbertForMaskedLM:()=>nr,AlbertForQuestionAnswering:()=>kn,AlbertForSequenceClassification:()=>pn,AlbertModel:()=>Cn,AlbertPreTrainedModel:()=>Os,AutoModel:()=>Iu,AutoModelForAudioClassification:()=>Lc,AutoModelForAudioFrameClassification:()=>Bc,AutoModelForCTC:()=>Dc,AutoModelForCausalLM:()=>Cc,AutoModelForDepthEstimation:()=>jc,AutoModelForDocumentQuestionAnswering:()=>M1,AutoModelForImageClassification:()=>Sc,AutoModelForImageFeatureExtraction:()=>Vc,AutoModelForImageMatting:()=>Rc,AutoModelForImageSegmentation:()=>Ac,AutoModelForImageToImage:()=>Nc,AutoModelForMaskGeneration:()=>b1,AutoModelForMaskedLM:()=>w1,AutoModelForNormalEstimation:()=>Uc,AutoModelForObjectDetection:()=>Oc,AutoModelForPoseEstimation:()=>Wc,AutoModelForQuestionAnswering:()=>kc,AutoModelForSemanticSegmentation:()=>y1,AutoModelForSeq2SeqLM:()=>Ou,AutoModelForSequenceClassification:()=>vc,AutoModelForSpeechSeq2Seq:()=>Tc,AutoModelForTextToSpectrogram:()=>Ec,AutoModelForTextToWaveform:()=>Pc,AutoModelForTokenClassification:()=>xc,AutoModelForUniversalSegmentation:()=>Ic,AutoModelForVision2Seq:()=>$c,AutoModelForXVector:()=>zc,AutoModelForZeroShotObjectDetection:()=>Fc,BartForConditionalGeneration:()=>Ke,BartForSequenceClassification:()=>ht,BartModel:()=>Ie,BartPretrainedModel:()=>we,BaseModelOutput:()=>Ne,BeitForImageClassification:()=>Kl,BeitModel:()=>Gl,BeitPreTrainedModel:()=>ai,BertForMaskedLM:()=>tt,BertForQuestionAnswering:()=>Be,BertForSequenceClassification:()=>He,BertForTokenClassification:()=>Xe,BertModel:()=>ke,BertPreTrainedModel:()=>ue,BlenderbotForConditionalGeneration:()=>Er,BlenderbotModel:()=>Ce,BlenderbotPreTrainedModel:()=>gr,BlenderbotSmallForConditionalGeneration:()=>ds,BlenderbotSmallModel:()=>Rr,BlenderbotSmallPreTrainedModel:()=>jr,BloomForCausalLM:()=>Ml,BloomModel:()=>bl,BloomPreTrainedModel:()=>Ko,CLIPModel:()=>ka,CLIPPreTrainedModel:()=>qs,CLIPSegForImageSegmentation:()=>ro,CLIPSegModel:()=>Ba,CLIPSegPreTrainedModel:()=>is,CLIPTextModel:()=>Ku,CLIPTextModelWithProjection:()=>$a,CLIPVisionModel:()=>_s,CLIPVisionModelWithProjection:()=>Sa,CamembertForMaskedLM:()=>ns,CamembertForQuestionAnswering:()=>an,CamembertForSequenceClassification:()=>Bs,CamembertForTokenClassification:()=>Cs,CamembertModel:()=>Hr,CamembertPreTrainedModel:()=>br,CausalLMOutput:()=>en,CausalLMOutputWithPast:()=>Kc,ChineseCLIPModel:()=>Da,ChineseCLIPPreTrainedModel:()=>Fa,ClapAudioModelWithProjection:()=>Xd,ClapModel:()=>cc,ClapPreTrainedModel:()=>bo,ClapTextModelWithProjection:()=>qd,CodeGenForCausalLM:()=>Ya,CodeGenModel:()=>Qa,CodeGenPreTrainedModel:()=>Lo,CohereForCausalLM:()=>ol,CohereModel:()=>jo,CoherePreTrainedModel:()=>No,ConvBertForMaskedLM:()=>Ge,ConvBertForQuestionAnswering:()=>wt,ConvBertForSequenceClassification:()=>Je,ConvBertForTokenClassification:()=>nt,ConvBertModel:()=>Ae,ConvBertPreTrainedModel:()=>he,ConvNextForImageClassification:()=>co,ConvNextModel:()=>ud,ConvNextPreTrainedModel:()=>dd,ConvNextV2ForImageClassification:()=>Pi,ConvNextV2Model:()=>po,ConvNextV2PreTrainedModel:()=>Ei,DPTForDepthEstimation:()=>rd,DPTModel:()=>yi,DPTPreTrainedModel:()=>wi,DebertaForMaskedLM:()=>ys,DebertaForQuestionAnswering:()=>$s,DebertaForSequenceClassification:()=>ks,DebertaForTokenClassification:()=>bs,DebertaModel:()=>Rs,DebertaPreTrainedModel:()=>Ot,DebertaV2ForMaskedLM:()=>Ms,DebertaV2ForQuestionAnswering:()=>ot,DebertaV2ForSequenceClassification:()=>Ns,DebertaV2ForTokenClassification:()=>os,DebertaV2Model:()=>ls,DebertaV2PreTrainedModel:()=>Jr,DecisionTransformerModel:()=>iu,DecisionTransformerPreTrainedModel:()=>ou,DeiTForImageClassification:()=>Ys,DeiTModel:()=>ci,DeiTPreTrainedModel:()=>Ds,DepthAnythingForDepthEstimation:()=>bi,DepthAnythingPreTrainedModel:()=>lo,DepthProForDepthEstimation:()=>Ln,DepthProPreTrainedModel:()=>Mi,DetrForObjectDetection:()=>ql,DetrForSegmentation:()=>li,DetrModel:()=>Hl,DetrObjectDetectionOutput:()=>Xl,DetrPreTrainedModel:()=>io,DetrSegmentationOutput:()=>Ql,Dinov2ForImageClassification:()=>pd,Dinov2Model:()=>cd,Dinov2PreTrainedModel:()=>ho,DistilBertForMaskedLM:()=>Us,DistilBertForQuestionAnswering:()=>sr,DistilBertForSequenceClassification:()=>cr,DistilBertForTokenClassification:()=>js,DistilBertModel:()=>kt,DistilBertPreTrainedModel:()=>dt,DonutSwinModel:()=>ld,DonutSwinPreTrainedModel:()=>ad,EfficientNetForImageClassification:()=>eu,EfficientNetModel:()=>Zd,EfficientNetPreTrainedModel:()=>Li,ElectraForMaskedLM:()=>tr,ElectraForQuestionAnswering:()=>Sr,ElectraForSequenceClassification:()=>Tr,ElectraForTokenClassification:()=>mr,ElectraModel:()=>Qt,ElectraPreTrainedModel:()=>pt,EsmForMaskedLM:()=>Mn,EsmForSequenceClassification:()=>Ws,EsmForTokenClassification:()=>vn,EsmModel:()=>Yn,EsmPreTrainedModel:()=>Ss,FalconForCausalLM:()=>Hd,FalconModel:()=>Kd,FalconPreTrainedModel:()=>Oi,FastViTForImageClassification:()=>zl,FastViTModel:()=>Ll,FastViTPreTrainedModel:()=>ti,Florence2ForConditionalGeneration:()=>Ta,Florence2PreTrainedModel:()=>xa,GLPNForDepthEstimation:()=>ec,GLPNModel:()=>id,GLPNPreTrainedModel:()=>Ti,GPT2LMHeadModel:()=>Ra,GPT2Model:()=>us,GPT2PreTrainedModel:()=>so,GPTBigCodeForCausalLM:()=>Xa,GPTBigCodeModel:()=>qa,GPTBigCodePreTrainedModel:()=>Do,GPTJForCausalLM:()=>Ha,GPTJModel:()=>Ka,GPTJPreTrainedModel:()=>as,GPTNeoForCausalLM:()=>Wa,GPTNeoModel:()=>Ua,GPTNeoPreTrainedModel:()=>Oo,GPTNeoXForCausalLM:()=>Ga,GPTNeoXModel:()=>Va,GPTNeoXPreTrainedModel:()=>Fo,Gemma2ForCausalLM:()=>ul,Gemma2Model:()=>dl,Gemma2PreTrainedModel:()=>ll,GemmaForCausalLM:()=>al,GemmaModel:()=>il,GemmaPreTrainedModel:()=>Uo,GraniteForCausalLM:()=>nl,GraniteModel:()=>In,GranitePreTrainedModel:()=>Ro,GroupViTModel:()=>ei,GroupViTPreTrainedModel:()=>Zo,HieraForImageClassification:()=>pi,HieraModel:()=>ed,HieraPreTrainedModel:()=>Ur,HubertForCTC:()=>Od,HubertForSequenceClassification:()=>Fd,HubertModel:()=>Ai,HubertPreTrainedModel:()=>oc,IJepaForImageClassification:()=>kl,IJepaModel:()=>Cl,IJepaPreTrainedModel:()=>Xo,Idefics3ForConditionalGeneration:()=>So,Idefics3PreTrainedModel:()=>Ca,ImageMattingOutput:()=>Du,JAISLMHeadModel:()=>ja,JAISModel:()=>Na,JAISPreTrainedModel:()=>Io,JinaCLIPModel:()=>La,JinaCLIPPreTrainedModel:()=>to,JinaCLIPTextModel:()=>za,JinaCLIPVisionModel:()=>Hu,LlamaForCausalLM:()=>Bo,LlamaModel:()=>Ja,LlamaPreTrainedModel:()=>zo,LlavaForConditionalGeneration:()=>eo,LlavaOnevisionForConditionalGeneration:()=>va,LlavaPreTrainedModel:()=>rs,LongT5ForConditionalGeneration:()=>xe,LongT5Model:()=>Sn,LongT5PreTrainedModel:()=>Ks,M2M100ForConditionalGeneration:()=>bd,M2M100Model:()=>yd,M2M100PreTrainedModel:()=>_o,MBartForCausalLM:()=>Xt,MBartForConditionalGeneration:()=>qe,MBartForSequenceClassification:()=>It,MBartModel:()=>Mt,MBartPreTrainedModel:()=>mt,MPNetForMaskedLM:()=>Vs,MPNetForQuestionAnswering:()=>un,MPNetForSequenceClassification:()=>dn,MPNetForTokenClassification:()=>Gs,MPNetModel:()=>ln,MPNetPreTrainedModel:()=>Zr,MT5ForConditionalGeneration:()=>le,MT5Model:()=>Y,MT5PreTrainedModel:()=>y,MarianMTModel:()=>wd,MarianModel:()=>gd,MarianPreTrainedModel:()=>fo,MaskFormerForInstanceSegmentation:()=>od,MaskFormerModel:()=>xi,MaskFormerPreTrainedModel:()=>vi,MaskedLMOutput:()=>Wr,MgpstrForSceneTextRecognition:()=>uu,MgpstrModelOutput:()=>lu,MgpstrPreTrainedModel:()=>du,MistralForCausalLM:()=>Vd,MistralModel:()=>Wd,MistralPreTrainedModel:()=>Ud,MobileBertForMaskedLM:()=>Jn,MobileBertForQuestionAnswering:()=>hs,MobileBertForSequenceClassification:()=>Is,MobileBertModel:()=>xn,MobileBertPreTrainedModel:()=>As,MobileLLMForCausalLM:()=>el,MobileLLMModel:()=>Za,MobileLLMPreTrainedModel:()=>no,MobileNetV1ForImageClassification:()=>qr,MobileNetV1Model:()=>mc,MobileNetV1PreTrainedModel:()=>Ri,MobileNetV2ForImageClassification:()=>ji,MobileNetV2Model:()=>tu,MobileNetV2PreTrainedModel:()=>Ni,MobileNetV3ForImageClassification:()=>ru,MobileNetV3Model:()=>Rn,MobileNetV3PreTrainedModel:()=>Ui,MobileNetV4ForImageClassification:()=>nu,MobileNetV4Model:()=>su,MobileNetV4PreTrainedModel:()=>Wi,MobileViTForImageClassification:()=>Nl,MobileViTModel:()=>si,MobileViTPreTrainedModel:()=>ri,MobileViTV2ForImageClassification:()=>Qu,MobileViTV2Model:()=>jl,MobileViTV2PreTrainedModel:()=>ni,ModelOutput:()=>Ve,Moondream1ForConditionalGeneration:()=>Fs,MptForCausalLM:()=>vl,MptModel:()=>On,MptPreTrainedModel:()=>Ho,MultiModalityCausalLM:()=>au,MultiModalityPreTrainedModel:()=>Vi,MusicgenForCausalLM:()=>hc,MusicgenForConditionalGeneration:()=>Bi,MusicgenModel:()=>pc,MusicgenPreTrainedModel:()=>zi,NomicBertModel:()=>lt,NomicBertPreTrainedModel:()=>st,OPTForCausalLM:()=>Tl,OPTModel:()=>xl,OPTPreTrainedModel:()=>Fn,Olmo2ForCausalLM:()=>sl,Olmo2Model:()=>rl,Olmo2PreTrainedModel:()=>An,OlmoForCausalLM:()=>tl,OlmoModel:()=>qu,OlmoPreTrainedModel:()=>oo,OpenELMForCausalLM:()=>cl,OpenELMModel:()=>Xu,OpenELMPreTrainedModel:()=>Wo,OwlViTForObjectDetection:()=>cs,OwlViTModel:()=>Ul,OwlViTPreTrainedModel:()=>oi,Owlv2ForObjectDetection:()=>Vl,Owlv2Model:()=>Wl,Owlv2PreTrainedModel:()=>ii,PaliGemmaForConditionalGeneration:()=>Pa,PaliGemmaPreTrainedModel:()=>Ea,PatchTSMixerForPrediction:()=>hu,PatchTSMixerModel:()=>Hi,PatchTSMixerPreTrainedModel:()=>pu,PatchTSTForPrediction:()=>cu,PatchTSTModel:()=>Ki,PatchTSTPreTrainedModel:()=>Gi,Phi3ForCausalLM:()=>yl,Phi3Model:()=>wl,Phi3PreTrainedModel:()=>Go,PhiForCausalLM:()=>gl,PhiModel:()=>_l,PhiPreTrainedModel:()=>Vo,PreTrainedModel:()=>oe,PretrainedMixin:()=>fr,PvtForImageClassification:()=>Il,PvtModel:()=>Al,PvtPreTrainedModel:()=>Qo,PyAnnoteForAudioFrameClassification:()=>Ed,PyAnnoteModel:()=>Td,PyAnnotePreTrainedModel:()=>Ci,QuestionAnsweringModelOutput:()=>Vr,Qwen2ForCausalLM:()=>hl,Qwen2Model:()=>pl,Qwen2PreTrainedModel:()=>ir,Qwen2VLForConditionalGeneration:()=>fl,Qwen2VLPreTrainedModel:()=>ml,RTDetrForObjectDetection:()=>Jl,RTDetrModel:()=>Yl,RTDetrObjectDetectionOutput:()=>Zl,RTDetrPreTrainedModel:()=>di,ResNetForImageClassification:()=>Dn,ResNetModel:()=>Ju,ResNetPreTrainedModel:()=>hi,RoFormerForMaskedLM:()=>gt,RoFormerForQuestionAnswering:()=>X,RoFormerForSequenceClassification:()=>I,RoFormerForTokenClassification:()=>se,RoFormerModel:()=>ut,RoFormerPreTrainedModel:()=>xt,RobertaForMaskedLM:()=>ms,RobertaForQuestionAnswering:()=>Tt,RobertaForSequenceClassification:()=>Zt,RobertaForTokenClassification:()=>dr,RobertaModel:()=>Lr,RobertaPreTrainedModel:()=>zt,SamImageSegmentationOutput:()=>_d,SamModel:()=>fd,SamPreTrainedModel:()=>md,SapiensForDepthEstimation:()=>Zu,SapiensForNormalEstimation:()=>nd,SapiensForSemanticSegmentation:()=>sd,SapiensPreTrainedModel:()=>uo,SegformerForImageClassification:()=>xs,SegformerForSemanticSegmentation:()=>Zs,SegformerModel:()=>vs,SegformerPreTrainedModel:()=>Di,Seq2SeqLMOutput:()=>Gc,SequenceClassifierOutput:()=>Kt,SiglipModel:()=>Aa,SiglipPreTrainedModel:()=>Ao,SiglipTextModel:()=>Ia,SiglipVisionModel:()=>Oa,SpeechT5ForSpeechToText:()=>Bd,SpeechT5ForTextToSpeech:()=>dc,SpeechT5HifiGan:()=>Rd,SpeechT5Model:()=>lc,SpeechT5PreTrainedModel:()=>yo,SqueezeBertForMaskedLM:()=>Tn,SqueezeBertForQuestionAnswering:()=>Pn,SqueezeBertForSequenceClassification:()=>En,SqueezeBertModel:()=>cn,SqueezeBertPreTrainedModel:()=>Ft,StableLmForCausalLM:()=>Jd,StableLmModel:()=>Yd,StableLmPreTrainedModel:()=>Ls,Starcoder2ForCausalLM:()=>uc,Starcoder2Model:()=>Gd,Starcoder2PreTrainedModel:()=>Ii,Swin2SRForImageSuperResolution:()=>gi,Swin2SRModel:()=>_i,Swin2SRPreTrainedModel:()=>fi,SwinForImageClassification:()=>td,SwinModel:()=>mi,SwinPreTrainedModel:()=>ao,T5ForConditionalGeneration:()=>$n,T5Model:()=>hn,T5PreTrainedModel:()=>es,TableTransformerForObjectDetection:()=>Xs,TableTransformerModel:()=>Yu,TableTransformerObjectDetectionOutput:()=>Qs,TableTransformerPreTrainedModel:()=>ui,TokenClassifierOutput:()=>Nr,TrOCRForCausalLM:()=>jd,TrOCRPreTrainedModel:()=>Nd,UniSpeechForCTC:()=>zn,UniSpeechForSequenceClassification:()=>$i,UniSpeechModel:()=>go,UniSpeechPreTrainedModel:()=>ki,UniSpeechSatForAudioFrameClassification:()=>Si,UniSpeechSatForCTC:()=>$d,UniSpeechSatForSequenceClassification:()=>Sd,UniSpeechSatModel:()=>kd,UniSpeechSatPreTrainedModel:()=>Bn,ViTForImageClassification:()=>Pl,ViTMAEModel:()=>Fl,ViTMAEPreTrainedModel:()=>Ol,ViTMSNForImageClassification:()=>Dl,ViTMSNModel:()=>Jo,ViTMSNPreTrainedModel:()=>Yo,ViTModel:()=>El,ViTPreTrainedModel:()=>qo,VisionEncoderDecoderModel:()=>$o,VitMatteForImageMatting:()=>Rl,VitMattePreTrainedModel:()=>Bl,VitPoseForPoseEstimation:()=>Sl,VitPosePreTrainedModel:()=>$l,VitsModel:()=>Fi,VitsModelOutput:()=>Lu,VitsPreTrainedModel:()=>Qd,Wav2Vec2BertForCTC:()=>Id,Wav2Vec2BertForSequenceClassification:()=>nc,Wav2Vec2BertModel:()=>Ad,Wav2Vec2BertPreTrainedModel:()=>wo,Wav2Vec2ForAudioFrameClassification:()=>sc,Wav2Vec2ForCTC:()=>vd,Wav2Vec2ForSequenceClassification:()=>xd,Wav2Vec2Model:()=>Md,Wav2Vec2PreTrainedModel:()=>Js,WavLMForAudioFrameClassification:()=>zd,WavLMForCTC:()=>Dd,WavLMForSequenceClassification:()=>Ld,WavLMForXVector:()=>ac,WavLMModel:()=>ic,WavLMPreTrainedModel:()=>mn,WeSpeakerResNetModel:()=>Cd,WeSpeakerResNetPreTrainedModel:()=>Pd,WhisperForConditionalGeneration:()=>Ma,WhisperModel:()=>ba,WhisperPreTrainedModel:()=>ko,XLMForQuestionAnswering:()=>Pr,XLMForSequenceClassification:()=>Gr,XLMForTokenClassification:()=>yt,XLMModel:()=>fs,XLMPreTrainedModel:()=>or,XLMRobertaForMaskedLM:()=>ts,XLMRobertaForQuestionAnswering:()=>wa,XLMRobertaForSequenceClassification:()=>Hs,XLMRobertaForTokenClassification:()=>Zn,XLMRobertaModel:()=>ft,XLMRobertaPreTrainedModel:()=>Oe,XLMWithLMHeadModel:()=>Ar,XVectorOutput:()=>Fu,YolosForObjectDetection:()=>hd,YolosModel:()=>tc,YolosObjectDetectionOutput:()=>rc,YolosPreTrainedModel:()=>mo});var _=s("./src/configs.js"),A=s("./src/backends/onnx.js"),j=s("./src/utils/dtypes.js"),ee=s("./src/utils/generic.js"),U=s("./src/utils/core.js"),b=s("./src/utils/hub.js"),T=s("./src/utils/constants.js"),M=s("./src/generation/logits_process.js"),x=s("./src/generation/configuration_utils.js"),P=s("./src/utils/tensor.js"),R=s("./src/utils/image.js"),Q=s("./src/utils/maths.js"),ne=s("./src/generation/stopping_criteria.js"),de=s("./src/generation/logits_sampler.js"),N=s("./src/env.js"),K=s("./src/models/whisper/generation_whisper.js"),q=s("./src/models/whisper/common_whisper.js");const B={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8},O=new Map,w=new Map,$=new Map;async function E(g,f,H){const Te=H.config?.["transformers.js_config"]??{};let $e=H.device??Te.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 Fe=$e??(N.apis.IS_NODE_ENV?"cpu":"wasm"),et=(0,A.deviceToExecutionProviders)(Fe);let rt=H.dtype??Te.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(f)?rt=rt[f]:(rt=j.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??j.DATA_TYPES.fp32,console.warn(`dtype not specified for "${f}". Using the default dtype (${rt}) for this device (${Fe}).`))),rt===j.DATA_TYPES.auto){let er=Te.dtype;typeof er!="string"&&(er=er[f]),er&&er!==j.DATA_TYPES.auto&&j.DATA_TYPES.hasOwnProperty(er)?rt=er:rt=j.DEFAULT_DEVICE_DTYPE_MAPPING[Fe]??j.DATA_TYPES.fp32}const _t=rt;if(j.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(_t)){if(_t===j.DATA_TYPES.fp16&&Fe==="webgpu"&&!await(0,j.isWebGpuFp16Supported)())throw new Error(`The device (${Fe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_t}. Should be one of: ${Object.keys(j.DATA_TYPES).join(", ")}`);const $t=Te.kv_cache_dtype?typeof Te.kv_cache_dtype=="string"?Te.kv_cache_dtype:Te.kv_cache_dtype[_t]??"float32":void 0;if($t&&!["float32","float16"].includes($t))throw new Error(`Invalid kv_cache_dtype: ${$t}. Should be one of: float32, float16`);const Jt={dtype:_t,kv_cache_dtype:$t},Ht=j.DEFAULT_DTYPE_SUFFIX_MAPPING[_t],Nt=`${H.subfolder??""}/${f}${Ht}.onnx`,At={...H.session_options};At.executionProviders??=et;const Mr=Te.free_dimension_overrides;Mr?At.freeDimensionOverrides??=Mr:Fe.startsWith("webnn")&&!At.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const Ut=(0,b.getModelFile)(g,Nt,!0,H),Vt=H.use_external_data_format??Te.use_external_data_format;let pr=[];if(Vt&&(Vt===!0||typeof Vt=="object"&&Vt.hasOwnProperty(f)&&Vt[f]===!0)){if(N.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const er=`${f}${Ht}.onnx_data`,zr=`${H.subfolder??""}/${er}`;pr.push(new Promise(async(Ir,kr)=>{const Or=await(0,b.getModelFile)(g,zr,!0,H);Ir({path:er,data:Or})}))}else At.externalData!==void 0&&(pr=At.externalData.map(async er=>{if(typeof er.data=="string"){const zr=await(0,b.getModelFile)(g,er.data,!0,H);return{...er,data:zr}}return er}));if(pr.length>0&&(At.externalData=await Promise.all(pr)),Fe==="webgpu"){const er=(0,_.getKeyValueShapes)(H.config,{prefix:"present"});if(Object.keys(er).length>0&&!(0,A.isONNXProxy)()){const zr={};for(const Ir in er)zr[Ir]="gpu-buffer";At.preferredOutputLocation=zr}}return{buffer:await Ut,session_options:At,session_config:Jt}}async function Z(g,f,H){return Object.fromEntries(await Promise.all(Object.keys(f).map(async Te=>{const{buffer:$e,session_options:Fe,session_config:et}=await E(g,f[Te],H),rt=await(0,A.createInferenceSession)($e,Fe,et);return[Te,rt]})))}async function J(g,f,H){return Object.fromEntries(await Promise.all(Object.keys(f).map(async Te=>{const $e=await(0,b.getModelJSON)(g,f[Te],!1,H);return[Te,$e]})))}function ae(g,f){const H=Object.create(null),Te=[];for(const et of g.inputNames){const rt=f[et];if(!(rt instanceof P.Tensor)){Te.push(et);continue}H[et]=(0,A.isONNXProxy)()?rt.clone():rt}if(Te.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Te.join(", ")}.`);const $e=Object.keys(f).length,Fe=g.inputNames.length;if($e>Fe){let et=Object.keys(f).filter(rt=>!g.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${$e} > ${Fe}). The following inputs will be ignored: "${et.join(", ")}".`)}return H}async function me(g,f){const H=ae(g,f);try{const Te=Object.fromEntries(Object.entries(H).map(([Fe,et])=>[Fe,et.ort_tensor]));let $e=await g.run(Te);return $e=ge($e),$e}catch(Te){const $e=Object.fromEntries(Object.entries(H).map(([Fe,{type:et,dims:rt,data:_t}])=>[Fe,{type:et,dims:rt,data:_t}]));throw console.error(`An error occurred during model execution: "${Te}".`),console.error("Inputs given to model:",$e),Te}}function ge(g){for(let f in g)(0,A.isONNXTensor)(g[f])?g[f]=new P.Tensor(g[f]):typeof g[f]=="object"&&ge(g[f]);return g}function Ee(g){if(g instanceof P.Tensor)return g;if(g.length===0)throw Error("items must be non-empty");if(Array.isArray(g[0])){if(g.some(f=>f.length!==g[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new P.Tensor("int64",BigInt64Array.from(g.flat().map(f=>BigInt(f))),[g.length,g[0].length])}else return new P.Tensor("int64",BigInt64Array.from(g.map(f=>BigInt(f))),[1,g.length])}function ve(g){return new P.Tensor("bool",[g],[1])}async function Le(g,f){let{encoder_outputs:H,input_ids:Te,decoder_input_ids:$e,...Fe}=f;if(!H){const rt=(0,U.pick)(f,g.sessions.model.inputNames);H=(await fe(g,rt)).last_hidden_state}return Fe.input_ids=$e,Fe.encoder_hidden_states=H,g.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Fe.encoder_attention_mask=f.attention_mask),await W(g,Fe,!0)}async function fe(g,f){const H=g.sessions.model,Te=(0,U.pick)(f,H.inputNames);if(H.inputNames.includes("inputs_embeds")&&!Te.inputs_embeds){if(!f.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Te.inputs_embeds=await g.encode_text({input_ids:f.input_ids})}return H.inputNames.includes("token_type_ids")&&!Te.token_type_ids&&(Te.token_type_ids=new P.Tensor("int64",new BigInt64Array(Te.input_ids.data.length),Te.input_ids.dims)),await me(H,Te)}async function W(g,f,H=!1){const Te=g.sessions[H?"decoder_model_merged":"model"],{past_key_values:$e,...Fe}=f;if(Te.inputNames.includes("use_cache_branch")&&(Fe.use_cache_branch=ve(!!$e)),Te.inputNames.includes("position_ids")&&Fe.attention_mask&&!Fe.position_ids){const rt=g.config.model_type==="paligemma"?1:0;Fe.position_ids=Re(Fe,$e,rt)}g.addPastKeyValues(Fe,$e);const et=(0,U.pick)(Fe,Te.inputNames);return await me(Te,et)}function ce({image_token_id:g,inputs_embeds:f,image_features:H,input_ids:Te,attention_mask:$e}){const Fe=Te.tolist().map($t=>$t.reduce((Jt,Ht,Nt)=>(Ht==g&&Jt.push(Nt),Jt),[])),et=Fe.reduce(($t,Jt)=>$t+Jt.length,0),rt=H.dims[0];if(et!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${et}, features ${rt}`);let _t=0;for(let $t=0;$tFe.dims[1])){if($ert==g.config.image_token_index)){const rt=g.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const _t=Fe.dims[1]-($e-rt);H.input_ids=Fe.slice(null,[-_t,null]),H.attention_mask=(0,P.ones)([1,$e+_t])}}}return H}function Qe(g,f,H,Te){return H.past_key_values&&(f=f.map($e=>[$e.at(-1)])),{...H,decoder_input_ids:Ee(f)}}function at(g,...f){return g.config.is_encoder_decoder?Qe(g,...f):We(g,...f)}function Ue(g,f,H,Te){const $e=!!H.past_key_values;return Te.guidance_scale!==null&&Te.guidance_scale>1&&($e?H.input_ids=(0,P.cat)([H.input_ids,H.input_ids],0):(H.input_ids=(0,P.cat)([H.input_ids,(0,P.full_like)(H.input_ids,BigInt(Te.pad_token_id))],0),H.attention_mask=(0,P.cat)([H.attention_mask,(0,P.full_like)(H.attention_mask,0n)],0))),($e||!H.pixel_values)&&(H.pixel_values=(0,P.full)([0,0,3,384,384],1)),$e&&(H.images_seq_mask=new P.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),H.images_emb_mask=new P.Tensor("bool",new Array(0).fill(!1),[1,1,0])),H}class oe extends ee.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(f,H,Te){super(),this.config=f,this.sessions=H,this.configs=Te;const $e=$.get(this.constructor),Fe=O.get($e);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Fe){case B.DecoderOnly:this.can_generate=!0,this._forward=W,this._prepare_inputs_for_generation=We;break;case B.Seq2Seq:case B.Vision2Seq:case B.Musicgen:this.can_generate=!0,this._forward=Le,this._prepare_inputs_for_generation=Qe;break;case B.EncoderDecoder:this._forward=Le;break;case B.ImageTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=at;break;case B.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Ue;break;default:this._forward=fe;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 H of Object.values(this.sessions))H?.handler?.dispose&&f.push(H.handler.dispose());return await Promise.all(f)}static async from_pretrained(f,{progress_callback:H=null,config:Te=null,cache_dir:$e=null,local_files_only:Fe=!1,revision:et="main",model_file_name:rt=null,subfolder:_t="onnx",device:$t=null,dtype:Jt=null,use_external_data_format:Ht=null,session_options:Nt={}}={}){let At={progress_callback:H,config:Te,cache_dir:$e,local_files_only:Fe,revision:et,model_file_name:rt,subfolder:_t,device:$t,dtype:Jt,use_external_data_format:Ht,session_options:Nt};const Mr=$.get(this),Ut=O.get(Mr);Te=At.config=await _.AutoConfig.from_pretrained(f,At);let Vt;if(Ut===B.DecoderOnly)Vt=await Promise.all([Z(f,{model:At.model_file_name??"model"},At),J(f,{generation_config:"generation_config.json"},At)]);else if(Ut===B.Seq2Seq||Ut===B.Vision2Seq)Vt=await Promise.all([Z(f,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},At),J(f,{generation_config:"generation_config.json"},At)]);else if(Ut===B.MaskGeneration)Vt=await Promise.all([Z(f,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},At)]);else if(Ut===B.EncoderDecoder)Vt=await Promise.all([Z(f,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},At)]);else if(Ut===B.ImageTextToText){const pr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Te.is_encoder_decoder&&(pr.model="encoder_model"),Vt=await Promise.all([Z(f,pr,At),J(f,{generation_config:"generation_config.json"},At)])}else if(Ut===B.Musicgen)Vt=await Promise.all([Z(f,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},At),J(f,{generation_config:"generation_config.json"},At)]);else if(Ut===B.MultiModality)Vt=await Promise.all([Z(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),J(f,{generation_config:"generation_config.json"},At)]);else{if(Ut!==B.EncoderOnly){const pr=Mr??Te?.model_type;pr!=="custom"&&console.warn(`Model type for '${pr}' not found, assuming encoder-only architecture. Please report this at ${T.GITHUB_ISSUE_URL}.`)}Vt=await Promise.all([Z(f,{model:At.model_file_name??"model"},At)])}return new this(Te,...Vt)}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 H=new M.LogitsProcessorList;return f.temperature!==null&&f.temperature!==1&&H.push(new M.TemperatureLogitsWarper(f.temperature)),f.top_k!==null&&f.top_k!==0&&H.push(new M.TopKLogitsWarper(f.top_k)),f.top_p!==null&&f.top_p<1&&H.push(new M.TopPLogitsWarper(f.top_p)),H}_get_logits_processor(f,H,Te=null){const $e=new M.LogitsProcessorList;if(f.repetition_penalty!==null&&f.repetition_penalty!==1&&$e.push(new M.RepetitionPenaltyLogitsProcessor(f.repetition_penalty)),f.no_repeat_ngram_size!==null&&f.no_repeat_ngram_size>0&&$e.push(new M.NoRepeatNGramLogitsProcessor(f.no_repeat_ngram_size)),f.bad_words_ids!==null&&$e.push(new M.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 M.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 M.MinNewTokensLengthLogitsProcessor(H,f.min_new_tokens,f.eos_token_id)),f.forced_bos_token_id!==null&&$e.push(new M.ForcedBOSTokenLogitsProcessor(f.forced_bos_token_id)),f.forced_eos_token_id!==null&&$e.push(new M.ForcedEOSTokenLogitsProcessor(f.max_length,f.forced_eos_token_id)),f.begin_suppress_tokens!==null){const Fe=H>1||f.forced_bos_token_id===null?H:H+1;$e.push(new M.SuppressTokensAtBeginLogitsProcessor(f.begin_suppress_tokens,Fe))}return f.guidance_scale!==null&&f.guidance_scale>1&&$e.push(new M.ClassifierFreeGuidanceLogitsProcessor(f.guidance_scale)),Te!==null&&$e.extend(Te),$e}_prepare_generation_config(f,H,Te=x.GenerationConfig){const $e={...this.config};for(const et of["decoder","generator","text_config"])et in $e&&Object.assign($e,$e[et]);const Fe=new Te($e);return Object.assign(Fe,this.generation_config??{}),f&&Object.assign(Fe,f),H&&Object.assign(Fe,(0,U.pick)(H,Object.getOwnPropertyNames(Fe))),Fe}_get_stopping_criteria(f,H=null){const Te=new ne.StoppingCriteriaList;return f.max_length!==null&&Te.push(new ne.MaxLengthCriteria(f.max_length,this.config.max_position_embeddings??null)),f.eos_token_id!==null&&Te.push(new ne.EosTokenCriteria(f.eos_token_id)),H&&Te.extend(H),Te}_validate_model_class(){if(!this.can_generate){const f=[Xi,Qi,gu,qi],H=$.get(this.constructor),Te=new Set,$e=this.config.model_type;for(const et of f){const rt=et.get($e);rt&&Te.add(rt[0])}let Fe=`The current model class (${H}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Te.size>0&&(Fe+=` Please use the following class instead: ${[...Te].join(", ")}`),Error(Fe)}}prepare_inputs_for_generation(...f){return this._prepare_inputs_for_generation(this,...f)}_update_model_kwargs_for_generation({generated_input_ids:f,outputs:H,model_inputs:Te,is_encoder_decoder:$e}){return Te.past_key_values=this.getPastKeyValues(H,Te.past_key_values),Te.input_ids=new P.Tensor("int64",f.flat(),[f.length,1]),$e||(Te.attention_mask=(0,P.cat)([Te.attention_mask,(0,P.ones)([Te.attention_mask.dims[0],1])],1)),Te.position_ids=null,Te}_prepare_model_inputs({inputs:f,bos_token_id:H,model_kwargs:Te}){const $e=(0,U.pick)(Te,this.forward_params),Fe=this.main_input_name;if(Fe 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[Fe]=f;return{inputs_tensor:$e[Fe],model_inputs:$e,model_input_name:Fe}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:f,model_inputs:H,model_input_name:Te,generation_config:$e}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!H.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:et,pixel_values:rt,attention_mask:_t,...$t}=H,Jt=await this._prepare_inputs_embeds(H);H={...$t,...(0,U.pick)(Jt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Fe}=await fe(this,H);if($e.guidance_scale!==null&&$e.guidance_scale>1)Fe=(0,P.cat)([Fe,(0,P.full_like)(Fe,0)],0),"attention_mask"in H&&(H.attention_mask=(0,P.cat)([H.attention_mask,(0,P.zeros_like)(H.attention_mask)],0));else if(H.decoder_input_ids){const et=Ee(H.decoder_input_ids).dims[0];if(et!==Fe.dims[0]){if(Fe.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Fe.dims[0]}) than the decoder inputs (${et}).`);Fe=(0,P.cat)(Array.from({length:et},()=>Fe),0)}}return H.encoder_outputs=Fe,H}_prepare_decoder_input_ids_for_generation({batch_size:f,model_input_name:H,model_kwargs:Te,decoder_start_token_id:$e,bos_token_id:Fe,generation_config:et}){let{decoder_input_ids:rt,..._t}=Te;if(!(rt instanceof P.Tensor)){if(rt)Array.isArray(rt[0])||(rt=Array.from({length:f},()=>rt));else if($e??=Fe,this.config.model_type==="musicgen")rt=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}`);rt=$e}else rt=Array.from({length:f},()=>[$e]);rt=Ee(rt)}return Te.decoder_attention_mask=(0,P.ones_like)(rt),{input_ids:rt,model_inputs:_t}}async generate({inputs:f=null,generation_config:H=null,logits_processor:Te=null,stopping_criteria:$e=null,streamer:Fe=null,...et}){this._validate_model_class(),H=this._prepare_generation_config(H,et);let{inputs_tensor:rt,model_inputs:_t,model_input_name:$t}=this._prepare_model_inputs({inputs:f,model_kwargs:et});const Jt=this.config.is_encoder_decoder;Jt&&("encoder_outputs"in _t||(_t=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:rt,model_inputs:_t,model_input_name:$t,generation_config:H})));let Ht;Jt?{input_ids:Ht,model_inputs:_t}=this._prepare_decoder_input_ids_for_generation({batch_size:_t[$t].dims.at(0),model_input_name:$t,model_kwargs:_t,decoder_start_token_id:H.decoder_start_token_id,bos_token_id:H.bos_token_id,generation_config:H}):Ht=_t[$t];let Nt=Ht.dims.at(-1);H.max_new_tokens!==null&&(H.max_length=Nt+H.max_new_tokens);const At=this._get_logits_processor(H,Nt,Te),Mr=this._get_stopping_criteria(H,$e),Ut=_t[$t].dims.at(0),Vt=de.LogitsSampler.getSampler(H),pr=new Array(Ut).fill(0),wr=Ht.tolist();Fe&&Fe.put(wr);let er,zr={};for(;;){if(_t=this.prepare_inputs_for_generation(wr,_t,H),er=await this.forward(_t),H.output_attentions&&H.return_dict_in_generate){const ss=this.getAttentions(er);for(const Ts in ss)Ts in zr||(zr[Ts]=[]),zr[Ts].push(ss[Ts])}const Or=er.logits.slice(null,-1,null),Xr=At(wr,Or),ps=[];for(let ss=0;ssss))break;_t=this._update_model_kwargs_for_generation({generated_input_ids:ps,outputs:er,model_inputs:_t,is_encoder_decoder:Jt})}Fe&&Fe.end();const Ir=this.getPastKeyValues(er,_t.past_key_values,!0),kr=new P.Tensor("int64",wr.flat(),[wr.length,wr[0].length]);if(H.return_dict_in_generate)return{sequences:kr,past_key_values:Ir,...zr};for(const Or of Object.values(er))Or.location==="gpu-buffer"&&Or.dispose();return kr}getPastKeyValues(f,H,Te=!1){const $e=Object.create(null);for(const Fe in f)if(Fe.startsWith("present")){const et=Fe.replace("present","past_key_values"),rt=Fe.includes("encoder");if(rt&&H?$e[et]=H[et]:$e[et]=f[Fe],H&&(!rt||Te)){const _t=H[et];_t.location==="gpu-buffer"&&_t.dispose()}}return $e}getAttentions(f){const H={};for(const Te of["cross_attentions","encoder_attentions","decoder_attentions"])for(const $e in f)$e.startsWith(Te)&&(Te in H||(H[Te]=[]),H[Te].push(f[$e]));return H}addPastKeyValues(f,H){if(H)Object.assign(f,H);else{const $e=(this.sessions.decoder_model_merged??this.sessions.model)?.config?.kv_cache_dtype??"float32",Fe=$e==="float16"?new Uint16Array:[],et=(f[this.main_input_name]??f.attention_mask)?.dims?.[0]??1,rt=(0,_.getKeyValueShapes)(this.config,{batch_size:et});for(const _t in rt)f[_t]=new P.Tensor($e,Fe,rt[_t])}}async encode_image({pixel_values:f}){const H=(await me(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 (${H.dims[1]}).`),this.config.num_image_tokens=H.dims[1]),H}async encode_text({input_ids:f}){return(await me(this.sessions.embed_tokens,{input_ids:f})).inputs_embeds}}class Ve{}class Ne extends Ve{constructor({last_hidden_state:f,hidden_states:H=null,attentions:Te=null}){super(),this.last_hidden_state=f,this.hidden_states=H,this.attentions=Te}}class ue extends oe{}class ke extends ue{}class tt extends ue{async _call(f){return new Wr(await super._call(f))}}class He extends ue{async _call(f){return new Kt(await super._call(f))}}class Xe extends ue{async _call(f){return new Nr(await super._call(f))}}class Be extends ue{async _call(f){return new Vr(await super._call(f))}}class st extends oe{}class lt extends st{}class xt extends oe{}class ut extends xt{}class gt extends xt{async _call(f){return new Wr(await super._call(f))}}class I extends xt{async _call(f){return new Kt(await super._call(f))}}class se extends xt{async _call(f){return new Nr(await super._call(f))}}class X extends xt{async _call(f){return new Vr(await super._call(f))}}class he extends oe{}class Ae extends he{}class Ge extends he{async _call(f){return new Wr(await super._call(f))}}class Je extends he{async _call(f){return new Kt(await super._call(f))}}class nt extends he{async _call(f){return new Nr(await super._call(f))}}class wt extends he{async _call(f){return new Vr(await super._call(f))}}class pt extends oe{}class Qt extends pt{}class tr extends pt{async _call(f){return new Wr(await super._call(f))}}class Tr extends pt{async _call(f){return new Kt(await super._call(f))}}class mr extends pt{async _call(f){return new Nr(await super._call(f))}}class Sr extends pt{async _call(f){return new Vr(await super._call(f))}}class br extends oe{}class Hr extends br{}class ns extends br{async _call(f){return new Wr(await super._call(f))}}class Bs extends br{async _call(f){return new Kt(await super._call(f))}}class Cs extends br{async _call(f){return new Nr(await super._call(f))}}class an extends br{async _call(f){return new Vr(await super._call(f))}}class Ot extends oe{}class Rs extends Ot{}class ys extends Ot{async _call(f){return new Wr(await super._call(f))}}class ks extends Ot{async _call(f){return new Kt(await super._call(f))}}class bs extends Ot{async _call(f){return new Nr(await super._call(f))}}class $s extends Ot{async _call(f){return new Vr(await super._call(f))}}class Jr extends oe{}class ls extends Jr{}class Ms extends Jr{async _call(f){return new Wr(await super._call(f))}}class Ns extends Jr{async _call(f){return new Kt(await super._call(f))}}class os extends Jr{async _call(f){return new Nr(await super._call(f))}}class ot extends Jr{async _call(f){return new Vr(await super._call(f))}}class dt extends oe{}class kt extends dt{}class cr extends dt{async _call(f){return new Kt(await super._call(f))}}class js extends dt{async _call(f){return new Nr(await super._call(f))}}class sr extends dt{async _call(f){return new Vr(await super._call(f))}}class Us extends dt{async _call(f){return new Wr(await super._call(f))}}class Ss extends oe{}class Yn extends Ss{}class Mn extends Ss{async _call(f){return new Wr(await super._call(f))}}class Ws extends Ss{async _call(f){return new Kt(await super._call(f))}}class vn extends Ss{async _call(f){return new Nr(await super._call(f))}}class As extends oe{}class xn extends As{}class Jn extends As{async _call(f){return new Wr(await super._call(f))}}class Is extends As{async _call(f){return new Kt(await super._call(f))}}class hs extends As{async _call(f){return new Vr(await super._call(f))}}class Zr extends oe{}class ln extends Zr{}class Vs extends Zr{async _call(f){return new Wr(await super._call(f))}}class dn extends Zr{async _call(f){return new Kt(await super._call(f))}}class Gs extends Zr{async _call(f){return new Nr(await super._call(f))}}class un extends Zr{async _call(f){return new Vr(await super._call(f))}}class Ft extends oe{}class cn extends Ft{}class Tn extends Ft{async _call(f){return new Wr(await super._call(f))}}class En extends Ft{async _call(f){return new Kt(await super._call(f))}}class Pn extends Ft{async _call(f){return new Vr(await super._call(f))}}class Os extends oe{}class Cn extends Os{}class pn extends Os{async _call(f){return new Kt(await super._call(f))}}class kn extends Os{async _call(f){return new Vr(await super._call(f))}}class nr extends Os{async _call(f){return new Wr(await super._call(f))}}class es extends oe{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class hn extends es{}class $n extends es{}class Ks extends oe{}class Sn extends Ks{}class xe extends Ks{}class y extends oe{}class Y extends y{}class le extends y{}class we extends oe{}class Ie extends we{}class Ke extends we{}class ht extends we{async _call(f){return new Kt(await super._call(f))}}class mt extends oe{}class Mt extends mt{}class qe extends mt{}class It extends mt{async _call(f){return new Kt(await super._call(f))}}class Xt extends mt{}class gr extends oe{}class Ce extends gr{}class Er extends gr{}class jr extends oe{}class Rr extends jr{}class ds extends jr{}class zt extends oe{}class Lr extends zt{}class ms extends zt{async _call(f){return new Wr(await super._call(f))}}class Zt extends zt{async _call(f){return new Kt(await super._call(f))}}class dr extends zt{async _call(f){return new Nr(await super._call(f))}}class Tt extends zt{async _call(f){return new Vr(await super._call(f))}}class or extends oe{}class fs extends or{}class Ar extends or{async _call(f){return new Wr(await super._call(f))}}class Gr extends or{async _call(f){return new Kt(await super._call(f))}}class yt extends or{async _call(f){return new Nr(await super._call(f))}}class Pr extends or{async _call(f){return new Vr(await super._call(f))}}class Oe extends oe{}class ft extends Oe{}class ts extends Oe{async _call(f){return new Wr(await super._call(f))}}class Hs extends Oe{async _call(f){return new Kt(await super._call(f))}}class Zn extends Oe{async _call(f){return new Nr(await super._call(f))}}class wa extends Oe{async _call(f){return new Vr(await super._call(f))}}class Wt extends oe{}class ya extends Wt{}class Co extends Wt{}class ko extends oe{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 ba extends ko{}class Ma extends ko{_prepare_generation_config(f,H){return super._prepare_generation_config(f,H,K.WhisperGenerationConfig)}_retrieve_init_tokens(f){const H=[f.decoder_start_token_id];let Te=f.language;const $e=f.task;if(f.is_multilingual){Te||(console.warn("No language specified - defaulting to English (en)."),Te="en");const et=`<|${(0,q.whisper_language_to_code)(Te)}|>`;H.push(f.lang_to_id[et]),H.push(f.task_to_id[$e??"transcribe"])}else if(Te||$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&&H.at(-1)!==f.no_timestamps_token_id?H.push(f.no_timestamps_token_id):f.return_timestamps&&H.at(-1)===f.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),H.pop()),H.filter(Fe=>Fe!=null)}async generate({inputs:f=null,generation_config:H=null,logits_processor:Te=null,stopping_criteria:$e=null,...Fe}){H=this._prepare_generation_config(H,Fe);const et=Fe.decoder_input_ids??this._retrieve_init_tokens(H);if(H.return_timestamps&&(Te??=new M.LogitsProcessorList,Te.push(new M.WhisperTimeStampLogitsProcessor(H,et))),H.begin_suppress_tokens&&(Te??=new M.LogitsProcessorList,Te.push(new M.SuppressTokensAtBeginLogitsProcessor(H.begin_suppress_tokens,et.length))),H.return_token_timestamps){if(!H.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.");H.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),H.output_attentions=!0,H.return_dict_in_generate=!0}const rt=await super.generate({inputs:f,generation_config:H,logits_processor:Te,decoder_input_ids:et,...Fe});return H.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,H.alignment_heads,H.num_frames)),rt}_extract_token_timestamps(f,H,Te=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`.");Te==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let Fe=this.config.median_filter_width;Fe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Fe=7);const et=f.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(Ut,Vt)=>(0,P.cat)(et.map(pr=>pr[Vt]),2)),_t=(0,P.stack)(H.map(([Ut,Vt])=>{if(Ut>=rt.length)throw new Error(`Layer index ${Ut} is out of bounds for cross attentions (length ${rt.length}).`);return Te?rt[Ut].slice(null,Vt,null,[0,Te]):rt[Ut].slice(null,Vt)})).transpose(1,0,2,3),[$t,Jt]=(0,P.std_mean)(_t,-2,0,!0),Ht=_t.clone();for(let Ut=0;Utpr[Or+1]-pr[Or]),zr=(0,U.mergeArrays)([1],er).map(kr=>!!kr),Ir=[];for(let kr=0;krNt.findIndex(At=>At==Fe)),_t=rt.every(Nt=>Nt===-1),$t=rt.every(Nt=>Nt!==-1);if(!_t&&!$t)throw new Error("Every input should contain either 0 or 1 image token.");if(_t)return{inputs_embeds:f,attention_mask:$e};const Jt=[],Ht=[];for(let Nt=0;NtArray.from({length:f.dims[0]},er=>Array.from({length:f.dims[1]},zr=>1))),Mr=H?H.tolist():[],Ut=Te?Te.tolist():[];let Vt=0,pr=0;for(let wr=0;wrNt[wr][Br]==1),Ir=er.reduce((yr,Br,zs)=>(Br==_t&&yr.push(zs),yr),[]).map(yr=>er[yr+1]),kr=Ir.filter(yr=>yr==et).length,Or=Ir.filter(yr=>yr==rt).length;let Xr=[],ps=0,Mo=kr,ss=Or;for(let yr=0;yrgs>ps&&tn==et),zs=er.findIndex((tn,gs)=>gs>ps&&tn==rt),fn=Mo>0&&Br!==-1?Br:er.length+1,_n=ss>0&&zs!==-1?zs:er.length+1;let na,oa,ia,aa;fn<_n?([oa,ia,aa]=Mr[Vt],++Vt,--Mo,na=fn):([oa,ia,aa]=Ut[pr],++pr,--ss,na=_n);const[qc,la,da]=[Number(oa),Math.floor(Number(ia)/$t),Math.floor(Number(aa)/$t)],ua=na-ps,ca=Xr.length>0?(0,Q.max)(Xr.at(-1))[0]+1:0;Xr.push(Array.from({length:3*ua},(tn,gs)=>ca+gs%ua));const pa=ua+ca,Wn=qc*la*da,zu=Array.from({length:Wn},(tn,gs)=>pa+Math.floor(gs/(la*da))),Bu=Array.from({length:Wn},(tn,gs)=>pa+Math.floor(gs/da)%la),Xc=Array.from({length:Wn},(tn,gs)=>pa+gs%da);Xr.push([zu,Bu,Xc].flat()),ps=na+Wn}if(ps0?(0,Q.max)(Xr.at(-1))[0]+1:0,Br=er.length-ps;Xr.push(Array.from({length:3*Br},(zs,fn)=>yr+fn%Br))}const Ts=Xr.reduce((yr,Br)=>yr+Br.length,0),jn=new Array(Ts);let ra=0;for(let yr=0;yr<3;++yr)for(let Br=0;BrHt[Vt%Ht.length]),Mr=Array.from({length:Nt[0]},(Ut,Vt)=>(0,Q.max)(Ht.subarray(Nt[1]*Vt,Nt[1]*(Vt+1)))[0]+1+Nt[1]);return[new P.Tensor("int64",At,[3,...Nt]),new P.Tensor("int64",Mr,[Mr.length,1])]}else{const[Ht,Nt]=f.dims,At=BigInt64Array.from({length:3*Ht*Nt},(Mr,Ut)=>BigInt(Math.floor(Ut%Nt/Ht)));return[new P.Tensor("int64",At,[3,...f.dims]),(0,P.zeros)([Ht,1])]}}async encode_image({pixel_values:f,image_grid_thw:H}){return(await me(this.sessions.vision_encoder,{pixel_values:f,grid_thw:H})).image_features}_merge_input_ids_with_image_features(f){return ce({image_token_id:this.config.image_token_id,...f})}prepare_inputs_for_generation(f,H,Te){if(H.attention_mask&&!H.position_ids)if(!H.past_key_values)[H.position_ids,H.rope_deltas]=this.get_rope_index(H.input_ids,H.image_grid_thw,H.video_grid_thw,H.attention_mask);else{H.pixel_values=null;const $e=BigInt(Object.values(H.past_key_values)[0].dims.at(-2)),Fe=H.rope_deltas.map(et=>$e+et);H.position_ids=(0,P.stack)([Fe,Fe,Fe],0)}return H}}class Vo extends oe{}class _l extends Vo{}class gl extends Vo{}class Go extends oe{}class wl extends Go{}class yl extends Go{}class Ko extends oe{}class bl extends Ko{}class Ml extends Ko{}class Ho extends oe{}class On extends Ho{}class vl extends Ho{}class Fn extends oe{}class xl extends Fn{}class Tl extends Fn{}class qo extends oe{}class El extends qo{}class Pl extends qo{async _call(f){return new Kt(await super._call(f))}}class Xo extends oe{}class Cl extends Xo{}class kl extends Xo{async _call(f){return new Kt(await super._call(f))}}class $l extends oe{}class Sl extends $l{}class Qo extends oe{}class Al extends Qo{}class Il extends Qo{async _call(f){return new Kt(await super._call(f))}}class Ol extends oe{}class Fl extends Ol{}class Yo extends oe{}class Jo extends Yo{}class Dl extends Yo{async _call(f){return new Kt(await super._call(f))}}class Zo extends oe{}class ei extends Zo{}class ti extends oe{}class Ll extends ti{}class zl extends ti{async _call(f){return new Kt(await super._call(f))}}class Bl extends oe{}class Rl extends Bl{async _call(f){return new Du(await super._call(f))}}class ri extends oe{}class si extends ri{}class Nl extends ri{async _call(f){return new Kt(await super._call(f))}}class ni extends oe{}class jl extends ni{}class Qu extends ni{async _call(f){return new Kt(await super._call(f))}}class oi extends oe{}class Ul extends oi{}class cs extends oi{}class ii extends oe{}class Wl extends ii{}class Vl extends ii{}class ai extends oe{}class Gl extends ai{}class Kl extends ai{async _call(f){return new Kt(await super._call(f))}}class io extends oe{}class Hl extends io{}class ql extends io{async _call(f){return new Xl(await super._call(f))}}class li extends io{async _call(f){return new Ql(await super._call(f))}}class Xl extends Ve{constructor({logits:f,pred_boxes:H}){super(),this.logits=f,this.pred_boxes=H}}class Ql extends Ve{constructor({logits:f,pred_boxes:H,pred_masks:Te}){super(),this.logits=f,this.pred_boxes=H,this.pred_masks=Te}}class di extends oe{}class Yl extends di{}class Jl extends di{async _call(f){return new Zl(await super._call(f))}}class Zl extends Ve{constructor({logits:f,pred_boxes:H}){super(),this.logits=f,this.pred_boxes=H}}class ui extends oe{}class Yu extends ui{}class Xs extends ui{async _call(f){return new Qs(await super._call(f))}}class Qs extends Xl{}class Ds extends oe{}class ci extends Ds{}class Ys extends Ds{async _call(f){return new Kt(await super._call(f))}}class Ur extends oe{}class ed extends Ur{}class pi extends Ur{async _call(f){return new Kt(await super._call(f))}}class hi extends oe{}class Ju extends hi{}class Dn extends hi{async _call(f){return new Kt(await super._call(f))}}class ao extends oe{}class mi extends ao{}class td extends ao{async _call(f){return new Kt(await super._call(f))}}class fi extends oe{}class _i extends fi{}class gi extends fi{}class wi extends oe{}class yi extends wi{}class rd extends wi{}class lo extends oe{}class bi extends lo{}class uo extends oe{}class sd extends uo{}class Zu extends uo{}class nd extends uo{}class Mi extends oe{}class Ln extends Mi{}class vi extends oe{}class xi extends vi{}class od extends vi{}class Ti extends oe{}class id extends Ti{}class ec extends Ti{}class ad extends oe{}class ld extends ad{}class dd extends oe{}class ud extends dd{}class co extends dd{async _call(f){return new Kt(await super._call(f))}}class Ei extends oe{}class po extends Ei{}class Pi extends Ei{async _call(f){return new Kt(await super._call(f))}}class ho extends oe{}class cd extends ho{}class pd extends ho{async _call(f){return new Kt(await super._call(f))}}class mo extends oe{}class tc extends mo{}class hd extends mo{async _call(f){return new rc(await super._call(f))}}class rc extends Ve{constructor({logits:f,pred_boxes:H}){super(),this.logits=f,this.pred_boxes=H}}class md extends oe{}class fd extends md{async get_image_embeddings({pixel_values:f}){return await fe(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 Te=f.input_points.dims.slice(0,-1),$e=Te.reduce((Fe,et)=>Fe*et,1);f.input_labels=new P.Tensor("int64",new BigInt64Array($e).fill(1n),Te)}const H={image_embeddings:f.image_embeddings,image_positional_embeddings:f.image_positional_embeddings};return f.input_points&&(H.input_points=f.input_points),f.input_labels&&(H.input_labels=f.input_labels),f.input_boxes&&(H.input_boxes=f.input_boxes),await me(this.sessions.prompt_encoder_mask_decoder,H)}async _call(f){return new _d(await super._call(f))}}class _d extends Ve{constructor({iou_scores:f,pred_masks:H}){super(),this.iou_scores=f,this.pred_masks=H}}class fo extends oe{}class gd extends fo{}class wd extends fo{}class _o extends oe{}class yd extends _o{}class bd extends _o{}class Js extends oe{}class Md extends Js{}class vd extends Js{async _call(f){return new en(await super._call(f))}}class xd extends Js{async _call(f){return new Kt(await super._call(f))}}class sc extends Js{async _call(f){return new Nr(await super._call(f))}}class Ci extends oe{}class Td extends Ci{}class Ed extends Ci{async _call(f){return new Nr(await super._call(f))}}class Pd extends oe{}class Cd extends Pd{}class ki extends oe{}class go extends ki{}class zn extends ki{async _call(f){return new en(await super._call(f))}}class $i extends ki{async _call(f){return new Kt(await super._call(f))}}class Bn extends oe{}class kd extends Bn{}class $d extends Bn{async _call(f){return new en(await super._call(f))}}class Sd extends Bn{async _call(f){return new Kt(await super._call(f))}}class Si extends Bn{async _call(f){return new Nr(await super._call(f))}}class wo extends oe{}class Ad extends wo{}class Id extends wo{async _call(f){return new en(await super._call(f))}}class nc extends wo{async _call(f){return new Kt(await super._call(f))}}class oc extends oe{}class Ai extends Js{}class Od extends Js{async _call(f){return new en(await super._call(f))}}class Fd extends Js{async _call(f){return new Kt(await super._call(f))}}class mn extends oe{}class ic extends mn{}class Dd extends mn{async _call(f){return new en(await super._call(f))}}class Ld extends mn{async _call(f){return new Kt(await super._call(f))}}class ac extends mn{async _call(f){return new Fu(await super._call(f))}}class zd extends mn{async _call(f){return new Nr(await super._call(f))}}class yo extends oe{}class lc extends yo{}class Bd extends yo{}class dc extends yo{async generate_speech(f,H,{threshold:Te=.5,minlenratio:$e=0,maxlenratio:Fe=20,vocoder:et=null}={}){const rt={input_ids:f},{encoder_outputs:_t,encoder_attention_mask:$t}=await fe(this,rt),Jt=_t.dims[1]/this.config.reduction_factor,Ht=Math.floor(Jt*Fe),Nt=Math.floor(Jt*$e),At=this.config.num_mel_bins;let Mr=[],Ut=null,Vt=null,pr=0;for(;;){++pr;const zr=ve(!!Vt);let Ir;Vt?Ir=Vt.output_sequence_out:Ir=new P.Tensor("float32",new Float32Array(At),[1,1,At]);let kr={use_cache_branch:zr,output_sequence:Ir,encoder_attention_mask:$t,speaker_embeddings:H,encoder_hidden_states:_t};this.addPastKeyValues(kr,Ut),Vt=await me(this.sessions.decoder_model_merged,kr),Ut=this.getPastKeyValues(Vt,Ut);const{prob:Or,spectrum:Xr}=Vt;if(Mr.push(Xr),pr>=Nt&&(Array.from(Or.data).filter(ps=>ps>=Te).length>0||pr>=Ht))break}const wr=(0,P.cat)(Mr),{waveform:er}=await me(et.sessions.model,{spectrogram:wr});return{spectrogram:wr,waveform:er}}}class Rd extends oe{main_input_name="spectrogram"}class Nd extends oe{}class jd extends Nd{}class Ud extends oe{}class Wd extends Ud{}class Vd extends Ud{}class Ii extends oe{}class Gd extends Ii{}class uc extends Ii{}class Oi extends oe{}class Kd extends Oi{}class Hd extends Oi{}class bo extends oe{}class cc extends bo{}class qd extends bo{static async from_pretrained(f,H={}){return H.model_file_name??="text_model",super.from_pretrained(f,H)}}class Xd extends bo{static async from_pretrained(f,H={}){return H.model_file_name??="audio_model",super.from_pretrained(f,H)}}class Qd extends oe{}class Fi extends Qd{async _call(f){return new Lu(await super._call(f))}}class Di extends oe{}class vs extends Di{}class xs extends Di{}class Zs extends Di{}class Ls extends oe{}class Yd extends Ls{}class Jd extends Ls{}class Li extends oe{}class Zd extends Li{}class eu extends Li{async _call(f){return new Kt(await super._call(f))}}class zi extends oe{}class pc extends zi{}class hc extends zi{}class Bi extends oe{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[H,Te]=f.dims,$e=this.config.decoder.num_codebooks,Fe=Te-$e;let et=0;for(let $t=0;$t0&&Nt<=Fe&&(f.data[et++]=f.data[$t])}const rt=Math.floor(H/$e),_t=et/(rt*$e);return new P.Tensor(f.type,f.data.slice(0,et),[rt,$e,_t])}prepare_inputs_for_generation(f,H,Te){let $e=structuredClone(f);for(let et=0;et<$e.length;++et)for(let rt=0;rt<$e[et].length;++rt)et%this.config.decoder.num_codebooks>=rt&&($e[et][rt]=BigInt(this.config.decoder.pad_token_id));return Te.guidance_scale!==null&&Te.guidance_scale>1&&($e=$e.concat($e)),super.prepare_inputs_for_generation($e,H,Te)}async generate(f){const H=await super.generate(f),Te=this._apply_and_filter_by_delay_pattern_mask(H).unsqueeze_(0),{audio_values:$e}=await me(this.sessions.encodec_decode,{audio_codes:Te});return $e}}class Ri extends oe{}class mc extends Ri{}class qr extends Ri{async _call(f){return new Kt(await super._call(f))}}class Ni extends oe{}class tu extends Ni{}class ji extends Ni{async _call(f){return new Kt(await super._call(f))}}class Ui extends oe{}class Rn extends Ui{}class ru extends Ui{async _call(f){return new Kt(await super._call(f))}}class Wi extends oe{}class su extends Wi{}class nu extends Wi{async _call(f){return new Kt(await super._call(f))}}class ou extends oe{}class iu extends ou{}class Vi extends oe{}class au extends Vi{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 H=this._generation_mode??"text";let Te;if(H==="text"||!f.past_key_values){const _t=this.sessions.prepare_inputs_embeds,$t=(0,U.pick)(f,_t.inputNames);Te=await me(_t,$t)}else{const _t=this.sessions.gen_img_embeds,$t=(0,U.pick)({image_ids:f.input_ids},_t.inputNames);Te=await me(_t,$t)}const $e={...f,...Te},Fe=await W(this,$e),et=this.sessions[H==="text"?"lm_head":"gen_head"];if(!et)throw new Error(`Unable to find "${et}" generation head`);const rt=await me(et,(0,U.pick)(Fe,et.inputNames));return{...Te,...Fe,...rt}}async generate(f){return this._generation_mode="text",super.generate(f)}async generate_images(f){this._generation_mode="image";const H=(f.inputs??f[this.main_input_name]).dims[1],$e=(await super.generate(f)).slice(null,[H,null]),Fe=this.sessions.image_decode,{decoded_image:et}=await me(Fe,{generated_tokens:$e}),rt=et.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),_t=[];for(const $t of rt){const Jt=R.RawImage.fromTensor($t);_t.push(Jt)}return _t}}class lu extends Ve{constructor({char_logits:f,bpe_logits:H,wp_logits:Te}){super(),this.char_logits=f,this.bpe_logits=H,this.wp_logits=Te}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class du extends oe{}class uu extends du{async _call(f){return new lu(await super._call(f))}}class Gi extends oe{}class Ki extends Gi{}class cu extends Gi{}class pu extends oe{}class Hi extends pu{}class hu extends pu{}class fr{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(f,{progress_callback:H=null,config:Te=null,cache_dir:$e=null,local_files_only:Fe=!1,revision:et="main",model_file_name:rt=null,subfolder:_t="onnx",device:$t=null,dtype:Jt=null,use_external_data_format:Ht=null,session_options:Nt={}}={}){const At={progress_callback:H,config:Te,cache_dir:$e,local_files_only:Fe,revision:et,model_file_name:rt,subfolder:_t,device:$t,dtype:Jt,use_external_data_format:Ht,session_options:Nt};if(At.config=await _.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 Mr of this.MODEL_CLASS_MAPPINGS){const Ut=Mr.get(At.config.model_type);if(Ut)return await Ut[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 oe.from_pretrained(f,At);throw Error(`Unsupported model type: ${At.config.model_type}`)}}const fc=new Map([["bert",["BertModel",ke]],["nomic_bert",["NomicBertModel",lt]],["roformer",["RoFormerModel",ut]],["electra",["ElectraModel",Qt]],["esm",["EsmModel",Yn]],["convbert",["ConvBertModel",Ae]],["camembert",["CamembertModel",Hr]],["deberta",["DebertaModel",Rs]],["deberta-v2",["DebertaV2Model",ls]],["mpnet",["MPNetModel",ln]],["albert",["AlbertModel",Cn]],["distilbert",["DistilBertModel",kt]],["roberta",["RobertaModel",Lr]],["xlm",["XLMModel",fs]],["xlm-roberta",["XLMRobertaModel",ft]],["clap",["ClapModel",cc]],["clip",["CLIPModel",ka]],["clipseg",["CLIPSegModel",Ba]],["chinese_clip",["ChineseCLIPModel",Da]],["siglip",["SiglipModel",Aa]],["jina_clip",["JinaCLIPModel",La]],["mobilebert",["MobileBertModel",xn]],["squeezebert",["SqueezeBertModel",cn]],["wav2vec2",["Wav2Vec2Model",Md]],["wav2vec2-bert",["Wav2Vec2BertModel",Ad]],["unispeech",["UniSpeechModel",go]],["unispeech-sat",["UniSpeechSatModel",kd]],["hubert",["HubertModel",Ai]],["wavlm",["WavLMModel",ic]],["audio-spectrogram-transformer",["ASTModel",ya]],["vits",["VitsModel",Fi]],["pyannote",["PyAnnoteModel",Td]],["wespeaker-resnet",["WeSpeakerResNetModel",Cd]],["detr",["DetrModel",Hl]],["rt_detr",["RTDetrModel",Yl]],["table-transformer",["TableTransformerModel",Yu]],["vit",["ViTModel",El]],["ijepa",["IJepaModel",Cl]],["pvt",["PvtModel",Al]],["vit_msn",["ViTMSNModel",Jo]],["vit_mae",["ViTMAEModel",Fl]],["groupvit",["GroupViTModel",ei]],["fastvit",["FastViTModel",Ll]],["mobilevit",["MobileViTModel",si]],["mobilevitv2",["MobileViTV2Model",jl]],["owlvit",["OwlViTModel",Ul]],["owlv2",["Owlv2Model",Wl]],["beit",["BeitModel",Gl]],["deit",["DeiTModel",ci]],["hiera",["HieraModel",ed]],["convnext",["ConvNextModel",ud]],["convnextv2",["ConvNextV2Model",po]],["dinov2",["Dinov2Model",cd]],["resnet",["ResNetModel",Ju]],["swin",["SwinModel",mi]],["swin2sr",["Swin2SRModel",_i]],["donut-swin",["DonutSwinModel",ld]],["yolos",["YolosModel",tc]],["dpt",["DPTModel",yi]],["glpn",["GLPNModel",id]],["hifigan",["SpeechT5HifiGan",Rd]],["efficientnet",["EfficientNetModel",Zd]],["decision_transformer",["DecisionTransformerModel",iu]],["patchtst",["PatchTSTForPrediction",Ki]],["patchtsmixer",["PatchTSMixerForPrediction",Hi]],["mobilenet_v1",["MobileNetV1Model",mc]],["mobilenet_v2",["MobileNetV2Model",tu]],["mobilenet_v3",["MobileNetV3Model",Rn]],["mobilenet_v4",["MobileNetV4Model",su]],["maskformer",["MaskFormerModel",xi]],["mgp-str",["MgpstrForSceneTextRecognition",uu]]]),_1=new Map([["t5",["T5Model",hn]],["longt5",["LongT5Model",Sn]],["mt5",["MT5Model",Y]],["bart",["BartModel",Ie]],["mbart",["MBartModel",Mt]],["marian",["MarianModel",gd]],["whisper",["WhisperModel",ba]],["m2m_100",["M2M100Model",yd]],["blenderbot",["BlenderbotModel",Ce]],["blenderbot-small",["BlenderbotSmallModel",Rr]]]),_c=new Map([["bloom",["BloomModel",bl]],["jais",["JAISModel",Na]],["gpt2",["GPT2Model",us]],["gptj",["GPTJModel",Ka]],["gpt_bigcode",["GPTBigCodeModel",qa]],["gpt_neo",["GPTNeoModel",Ua]],["gpt_neox",["GPTNeoXModel",Va]],["codegen",["CodeGenModel",Qa]],["llama",["LlamaModel",Ja]],["olmo",["OlmoModel",qu]],["olmo2",["Olmo2Model",rl]],["mobilellm",["MobileLLMModel",Za]],["granite",["GraniteModel",In]],["cohere",["CohereModel",jo]],["gemma",["GemmaModel",il]],["gemma2",["Gemma2Model",dl]],["openelm",["OpenELMModel",Xu]],["qwen2",["Qwen2Model",pl]],["phi",["PhiModel",_l]],["phi3",["Phi3Model",wl]],["mpt",["MptModel",On]],["opt",["OPTModel",xl]],["mistral",["MistralModel",Wd]],["starcoder2",["Starcoder2Model",Gd]],["falcon",["FalconModel",Kd]],["stablelm",["StableLmModel",Yd]]]),qi=new Map([["speecht5",["SpeechT5ForSpeechToText",Bd]],["whisper",["WhisperForConditionalGeneration",Ma]]]),mu=new Map([["speecht5",["SpeechT5ForTextToSpeech",dc]]]),gc=new Map([["vits",["VitsModel",Fi]],["musicgen",["MusicgenForConditionalGeneration",Bi]]]),fu=new Map([["bert",["BertForSequenceClassification",He]],["roformer",["RoFormerForSequenceClassification",I]],["electra",["ElectraForSequenceClassification",Tr]],["esm",["EsmForSequenceClassification",Ws]],["convbert",["ConvBertForSequenceClassification",Je]],["camembert",["CamembertForSequenceClassification",Bs]],["deberta",["DebertaForSequenceClassification",ks]],["deberta-v2",["DebertaV2ForSequenceClassification",Ns]],["mpnet",["MPNetForSequenceClassification",dn]],["albert",["AlbertForSequenceClassification",pn]],["distilbert",["DistilBertForSequenceClassification",cr]],["roberta",["RobertaForSequenceClassification",Zt]],["xlm",["XLMForSequenceClassification",Gr]],["xlm-roberta",["XLMRobertaForSequenceClassification",Hs]],["bart",["BartForSequenceClassification",ht]],["mbart",["MBartForSequenceClassification",It]],["mobilebert",["MobileBertForSequenceClassification",Is]],["squeezebert",["SqueezeBertForSequenceClassification",En]]]),_u=new Map([["bert",["BertForTokenClassification",Xe]],["roformer",["RoFormerForTokenClassification",se]],["electra",["ElectraForTokenClassification",mr]],["esm",["EsmForTokenClassification",vn]],["convbert",["ConvBertForTokenClassification",nt]],["camembert",["CamembertForTokenClassification",Cs]],["deberta",["DebertaForTokenClassification",bs]],["deberta-v2",["DebertaV2ForTokenClassification",os]],["mpnet",["MPNetForTokenClassification",Gs]],["distilbert",["DistilBertForTokenClassification",js]],["roberta",["RobertaForTokenClassification",dr]],["xlm",["XLMForTokenClassification",yt]],["xlm-roberta",["XLMRobertaForTokenClassification",Zn]]]),gu=new Map([["t5",["T5ForConditionalGeneration",$n]],["longt5",["LongT5ForConditionalGeneration",xe]],["mt5",["MT5ForConditionalGeneration",le]],["bart",["BartForConditionalGeneration",Ke]],["mbart",["MBartForConditionalGeneration",qe]],["marian",["MarianMTModel",wd]],["m2m_100",["M2M100ForConditionalGeneration",bd]],["blenderbot",["BlenderbotForConditionalGeneration",Er]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ds]]]),Xi=new Map([["bloom",["BloomForCausalLM",Ml]],["gpt2",["GPT2LMHeadModel",Ra]],["jais",["JAISLMHeadModel",ja]],["gptj",["GPTJForCausalLM",Ha]],["gpt_bigcode",["GPTBigCodeForCausalLM",Xa]],["gpt_neo",["GPTNeoForCausalLM",Wa]],["gpt_neox",["GPTNeoXForCausalLM",Ga]],["codegen",["CodeGenForCausalLM",Ya]],["llama",["LlamaForCausalLM",Bo]],["olmo",["OlmoForCausalLM",tl]],["olmo2",["Olmo2ForCausalLM",sl]],["mobilellm",["MobileLLMForCausalLM",el]],["granite",["GraniteForCausalLM",nl]],["cohere",["CohereForCausalLM",ol]],["gemma",["GemmaForCausalLM",al]],["gemma2",["Gemma2ForCausalLM",ul]],["openelm",["OpenELMForCausalLM",cl]],["qwen2",["Qwen2ForCausalLM",hl]],["phi",["PhiForCausalLM",gl]],["phi3",["Phi3ForCausalLM",yl]],["mpt",["MptForCausalLM",vl]],["opt",["OPTForCausalLM",Tl]],["mbart",["MBartForCausalLM",Xt]],["mistral",["MistralForCausalLM",Vd]],["starcoder2",["Starcoder2ForCausalLM",uc]],["falcon",["FalconForCausalLM",Hd]],["trocr",["TrOCRForCausalLM",jd]],["stablelm",["StableLmForCausalLM",Jd]]]),wc=new Map([["multi_modality",["MultiModalityCausalLM",au]]]),wu=new Map([["bert",["BertForMaskedLM",tt]],["roformer",["RoFormerForMaskedLM",gt]],["electra",["ElectraForMaskedLM",tr]],["esm",["EsmForMaskedLM",Mn]],["convbert",["ConvBertForMaskedLM",Ge]],["camembert",["CamembertForMaskedLM",ns]],["deberta",["DebertaForMaskedLM",ys]],["deberta-v2",["DebertaV2ForMaskedLM",Ms]],["mpnet",["MPNetForMaskedLM",Vs]],["albert",["AlbertForMaskedLM",nr]],["distilbert",["DistilBertForMaskedLM",Us]],["roberta",["RobertaForMaskedLM",ms]],["xlm",["XLMWithLMHeadModel",Ar]],["xlm-roberta",["XLMRobertaForMaskedLM",ts]],["mobilebert",["MobileBertForMaskedLM",Jn]],["squeezebert",["SqueezeBertForMaskedLM",Tn]]]),yu=new Map([["bert",["BertForQuestionAnswering",Be]],["roformer",["RoFormerForQuestionAnswering",X]],["electra",["ElectraForQuestionAnswering",Sr]],["convbert",["ConvBertForQuestionAnswering",wt]],["camembert",["CamembertForQuestionAnswering",an]],["deberta",["DebertaForQuestionAnswering",$s]],["deberta-v2",["DebertaV2ForQuestionAnswering",ot]],["mpnet",["MPNetForQuestionAnswering",un]],["albert",["AlbertForQuestionAnswering",kn]],["distilbert",["DistilBertForQuestionAnswering",sr]],["roberta",["RobertaForQuestionAnswering",Tt]],["xlm",["XLMForQuestionAnswering",Pr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",wa]],["mobilebert",["MobileBertForQuestionAnswering",hs]],["squeezebert",["SqueezeBertForQuestionAnswering",Pn]]]),Qi=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]],["idefics3",["Idefics3ForConditionalGeneration",So]]]),g1=new Map([["llava",["LlavaForConditionalGeneration",eo]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",va]],["moondream1",["Moondream1ForConditionalGeneration",Fs]],["florence2",["Florence2ForConditionalGeneration",Ta]],["qwen2-vl",["Qwen2VLForConditionalGeneration",fl]],["idefics3",["Idefics3ForConditionalGeneration",So]],["paligemma",["PaliGemmaForConditionalGeneration",Pa]]]),yc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]]]),bu=new Map([["vit",["ViTForImageClassification",Pl]],["ijepa",["IJepaForImageClassification",kl]],["pvt",["PvtForImageClassification",Il]],["vit_msn",["ViTMSNForImageClassification",Dl]],["fastvit",["FastViTForImageClassification",zl]],["mobilevit",["MobileViTForImageClassification",Nl]],["mobilevitv2",["MobileViTV2ForImageClassification",Qu]],["beit",["BeitForImageClassification",Kl]],["deit",["DeiTForImageClassification",Ys]],["hiera",["HieraForImageClassification",pi]],["convnext",["ConvNextForImageClassification",co]],["convnextv2",["ConvNextV2ForImageClassification",Pi]],["dinov2",["Dinov2ForImageClassification",pd]],["resnet",["ResNetForImageClassification",Dn]],["swin",["SwinForImageClassification",td]],["segformer",["SegformerForImageClassification",xs]],["efficientnet",["EfficientNetForImageClassification",eu]],["mobilenet_v1",["MobileNetV1ForImageClassification",qr]],["mobilenet_v2",["MobileNetV2ForImageClassification",ji]],["mobilenet_v3",["MobileNetV3ForImageClassification",ru]],["mobilenet_v4",["MobileNetV4ForImageClassification",nu]]]),Mu=new Map([["detr",["DetrForObjectDetection",ql]],["rt_detr",["RTDetrForObjectDetection",Jl]],["table-transformer",["TableTransformerForObjectDetection",Xs]],["yolos",["YolosForObjectDetection",hd]]]),vu=new Map([["owlvit",["OwlViTForObjectDetection",cs]],["owlv2",["Owlv2ForObjectDetection",Vl]]]),xu=new Map([["detr",["DetrForSegmentation",li]],["clipseg",["CLIPSegForImageSegmentation",ro]]]),Tu=new Map([["segformer",["SegformerForSemanticSegmentation",Zs]],["sapiens",["SapiensForSemanticSegmentation",sd]]]),Eu=new Map([["detr",["DetrForSegmentation",li]],["maskformer",["MaskFormerForInstanceSegmentation",od]]]),Pu=new Map([["sam",["SamModel",fd]]]),Cu=new Map([["wav2vec2",["Wav2Vec2ForCTC",vd]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Id]],["unispeech",["UniSpeechForCTC",zn]],["unispeech-sat",["UniSpeechSatForCTC",$d]],["wavlm",["WavLMForCTC",Dd]],["hubert",["HubertForCTC",Od]]]),bc=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",xd]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",nc]],["unispeech",["UniSpeechForSequenceClassification",$i]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Sd]],["wavlm",["WavLMForSequenceClassification",Ld]],["hubert",["HubertForSequenceClassification",Fd]],["audio-spectrogram-transformer",["ASTForAudioClassification",Co]]]),Nn=new Map([["wavlm",["WavLMForXVector",ac]]]),Yi=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Si]],["wavlm",["WavLMForAudioFrameClassification",zd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",sc]],["pyannote",["PyAnnoteForAudioFrameClassification",Ed]]]),Ji=new Map([["vitmatte",["VitMatteForImageMatting",Rl]]]),ku=new Map([["patchtst",["PatchTSTForPrediction",cu]],["patchtsmixer",["PatchTSMixerForPrediction",hu]]]),Zi=new Map([["swin2sr",["Swin2SRForImageSuperResolution",gi]]]),$u=new Map([["dpt",["DPTForDepthEstimation",rd]],["depth_anything",["DepthAnythingForDepthEstimation",bi]],["glpn",["GLPNForDepthEstimation",ec]],["sapiens",["SapiensForDepthEstimation",Zu]],["depth_pro",["DepthProForDepthEstimation",Ln]]]),Su=new Map([["sapiens",["SapiensForNormalEstimation",nd]]]),ea=new Map([["vitpose",["VitPoseForPoseEstimation",Sl]]]),ta=new Map([["clip",["CLIPVisionModelWithProjection",Sa]],["siglip",["SiglipVisionModel",Oa]],["jina_clip",["JinaCLIPVisionModel",Hu]]]),Au=[[fc,B.EncoderOnly],[_1,B.EncoderDecoder],[_c,B.DecoderOnly],[fu,B.EncoderOnly],[_u,B.EncoderOnly],[gu,B.Seq2Seq],[qi,B.Seq2Seq],[Xi,B.DecoderOnly],[wc,B.MultiModality],[wu,B.EncoderOnly],[yu,B.EncoderOnly],[Qi,B.Vision2Seq],[g1,B.ImageTextToText],[bu,B.EncoderOnly],[xu,B.EncoderOnly],[Eu,B.EncoderOnly],[Tu,B.EncoderOnly],[Ji,B.EncoderOnly],[ku,B.EncoderOnly],[Zi,B.EncoderOnly],[$u,B.EncoderOnly],[Su,B.EncoderOnly],[ea,B.EncoderOnly],[Mu,B.EncoderOnly],[vu,B.EncoderOnly],[Pu,B.MaskGeneration],[Cu,B.EncoderOnly],[bc,B.EncoderOnly],[mu,B.Seq2Seq],[gc,B.EncoderOnly],[Nn,B.EncoderOnly],[Yi,B.EncoderOnly],[ta,B.EncoderOnly]];for(const[g,f]of Au)for(const[H,Te]of g.values())O.set(H,f),$.set(Te,H),w.set(H,Te);const Mc=[["MusicgenForConditionalGeneration",Bi,B.Musicgen],["CLIPTextModelWithProjection",$a,B.EncoderOnly],["SiglipTextModel",Ia,B.EncoderOnly],["JinaCLIPTextModel",za,B.EncoderOnly],["ClapTextModelWithProjection",qd,B.EncoderOnly],["ClapAudioModelWithProjection",Xd,B.EncoderOnly]];for(const[g,f,H]of Mc)O.set(g,H),$.set(f,g),w.set(g,f);class Iu extends fr{static MODEL_CLASS_MAPPINGS=Au.map(f=>f[0]);static BASE_IF_FAIL=!0}class vc extends fr{static MODEL_CLASS_MAPPINGS=[fu]}class xc extends fr{static MODEL_CLASS_MAPPINGS=[_u]}class Ou extends fr{static MODEL_CLASS_MAPPINGS=[gu]}class Tc extends fr{static MODEL_CLASS_MAPPINGS=[qi]}class Ec extends fr{static MODEL_CLASS_MAPPINGS=[mu]}class Pc extends fr{static MODEL_CLASS_MAPPINGS=[gc]}class Cc extends fr{static MODEL_CLASS_MAPPINGS=[Xi]}class w1 extends fr{static MODEL_CLASS_MAPPINGS=[wu]}class kc extends fr{static MODEL_CLASS_MAPPINGS=[yu]}class $c extends fr{static MODEL_CLASS_MAPPINGS=[Qi]}class Sc extends fr{static MODEL_CLASS_MAPPINGS=[bu]}class Ac extends fr{static MODEL_CLASS_MAPPINGS=[xu]}class y1 extends fr{static MODEL_CLASS_MAPPINGS=[Tu]}class Ic extends fr{static MODEL_CLASS_MAPPINGS=[Eu]}class Oc extends fr{static MODEL_CLASS_MAPPINGS=[Mu]}class Fc extends fr{static MODEL_CLASS_MAPPINGS=[vu]}class b1 extends fr{static MODEL_CLASS_MAPPINGS=[Pu]}class Dc extends fr{static MODEL_CLASS_MAPPINGS=[Cu]}class Lc extends fr{static MODEL_CLASS_MAPPINGS=[bc]}class zc extends fr{static MODEL_CLASS_MAPPINGS=[Nn]}class Bc extends fr{static MODEL_CLASS_MAPPINGS=[Yi]}class M1 extends fr{static MODEL_CLASS_MAPPINGS=[yc]}class Rc extends fr{static MODEL_CLASS_MAPPINGS=[Ji]}class Nc extends fr{static MODEL_CLASS_MAPPINGS=[Zi]}class jc extends fr{static MODEL_CLASS_MAPPINGS=[$u]}class Uc extends fr{static MODEL_CLASS_MAPPINGS=[Su]}class Wc extends fr{static MODEL_CLASS_MAPPINGS=[ea]}class Vc extends fr{static MODEL_CLASS_MAPPINGS=[ta]}class Gc extends Ve{constructor({logits:f,past_key_values:H,encoder_outputs:Te,decoder_attentions:$e=null,cross_attentions:Fe=null}){super(),this.logits=f,this.past_key_values=H,this.encoder_outputs=Te,this.decoder_attentions=$e,this.cross_attentions=Fe}}class Kt extends Ve{constructor({logits:f}){super(),this.logits=f}}class Fu extends Ve{constructor({logits:f,embeddings:H}){super(),this.logits=f,this.embeddings=H}}class Nr extends Ve{constructor({logits:f}){super(),this.logits=f}}class Wr extends Ve{constructor({logits:f}){super(),this.logits=f}}class Vr extends Ve{constructor({start_logits:f,end_logits:H}){super(),this.start_logits=f,this.end_logits=H}}class en extends Ve{constructor({logits:f}){super(),this.logits=f}}class Kc extends Ve{constructor({logits:f,past_key_values:H}){super(),this.logits=f,this.past_key_values=H}}class Du extends Ve{constructor({alphas:f}){super(),this.alphas=f}}class Lu extends Ve{constructor({waveform:f,spectrogram:H}){super(),this.waveform=f,this.spectrogram=H}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Me,v,s)=>{s.r(v),s.d(v,{ASTFeatureExtractor:()=>j});var _=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var A=s("./src/utils/audio.js");class j extends _.FeatureExtractor{constructor(U){super(U);const b=this.config.sampling_rate,T=(0,A.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(b/2),b,null,"kaldi",!0);for(let M=0;M{s.r(v),s.d(v,{AutoFeatureExtractor:()=>ee});var _=s("./src/utils/constants.js"),A=s("./src/utils/hub.js");s("./src/base/feature_extraction_utils.js");var j=s("./src/models/feature_extractors.js");class ee{static async from_pretrained(b,T={}){const M=await(0,A.getModelJSON)(b,_.FEATURE_EXTRACTOR_NAME,!0,T),x=M.feature_extractor_type,P=j[x];if(!P)throw new Error(`Unknown feature_extractor_type: '${x}'. Please report this at ${_.GITHUB_ISSUE_URL}.`);return new P(M)}}},"./src/models/auto/image_processing_auto.js":(Me,v,s)=>{s.r(v),s.d(v,{AutoImageProcessor:()=>U});var _=s("./src/utils/constants.js"),A=s("./src/utils/hub.js"),j=s("./src/base/image_processors_utils.js"),ee=s("./src/models/image_processors.js");class U{static async from_pretrained(T,M={}){const x=await(0,A.getModelJSON)(T,_.IMAGE_PROCESSOR_NAME,!0,M),P=x.image_processor_type??x.feature_extractor_type;let R=ee[P];return R||(P!==void 0&&console.warn(`Image processor type '${P}' not found, assuming base ImageProcessor. Please report this at ${_.GITHUB_ISSUE_URL}.`),R=j.ImageProcessor),new R(x)}}},"./src/models/auto/processing_auto.js":(Me,v,s)=>{s.r(v),s.d(v,{AutoProcessor:()=>T});var _=s("./src/utils/constants.js"),A=s("./src/utils/hub.js"),j=s("./src/base/processing_utils.js"),ee=s("./src/models/processors.js"),U=s("./src/models/image_processors.js"),b=s("./src/models/feature_extractors.js");class T{static async from_pretrained(x,P={}){const R=await(0,A.getModelJSON)(x,_.IMAGE_PROCESSOR_NAME,!0,P),{image_processor_type:Q,feature_extractor_type:ne,processor_class:de}=R;if(de&&ee[de])return ee[de].from_pretrained(x,P);if(!Q&&!ne)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const N={};if(Q){const q=U[Q];if(!q)throw new Error(`Unknown image_processor_type: '${Q}'.`);N.image_processor=new q(R)}if(ne){const q=U[ne];if(q)N.image_processor=new q(R);else{const B=b[ne];if(!B)throw new Error(`Unknown feature_extractor_type: '${ne}'.`);N.feature_extractor=new B(R)}}const K={};return new j.Processor(K,N)}}},"./src/models/beit/image_processing_beit.js":(Me,v,s)=>{s.r(v),s.d(v,{BeitFeatureExtractor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Me,v,s)=>{s.r(v),s.d(v,{BitImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Me,v,s)=>{s.r(v),s.d(v,{ChineseCLIPFeatureExtractor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Me,v,s)=>{s.r(v),s.d(v,{ClapFeatureExtractor:()=>j});var _=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var A=s("./src/utils/audio.js");class j extends _.FeatureExtractor{constructor(U){super(U),this.mel_filters=(0,A.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,A.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,A.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(U,b,T,M){let x;const P=U.length-b;if(P>0)if(T==="rand_trunc"){const R=Math.floor(Math.random()*(P+1));U=U.subarray(R,R+b),x=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${T}" not implemented`);else{if(P<0){let R=new Float64Array(b);if(R.set(U),M==="repeat")for(let Q=U.length;Q{s.r(v),s.d(v,{CLIPFeatureExtractor:()=>j,CLIPImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/convnext/image_processing_convnext.js":(Me,v,s)=>{s.r(v),s.d(v,{ConvNextFeatureExtractor:()=>j,ConvNextImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){const b=this.size?.shortest_edge;if(b===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(b<384){const T=Math.floor(b/this.crop_pct),[M,x]=this.get_resize_output_image_size(U,{shortest_edge:T});U=await U.resize(M,x,{resample:this.resample}),U=await U.center_crop(b,b)}else U=await U.resize(b,b,{resample:this.resample});return U}}class j extends A{}},"./src/models/deit/image_processing_deit.js":(Me,v,s)=>{s.r(v),s.d(v,{DeiTFeatureExtractor:()=>j,DeiTImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/detr/image_processing_detr.js":(Me,v,s)=>{s.r(v),s.d(v,{DetrFeatureExtractor:()=>ee,DetrImageProcessor:()=>j});var _=s("./src/base/image_processors_utils.js"),A=s("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(b){const T=await super._call(b),M=[T.pixel_values.dims[0],64,64],x=(0,A.full)(M,1n);return{...T,pixel_mask:x}}post_process_object_detection(...b){return(0,_.post_process_object_detection)(...b)}post_process_panoptic_segmentation(...b){return(0,_.post_process_panoptic_segmentation)(...b)}post_process_instance_segmentation(...b){return(0,_.post_process_instance_segmentation)(...b)}}class ee extends j{}},"./src/models/donut/image_processing_donut.js":(Me,v,s)=>{s.r(v),s.d(v,{DonutFeatureExtractor:()=>j,DonutImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{pad_image(U,b,T,M={}){const[x,P,R]=b;let Q=this.image_mean;Array.isArray(this.image_mean)||(Q=new Array(R).fill(Q));let ne=this.image_std;Array.isArray(ne)||(ne=new Array(R).fill(Q));const de=Q.map((N,K)=>-N/ne[K]);return super.pad_image(U,b,T,{center:!0,constant_values:de,...M})}}class j extends A{}},"./src/models/dpt/image_processing_dpt.js":(Me,v,s)=>{s.r(v),s.d(v,{DPTFeatureExtractor:()=>j,DPTImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Me,v,s)=>{s.r(v),s.d(v,{EfficientNetImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{constructor(ee){super(ee),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(U=>U*U))}}},"./src/models/feature_extractors.js":(Me,v,s)=>{s.r(v),s.d(v,{ASTFeatureExtractor:()=>_.ASTFeatureExtractor,ClapFeatureExtractor:()=>A.ClapFeatureExtractor,ImageFeatureExtractor:()=>x.ImageProcessor,PyAnnoteFeatureExtractor:()=>j.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>ee.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>U.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>b.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>T.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var _=s("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),A=s("./src/models/clap/feature_extraction_clap.js"),j=s("./src/models/pyannote/feature_extraction_pyannote.js"),ee=s("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),U=s("./src/models/speecht5/feature_extraction_speecht5.js"),b=s("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),T=s("./src/models/wespeaker/feature_extraction_wespeaker.js"),M=s("./src/models/whisper/feature_extraction_whisper.js"),x=s("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Me,v,s)=>{s.r(v),s.d(v,{Florence2Processor:()=>ee});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js");class ee extends _.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=A.AutoImageProcessor;constructor(b,T){super(b,T);const{tasks_answer_post_processing_type:M,task_prompts_without_inputs:x,task_prompts_with_input:P}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(M??{})),this.task_prompts_without_inputs=new Map(Object.entries(x??{})),this.task_prompts_with_input=new Map(Object.entries(P??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(b){typeof b=="string"&&(b=[b]);const T=[];for(const M of b)if(this.task_prompts_without_inputs.has(M))T.push(this.task_prompts_without_inputs.get(M));else{for(const[x,P]of this.task_prompts_with_input)if(M.includes(x)){T.push(P.replaceAll("{input}",M).replaceAll(x,""));break}T.length!==b.length&&T.push(M)}return T}post_process_generation(b,T,M){const x=this.tasks_answer_post_processing_type.get(T)??"pure_text";b=b.replaceAll("","").replaceAll("","");let P;switch(x){case"pure_text":P=b;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const R=x==="ocr"?"quad_boxes":"bboxes",Q=b.matchAll(this.regexes[R]),ne=[],de=[];for(const[N,K,...q]of Q)ne.push(K?K.trim():ne.at(-1)??""),de.push(q.map((B,O)=>(Number(B)+.5)/this.size_per_bin*M[O%2]));P={labels:ne,[R]:de};break;default:throw new Error(`Task "${T}" (of type "${x}") not yet implemented.`)}return{[T]:P}}async _call(b,T=null,M={}){if(!b&&!T)throw new Error("Either text or images must be provided");const x=await this.image_processor(b,M),P=T?this.tokenizer(T,M):{};return{...x,...P}}}},"./src/models/glpn/image_processing_glpn.js":(Me,v,s)=>{s.r(v),s.d(v,{GLPNFeatureExtractor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(Me,v,s)=>{s.r(v),s.d(v,{Idefics3ImageProcessor:()=>j});var _=s("./src/base/image_processors_utils.js"),A=s("./src/utils/tensor.js");class j extends _.ImageProcessor{constructor(U){super(U),this.do_image_splitting=U.do_image_splitting??!0,this.max_image_size=U.max_image_size}get_resize_for_vision_encoder(U,b){let[T,M]=U.dims.slice(-2);const x=M/T;return M>=T?(M=Math.ceil(M/b)*b,T=Math.floor(M/x),T=Math.ceil(T/b)*b):(T=Math.ceil(T/b)*b,M=Math.floor(T*x),M=Math.ceil(M/b)*b),{height:T,width:M}}async _call(U,{do_image_splitting:b=null,return_row_col_info:T=!1}={}){let M;if(!Array.isArray(U))M=[[U]];else{if(U.length===0||!U[0])throw new Error("No images provided.");Array.isArray(U[0])?M=U:M=[U]}let x=[],P=[],R=[];const Q=[],ne=[];for(const $ of M){let E=await Promise.all($.map(ae=>this.preprocess(ae)));Q.push(...E.map(ae=>ae.original_size)),ne.push(...E.map(ae=>ae.reshaped_input_size)),E.forEach(ae=>ae.pixel_values.unsqueeze_(0));const{longest_edge:Z}=this.max_image_size;let J;if(b??this.do_image_splitting){let ae=new Array(E.length),me=new Array(E.length);J=await Promise.all(E.map(async(ge,Ee)=>{const ve=this.get_resize_for_vision_encoder(ge.pixel_values,Z),Le=await(0,A.interpolate_4d)(ge.pixel_values,{size:[ve.height,ve.width]}),{frames:fe,num_splits_h:W,num_splits_w:ce}=await this.split_image(Le,this.max_image_size);return ae[Ee]=W,me[Ee]=ce,(0,A.cat)(fe,0)})),P.push(ae),R.push(me)}else{const ae=[Z,Z];J=await Promise.all(E.map(me=>(0,A.interpolate_4d)(me.pixel_values,{size:ae}))),P.push(new Array(E.length).fill(0)),R.push(new Array(E.length).fill(0))}x.push((0,A.cat)(J,0))}const de=x.length,[N,K,q,B]=x[0].dims;let O,w;if(de===1)O=x[0].unsqueeze_(0),w=(0,A.full)([de,N,q,B],!0);else{const $=Math.max(...x.map(J=>J.dims.at(0)));w=(0,A.full)([de,$,q,B],!0);const E=w.data,Z=$*q*B;for(let J=0;JT||R>M){Q=Math.ceil(P/T),ne=Math.ceil(R/M);const de=Math.ceil(P/Q),N=Math.ceil(R/ne);for(let B=0;B{s.r(v),s.d(v,{Idefics3Processor:()=>M});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js");s("./src/utils/image.js");var ee=s("./src/utils/core.js");function U(x,P,R,Q,ne,de){let N="";for(let K=0;K`+ne.repeat(x);N+=` `}return N+=` ${Q}${de}`+ne.repeat(x)+`${Q}`,N}function b(x,P,R,Q){return`${P}${Q}`+R.repeat(x)+`${P}`}function T(x,P,R,Q,ne,de){return x===0&&P===0?b(R,Q,ne,de):U(R,x,P,Q,ne,de)}class M extends _.Processor{static image_processor_class=A.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(P,R=null,Q={}){Q.return_row_col_info??=!0;let ne;R&&(ne=await this.image_processor(R,Q)),Array.isArray(P)||(P=[P]);const de=ne.rows??[new Array(P.length).fill(0)],N=ne.cols??[new Array(P.length).fill(0)],K=this.config.image_seq_len,q=[],B=[];for(let w=0;wT(ge,Z[Ee],K,this.fake_image_token,this.image_token,this.global_img_token)),ae=$.split(this.image_token);if(ae.length===0)throw new Error("The image token should be present in the text.");let me=ae[0];for(let ge=0;ge{s.r(v),s.d(v,{BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BitImageProcessor:()=>A.BitImageProcessor,CLIPFeatureExtractor:()=>ee.CLIPFeatureExtractor,CLIPImageProcessor:()=>ee.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>j.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>U.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>U.ConvNextImageProcessor,DPTFeatureExtractor:()=>x.DPTFeatureExtractor,DPTImageProcessor:()=>x.DPTImageProcessor,DeiTFeatureExtractor:()=>b.DeiTFeatureExtractor,DeiTImageProcessor:()=>b.DeiTImageProcessor,DetrFeatureExtractor:()=>T.DetrFeatureExtractor,DetrImageProcessor:()=>T.DetrImageProcessor,DonutFeatureExtractor:()=>M.DonutFeatureExtractor,DonutImageProcessor:()=>M.DonutImageProcessor,EfficientNetImageProcessor:()=>P.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>R.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>Q.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>de.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>N.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>K.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>q.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>q.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>B.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>B.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>O.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>O.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>w.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>w.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>$.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>$.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>E.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>E.MobileViTImageProcessor,NougatImageProcessor:()=>Z.NougatImageProcessor,OwlViTFeatureExtractor:()=>ae.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>ae.OwlViTImageProcessor,Owlv2ImageProcessor:()=>J.Owlv2ImageProcessor,PvtImageProcessor:()=>me.PvtImageProcessor,Qwen2VLImageProcessor:()=>ge.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Ee.RTDetrImageProcessor,SamImageProcessor:()=>ve.SamImageProcessor,SegformerFeatureExtractor:()=>Le.SegformerFeatureExtractor,SegformerImageProcessor:()=>Le.SegformerImageProcessor,SiglipImageProcessor:()=>fe.SiglipImageProcessor,Swin2SRImageProcessor:()=>W.Swin2SRImageProcessor,VLMImageProcessor:()=>ne.VLMImageProcessor,ViTFeatureExtractor:()=>ce.ViTFeatureExtractor,ViTImageProcessor:()=>ce.ViTImageProcessor,VitMatteImageProcessor:()=>_e.VitMatteImageProcessor,VitPoseImageProcessor:()=>Se.VitPoseImageProcessor,YolosFeatureExtractor:()=>Re.YolosFeatureExtractor,YolosImageProcessor:()=>Re.YolosImageProcessor});var _=s("./src/models/beit/image_processing_beit.js"),A=s("./src/models/bit/image_processing_bit.js"),j=s("./src/models/chinese_clip/image_processing_chinese_clip.js"),ee=s("./src/models/clip/image_processing_clip.js"),U=s("./src/models/convnext/image_processing_convnext.js"),b=s("./src/models/deit/image_processing_deit.js"),T=s("./src/models/detr/image_processing_detr.js"),M=s("./src/models/donut/image_processing_donut.js"),x=s("./src/models/dpt/image_processing_dpt.js"),P=s("./src/models/efficientnet/image_processing_efficientnet.js"),R=s("./src/models/glpn/image_processing_glpn.js"),Q=s("./src/models/idefics3/image_processing_idefics3.js"),ne=s("./src/models/janus/image_processing_janus.js"),de=s("./src/models/jina_clip/image_processing_jina_clip.js"),N=s("./src/models/llava_onevision/image_processing_llava_onevision.js"),K=s("./src/models/mask2former/image_processing_mask2former.js"),q=s("./src/models/maskformer/image_processing_maskformer.js"),B=s("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),O=s("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),w=s("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),$=s("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),E=s("./src/models/mobilevit/image_processing_mobilevit.js"),Z=s("./src/models/nougat/image_processing_nougat.js"),J=s("./src/models/owlv2/image_processing_owlv2.js"),ae=s("./src/models/owlvit/image_processing_owlvit.js"),me=s("./src/models/pvt/image_processing_pvt.js"),ge=s("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Ee=s("./src/models/rt_detr/image_processing_rt_detr.js"),ve=s("./src/models/sam/image_processing_sam.js"),Le=s("./src/models/segformer/image_processing_segformer.js"),fe=s("./src/models/siglip/image_processing_siglip.js"),W=s("./src/models/swin2sr/image_processing_swin2sr.js"),ce=s("./src/models/vit/image_processing_vit.js"),_e=s("./src/models/vitmatte/image_processing_vitmatte.js"),Se=s("./src/models/vitpose/image_processing_vitpose.js"),Re=s("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Me,v,s)=>{s.r(v),s.d(v,{VLMImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{constructor(ee){super({do_pad:!0,pad_size:{width:ee.image_size,height:ee.image_size},...ee}),this.constant_values=this.config.background_color.map(U=>U*this.rescale_factor)}pad_image(ee,U,b,T){return super.pad_image(ee,U,b,{constant_values:this.constant_values,center:!0,...T})}}},"./src/models/janus/processing_janus.js":(Me,v,s)=>{s.r(v),s.d(v,{VLChatProcessor:()=>T});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js"),ee=s("./src/utils/core.js"),U=s("./src/utils/tensor.js"),b=s("./src/utils/image.js");class T extends _.Processor{static image_processor_class=A.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;static uses_processor_config=!0;constructor(x,P){super(x,P),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:P=null,chat_template:R="default"}={}){P?Array.isArray(P)||(P=[P]):P=await Promise.all(x.filter(J=>J.images).flatMap(J=>J.images).map(J=>b.RawImage.read(J)));const Q=this.tokenizer,ne=Q.apply_chat_template(x,{tokenize:!1,add_generation_prompt:!0,chat_template:R}),de=J=>Q.encode(J,{add_special_tokens:!1}),N=ne.split(this.image_tag),K=N.length-1;if(P.length!==K)throw new Error(`Number of images provided (${P.length}) does not match number of "${this.image_tag}" image tags (${K})`);const[q,B,O]=Q.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=de(N[0]),$=new Array(w.length).fill(!1);for(let J=1;J0){const J=await this.image_processor(P);return J.pixel_values.unsqueeze_(0),{...Z,...J}}return Z}}},"./src/models/jina_clip/image_processing_jina_clip.js":(Me,v,s)=>{s.r(v),s.d(v,{JinaCLIPImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{constructor(ee){const{resize_mode:U,fill_color:b,interpolation:T,size:M,...x}=ee,P=U==="squash"?{width:M,height:M}:U==="shortest"?{shortest_edge:M}:{longest_edge:M},R=T==="bicubic"?3:2;super({...x,size:P,resample:R,do_center_crop:!0,crop_size:M,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Me,v,s)=>{s.r(v),s.d(v,{JinaCLIPProcessor:()=>ee});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js");class ee extends _.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=A.AutoImageProcessor;async _call(b=null,T=null,M={}){if(!b&&!T)throw new Error("Either text or images must be provided");const x=b?this.tokenizer(b,M):{},P=T?await this.image_processor(T,M):{};return{...x,...P}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Me,v,s)=>{s.r(v),s.d(v,{LlavaOnevisionImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Me,v,s)=>{s.r(v),s.d(v,{Mask2FormerImageProcessor:()=>A});var _=s("./src/models/maskformer/image_processing_maskformer.js");class A extends _.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Me,v,s)=>{s.r(v),s.d(v,{MaskFormerFeatureExtractor:()=>j,MaskFormerImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{post_process_panoptic_segmentation(...U){return(0,_.post_process_panoptic_segmentation)(...U)}post_process_instance_segmentation(...U){return(0,_.post_process_instance_segmentation)(...U)}}class j extends A{}},"./src/models/mgp_str/processing_mgp_str.js":(Me,v,s)=>{s.r(v),s.d(v,{MgpstrProcessor:()=>b});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js"),ee=s("./src/utils/maths.js");const U={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class b extends _.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=A.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(M,x){if(!U.hasOwnProperty(x))throw new Error(`Format ${x} is not supported.`);const[P,R]=U[x],Q=this[P].bind(this),[ne,de]=M.dims,N=[],K=[],q=M.tolist();for(let O=0;O0?E.reduce((J,ae)=>J*ae,1):0;K.push($),N.push(Z)}return[Q(K),N]}char_decode(M){return this.char_tokenizer.batch_decode(M).map(x=>x.replaceAll(" ",""))}bpe_decode(M){return this.bpe_tokenizer.batch_decode(M)}wp_decode(M){return this.wp_tokenizer.batch_decode(M).map(x=>x.replaceAll(" ",""))}batch_decode([M,x,P]){const[R,Q]=this._decode_helper(M,"char"),[ne,de]=this._decode_helper(x,"bpe"),[N,K]=this._decode_helper(P,"wp"),q=[],B=[];for(let O=0;O{s.r(v),s.d(v,{MobileNetV1FeatureExtractor:()=>j,MobileNetV1ImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Me,v,s)=>{s.r(v),s.d(v,{MobileNetV2FeatureExtractor:()=>j,MobileNetV2ImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Me,v,s)=>{s.r(v),s.d(v,{MobileNetV3FeatureExtractor:()=>j,MobileNetV3ImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Me,v,s)=>{s.r(v),s.d(v,{MobileNetV4FeatureExtractor:()=>j,MobileNetV4ImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Me,v,s)=>{s.r(v),s.d(v,{MobileViTFeatureExtractor:()=>j,MobileViTImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/nougat/image_processing_nougat.js":(Me,v,s)=>{s.r(v),s.d(v,{NougatImageProcessor:()=>A});var _=s("./src/models/donut/image_processing_donut.js");class A extends _.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Me,v,s)=>{s.r(v),s.d(v,{Owlv2ImageProcessor:()=>A});var _=s("./src/models/owlvit/image_processing_owlvit.js");class A extends _.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Me,v,s)=>{s.r(v),s.d(v,{OwlViTFeatureExtractor:()=>j,OwlViTImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{post_process_object_detection(...U){return(0,_.post_process_object_detection)(...U)}}class j extends A{}},"./src/models/owlvit/processing_owlvit.js":(Me,v,s)=>{s.r(v),s.d(v,{OwlViTProcessor:()=>ee});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js");class ee extends _.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=A.AutoImageProcessor}},"./src/models/paligemma/processing_paligemma.js":(Me,v,s)=>{s.r(v),s.d(v,{PaliGemmaProcessor:()=>b});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js");const ee="";function U(T,M,x,P,R){return`${P.repeat(x*R)}${M}${T} `}class b extends _.Processor{static tokenizer_class=j.AutoTokenizer;static image_processor_class=A.AutoImageProcessor;static uses_processor_config=!1;async _call(M,x=null,P={}){x||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),x=""),Array.isArray(M)||(M=[M]),Array.isArray(x)||(x=[x]);const R=this.tokenizer.bos_token,Q=this.image_processor.config.image_seq_length;let ne;x.some(K=>K.includes(ee))?ne=x.map(K=>{const q=K.replaceAll(ee,ee.repeat(Q)),B=q.lastIndexOf(ee),O=B===-1?0:B+ee.length;return q.slice(0,O)+R+q.slice(O)+` `}):(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."),ne=x.map(K=>U(K,R,Q,ee,M.length)));const de=this.tokenizer(ne,P);return{...await this.image_processor(M,P),...de}}}},"./src/models/processors.js":(Me,v,s)=>{s.r(v),s.d(v,{Florence2Processor:()=>_.Florence2Processor,Idefics3Processor:()=>j.Idefics3Processor,JinaCLIPProcessor:()=>U.JinaCLIPProcessor,MgpstrProcessor:()=>A.MgpstrProcessor,OwlViTProcessor:()=>b.OwlViTProcessor,PaliGemmaProcessor:()=>T.PaliGemmaProcessor,PyAnnoteProcessor:()=>M.PyAnnoteProcessor,Qwen2VLProcessor:()=>x.Qwen2VLProcessor,SamProcessor:()=>P.SamProcessor,SpeechT5Processor:()=>R.SpeechT5Processor,VLChatProcessor:()=>ee.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>Q.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>ne.WhisperProcessor});var _=s("./src/models/florence2/processing_florence2.js"),A=s("./src/models/mgp_str/processing_mgp_str.js"),j=s("./src/models/idefics3/processing_idefics3.js"),ee=s("./src/models/janus/processing_janus.js"),U=s("./src/models/jina_clip/processing_jina_clip.js"),b=s("./src/models/owlvit/processing_owlvit.js"),T=s("./src/models/paligemma/processing_paligemma.js"),M=s("./src/models/pyannote/processing_pyannote.js"),x=s("./src/models/qwen2_vl/processing_qwen2_vl.js"),P=s("./src/models/sam/processing_sam.js"),R=s("./src/models/speecht5/processing_speecht5.js"),Q=s("./src/models/wav2vec2/processing_wav2vec2.js"),ne=s("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Me,v,s)=>{s.r(v),s.d(v,{PvtImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Me,v,s)=>{s.r(v),s.d(v,{PyAnnoteFeatureExtractor:()=>j});var _=s("./src/base/feature_extraction_utils.js"),A=s("./src/utils/tensor.js");class j extends _.FeatureExtractor{async _call(U){(0,_.validate_audio_inputs)(U,"PyAnnoteFeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));const b=[1,1,U.length];return{input_values:new A.Tensor("float32",U,b)}}}},"./src/models/pyannote/processing_pyannote.js":(Me,v,s)=>{s.r(v),s.d(v,{PyAnnoteProcessor:()=>ee});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/feature_extraction_auto.js"),j=s("./src/utils/maths.js");class ee extends _.Processor{static feature_extractor_class=A.AutoFeatureExtractor;async _call(b){return await this.feature_extractor(b)}samples_to_frames(b){return(b-this.config.offset)/this.config.step}post_process_speaker_diarization(b,T){const M=T/this.samples_to_frames(T)/this.config.sampling_rate,x=[];for(const P of b.tolist()){const R=[];let Q=-1;for(let ne=0;ne({id:ne,start:de*M,end:N*M,confidence:K/(N-de)})))}return x}}},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Me,v,s)=>{s.r(v),s.d(v,{Qwen2VLImageProcessor:()=>j});var _=s("./src/base/image_processors_utils.js"),A=s("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(U,...b){const{pixel_values:T,original_sizes:M,reshaped_input_sizes:x}=await super._call(U,...b);let P=T;const{temporal_patch_size:R,merge_size:Q,patch_size:ne}=this.config;P.dims[0]===1&&(P=(0,A.cat)(Array.from({length:R},()=>P),0));const de=P.dims[0]/R,N=P.dims[1],K=Math.floor(P.dims[2]/ne),q=Math.floor(P.dims[3]/ne),B=P.view(de,R,N,Math.floor(K/Q),Q,ne,Math.floor(q/Q),Q,ne).permute(0,3,6,4,7,2,1,5,8).view(de*K*q,N*R*ne*ne),O=new A.Tensor("int64",[de,K,q],[1,3]);return{pixel_values:B,image_grid_thw:O,original_sizes:M,reshaped_input_sizes:x}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Me,v,s)=>{s.r(v),s.d(v,{Qwen2VLProcessor:()=>ee});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js"),j=s("./src/tokenizers.js");s("./src/utils/image.js");class ee extends _.Processor{static image_processor_class=A.AutoImageProcessor;static tokenizer_class=j.AutoTokenizer;async _call(b,T=null,...M){Array.isArray(b)||(b=[b]);let x,P;if(T&&(x=await this.image_processor(T),P=x.image_grid_thw),P){let Q=this.image_processor.config.merge_size**2,ne=0;const de=P.tolist();b=b.map(N=>{for(;N.includes("<|image_pad|>");){const K=Number(de[ne++].reduce((q,B)=>q*B,1n));N=N.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(K/Q)))}return N.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(b),...x}}}},"./src/models/rt_detr/image_processing_rt_detr.js":(Me,v,s)=>{s.r(v),s.d(v,{RTDetrImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{post_process_object_detection(...ee){return(0,_.post_process_object_detection)(...ee)}}},"./src/models/sam/image_processing_sam.js":(Me,v,s)=>{s.r(v),s.d(v,{SamImageProcessor:()=>ee});var _=s("./src/base/image_processors_utils.js"),A=s("./src/utils/core.js"),j=s("./src/utils/tensor.js");class ee extends _.ImageProcessor{reshape_input_points(b,T,M,x=!1){b=structuredClone(b);let P=(0,A.calculateDimensions)(b);if(P.length===3)x||(P=[1,...P]),b=[b];else if(P.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 R=0;Rx!==T.dims[P]))throw Error(`The first ${M.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j.Tensor("int64",b.flat(1/0).map(BigInt),M)}async _call(b,{input_points:T=null,input_labels:M=null,input_boxes:x=null}={}){const P=await super._call(b);if(T&&(P.input_points=this.reshape_input_points(T,P.original_sizes,P.reshaped_input_sizes)),M){if(!P.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");P.input_labels=this.add_input_labels(M,P.input_points)}return x&&(P.input_boxes=this.reshape_input_points(x,P.original_sizes,P.reshaped_input_sizes,!0)),P}async post_process_masks(b,T,M,{mask_threshold:x=0,binarize:P=!0,pad_size:R=null}={}){const Q=[];R=R??this.pad_size;const ne=[R.height,R.width];for(let de=0;dex&&(O[w]=1);q=new j.Tensor("bool",O,q.dims)}Q.push(q)}return Q}generate_crop_boxes(b,T,{crop_n_layers:M=0,overlap_ratio:x=.3413333333333333,points_per_crop:P=32,crop_n_points_downscale_factor:R=1}={}){}}},"./src/models/sam/processing_sam.js":(Me,v,s)=>{s.r(v),s.d(v,{SamProcessor:()=>j});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/image_processing_auto.js");class j extends _.Processor{static image_processor_class=A.AutoImageProcessor;async _call(...U){return await this.image_processor(...U)}post_process_masks(...U){return this.image_processor.post_process_masks(...U)}reshape_input_points(...U){return this.image_processor.reshape_input_points(...U)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Me,v,s)=>{s.r(v),s.d(v,{SeamlessM4TFeatureExtractor:()=>ee});var _=s("./src/base/feature_extraction_utils.js"),A=s("./src/utils/tensor.js"),j=s("./src/utils/audio.js");class ee extends _.FeatureExtractor{constructor(b){super(b);const T=this.config.sampling_rate,M=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(T/2),T,null,"kaldi",!0);for(let x=0;xM*32768),(0,j.spectrogram)(b,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:T,transpose:!0})}async _call(b,{padding:T=!0,pad_to_multiple_of:M=2,do_normalize_per_mel_bins:x=!0,return_attention_mask:P=!0}={}){(0,_.validate_audio_inputs)(b,"SeamlessM4TFeatureExtractor");let R=await this._extract_fbank_features(b,this.config.max_length);if(x){const[O,w]=R.dims,$=R.data;for(let E=0;E0){const Z=new Float32Array(w*(O+E));Z.set($),Z.fill(this.config.padding_value,$.length);const J=O+E;R=new A.Tensor(R.type,Z,[J,w]),P&&(Q=new A.Tensor("int64",new BigInt64Array(J),[1,J]),Q.data.fill(1n,0,O))}}const[ne,de]=R.dims,N=this.config.stride;if(ne%N!==0)throw new Error(`The number of frames (${ne}) must be a multiple of the stride (${N}).`);const q=R.view(1,Math.floor(ne/N),de*N),B={input_features:q};if(P){const O=q.dims[1],w=new BigInt64Array(O);if(Q){const $=Q.data;for(let E=1,Z=0;E{s.r(v),s.d(v,{SegformerFeatureExtractor:()=>j,SegformerImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{post_process_semantic_segmentation(...U){return(0,_.post_process_semantic_segmentation)(...U)}}class j extends A{}},"./src/models/siglip/image_processing_siglip.js":(Me,v,s)=>{s.r(v),s.d(v,{SiglipImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Me,v,s)=>{s.r(v),s.d(v,{SpeechT5FeatureExtractor:()=>A});var _=s("./src/base/feature_extraction_utils.js");class A extends _.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Me,v,s)=>{s.r(v),s.d(v,{SpeechT5Processor:()=>ee});var _=s("./src/base/processing_utils.js"),A=s("./src/tokenizers.js"),j=s("./src/models/auto/feature_extraction_auto.js");class ee extends _.Processor{static tokenizer_class=A.AutoTokenizer;static feature_extractor_class=j.AutoFeatureExtractor;async _call(b){return await this.feature_extractor(b)}}},"./src/models/swin2sr/image_processing_swin2sr.js":(Me,v,s)=>{s.r(v),s.d(v,{Swin2SRImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{pad_image(ee,U,b,T={}){const[M,x,P]=U;return super.pad_image(ee,U,{width:x+(b-x%b)%b,height:M+(b-M%b)%b},{mode:"symmetric",center:!1,constant_values:-1,...T})}}},"./src/models/vit/image_processing_vit.js":(Me,v,s)=>{s.r(v),s.d(v,{ViTFeatureExtractor:()=>j,ViTImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{}class j extends A{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Me,v,s)=>{s.r(v),s.d(v,{VitMatteImageProcessor:()=>j});var _=s("./src/base/image_processors_utils.js"),A=s("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(U,b){Array.isArray(U)||(U=[U]),Array.isArray(b)||(b=[b]);const T=await Promise.all(U.map(P=>this.preprocess(P))),M=await Promise.all(b.map(P=>this.preprocess(P,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,A.stack)(T.map((P,R)=>(0,A.cat)([P.pixel_values,M[R].pixel_values],0)),0),original_sizes:T.map(P=>P.original_size),reshaped_input_sizes:T.map(P=>P.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Me,v,s)=>{s.r(v),s.d(v,{VitPoseImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{post_process_pose_estimation(ee,U,{threshold:b=null}={}){const T=ee.tolist(),[M,x,P,R]=ee.dims,Q=[];for(let ne=0;ne{s.r(v),s.d(v,{Wav2Vec2FeatureExtractor:()=>j});var _=s("./src/base/feature_extraction_utils.js"),A=s("./src/utils/tensor.js");class j extends _.FeatureExtractor{_zero_mean_unit_var_norm(U){const T=U.reduce((x,P)=>x+P,0)/U.length,M=U.reduce((x,P)=>x+(P-T)**2,0)/U.length;return U.map(x=>(x-T)/Math.sqrt(M+1e-7))}async _call(U){(0,_.validate_audio_inputs)(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let b=U;this.config.do_normalize&&(b=this._zero_mean_unit_var_norm(b));const T=[1,b.length];return{input_values:new A.Tensor("float32",b,T),attention_mask:new A.Tensor("int64",new BigInt64Array(b.length).fill(1n),T)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Me,v,s)=>{s.r(v),s.d(v,{Wav2Vec2ProcessorWithLM:()=>j});var _=s("./src/base/processing_utils.js"),A=s("./src/models/auto/feature_extraction_auto.js");class j extends _.Processor{static feature_extractor_class=A.AutoFeatureExtractor;async _call(U){return await this.feature_extractor(U)}}},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Me,v,s)=>{s.r(v),s.d(v,{WeSpeakerFeatureExtractor:()=>j});var _=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var A=s("./src/utils/audio.js");class j extends _.FeatureExtractor{constructor(U){super(U);const b=this.config.sampling_rate,T=(0,A.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(b/2),b,null,"kaldi",!0);for(let M=0;Mb*32768),(0,A.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){(0,_.validate_audio_inputs)(U,"WeSpeakerFeatureExtractor");const b=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const T=b.mean(1).data,M=b.data,[x,P,R]=b.dims;for(let Q=0;Q{s.r(v),s.d(v,{WHISPER_LANGUAGE_MAPPING:()=>A,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>j,whisper_language_to_code:()=>ee});const _=[["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"]],A=new Map(_),j=new Map([..._.map(([U,b])=>[b,U]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ee(U){U=U.toLowerCase();let b=j.get(U);if(b===void 0)if(A.has(U))b=U;else{const M=U.length===2?A.keys():A.values();throw new Error(`Language "${U}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return b}},"./src/models/whisper/feature_extraction_whisper.js":(Me,v,s)=>{s.r(v),s.d(v,{WhisperFeatureExtractor:()=>ee});var _=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var A=s("./src/utils/audio.js"),j=s("./src/utils/maths.js");class ee extends _.FeatureExtractor{constructor(b){super(b),this.config.mel_filters??=(0,A.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,A.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(b){const T=await(0,A.spectrogram)(b,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),M=T.data,x=(0,j.max)(M)[0];for(let P=0;Pthis.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=b.slice(0,this.config.n_samples)):(T=new Float32Array(this.config.n_samples),T.set(b)),{input_features:(await this._extract_fbank_features(T)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(Me,v,s)=>{s.r(v),s.d(v,{WhisperGenerationConfig:()=>A});var _=s("./src/generation/configuration_utils.js");class A extends _.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":(Me,v,s)=>{s.r(v),s.d(v,{WhisperProcessor:()=>ee});var _=s("./src/models/auto/feature_extraction_auto.js"),A=s("./src/tokenizers.js"),j=s("./src/base/processing_utils.js");class ee extends j.Processor{static tokenizer_class=A.AutoTokenizer;static feature_extractor_class=_.AutoFeatureExtractor;async _call(b){return await this.feature_extractor(b)}}},"./src/models/yolos/image_processing_yolos.js":(Me,v,s)=>{s.r(v),s.d(v,{YolosFeatureExtractor:()=>j,YolosImageProcessor:()=>A});var _=s("./src/base/image_processors_utils.js");class A extends _.ImageProcessor{post_process_object_detection(...U){return(0,_.post_process_object_detection)(...U)}}class j extends A{}},"./src/ops/registry.js":(Me,v,s)=>{s.r(v),s.d(v,{TensorOpRegistry:()=>ee});var _=s("./src/backends/onnx.js"),A=s("./src/utils/tensor.js");const j=async(U,b,T)=>{const M=await(0,_.createInferenceSession)(new Uint8Array(U),b);return async x=>{const P=Object.fromEntries(Object.entries(x).map(([Q,ne])=>[Q,ne.ort_tensor])),R=await M.run(P);return Array.isArray(T)?T.map(Q=>new A.Tensor(R[Q])):new A.Tensor(R[T])}};class ee{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=j([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=j([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=j([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=j([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=j([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=j([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}},"./src/pipelines.js":(Me,v,s)=>{s.r(v),s.d(v,{AudioClassificationPipeline:()=>me,AutomaticSpeechRecognitionPipeline:()=>Ee,DepthEstimationPipeline:()=>Qe,DocumentQuestionAnsweringPipeline:()=>Se,FeatureExtractionPipeline:()=>J,FillMaskPipeline:()=>q,ImageClassificationPipeline:()=>Le,ImageFeatureExtractionPipeline:()=>ae,ImageSegmentationPipeline:()=>fe,ImageToImagePipeline:()=>We,ImageToTextPipeline:()=>ve,ObjectDetectionPipeline:()=>ce,Pipeline:()=>ne,QuestionAnsweringPipeline:()=>K,SummarizationPipeline:()=>O,Text2TextGenerationPipeline:()=>B,TextClassificationPipeline:()=>de,TextGenerationPipeline:()=>E,TextToAudioPipeline:()=>Re,TokenClassificationPipeline:()=>N,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>ge,ZeroShotClassificationPipeline:()=>Z,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>_e,pipeline:()=>oe});var _=s("./src/tokenizers.js"),A=s("./src/models.js"),j=s("./src/models/auto/processing_auto.js");s("./src/base/processing_utils.js");var ee=s("./src/utils/generic.js"),U=s("./src/utils/core.js"),b=s("./src/utils/maths.js"),T=s("./src/utils/audio.js"),M=s("./src/utils/tensor.js"),x=s("./src/utils/image.js");async function P(Ne){return Array.isArray(Ne)||(Ne=[Ne]),await Promise.all(Ne.map(ue=>x.RawImage.read(ue)))}async function R(Ne,ue){return Array.isArray(Ne)||(Ne=[Ne]),await Promise.all(Ne.map(ke=>typeof ke=="string"||ke instanceof URL?(0,T.read_audio)(ke,ue):ke instanceof Float64Array?new Float32Array(ke):ke))}function Q(Ne,ue){ue&&(Ne=Ne.map(Be=>Be|0));const[ke,tt,He,Xe]=Ne;return{xmin:ke,ymin:tt,xmax:He,ymax:Xe}}class ne extends ee.Callable{constructor({task:ue,model:ke,tokenizer:tt=null,processor:He=null}){super(),this.task=ue,this.model=ke,this.tokenizer=tt,this.processor=He}async dispose(){await this.model.dispose()}}class de extends ne{constructor(ue){super(ue)}async _call(ue,{top_k:ke=1}={}){const tt=this.tokenizer(ue,{padding:!0,truncation:!0}),He=await this.model(tt),Xe=this.model.config.problem_type==="multi_label_classification"?lt=>lt.sigmoid():lt=>new M.Tensor("float32",(0,b.softmax)(lt.data),lt.dims),Be=this.model.config.id2label,st=[];for(const lt of He.logits){const xt=Xe(lt),ut=await(0,M.topk)(xt,ke),gt=ut[0].tolist(),se=ut[1].tolist().map((X,he)=>({label:Be?Be[X]:`LABEL_${X}`,score:gt[he]}));ke===1?st.push(...se):st.push(se)}return Array.isArray(ue)||ke===1?st:st[0]}}class N extends ne{constructor(ue){super(ue)}async _call(ue,{ignore_labels:ke=["O"]}={}){const tt=Array.isArray(ue),He=this.tokenizer(tt?ue:[ue],{padding:!0,truncation:!0}),Be=(await this.model(He)).logits,st=this.model.config.id2label,lt=[];for(let xt=0;xtnt==this.tokenizer.sep_token_id);lt[gt].map((nt,wt)=>nt==1&&(wt===0||wt>se&&xt.findIndex(pt=>pt==I[wt])===-1));const X=Xe[gt].tolist(),he=Be[gt].tolist();for(let nt=1;ntwt==I[nt])!==-1)&&(X[nt]=-1/0,he[nt]=-1/0);const Ae=(0,b.softmax)(X).map((nt,wt)=>[nt,wt]),Ge=(0,b.softmax)(he).map((nt,wt)=>[nt,wt]);Ae[0][0]=0,Ge[0][0]=0;const Je=(0,U.product)(Ae,Ge).filter(nt=>nt[0][1]<=nt[1][1]).map(nt=>[nt[0][1],nt[1][1],nt[0][0]*nt[1][0]]).sort((nt,wt)=>wt[2]-nt[2]);for(let nt=0;ntX==this.tokenizer.mask_token_id);if(xt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ut=He[st][xt],gt=await(0,M.topk)(new M.Tensor("float32",(0,b.softmax)(ut.data),ut.dims),ke),I=gt[0].tolist(),se=gt[1].tolist();Xe.push(se.map((X,he)=>{const Ae=lt.slice();return Ae[xt]=X,{score:I[he],token:Number(X),token_str:this.tokenizer.model.vocab[X],sequence:this.tokenizer.decode(Ae,{skip_special_tokens:!0})}}))}return Array.isArray(ue)?Xe:Xe[0]}}class B extends ne{_key="generated_text";constructor(ue){super(ue)}async _call(ue,ke={}){Array.isArray(ue)||(ue=[ue]),this.model.config.prefix&&(ue=ue.map(lt=>this.model.config.prefix+lt));const tt=this.model.config.task_specific_params;tt&&tt[this.task]&&tt[this.task].prefix&&(ue=ue.map(lt=>tt[this.task].prefix+lt));const He=this.tokenizer,Xe={padding:!0,truncation:!0};let Be;this instanceof w&&"_build_translation_inputs"in He?Be=He._build_translation_inputs(ue,Xe,ke):Be=He(ue,Xe);const st=await this.model.generate({...Be,...ke});return He.batch_decode(st,{skip_special_tokens:!0}).map(lt=>({[this._key]:lt}))}}class O extends B{_key="summary_text";constructor(ue){super(ue)}}class w extends B{_key="translation_text";constructor(ue){super(ue)}}function $(Ne){return Array.isArray(Ne)&&Ne.every(ue=>"role"in ue&&"content"in ue)}class E extends ne{constructor(ue){super(ue)}async _call(ue,ke={}){let tt=!1,He=!1,Xe;if(typeof ue=="string")Xe=ue=[ue];else if(Array.isArray(ue)&&ue.every(se=>typeof se=="string"))tt=!0,Xe=ue;else{if($(ue))ue=[ue];else if(Array.isArray(ue)&&ue.every($))tt=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");He=!0,Xe=ue.map(se=>this.tokenizer.apply_chat_template(se,{tokenize:!1,add_generation_prompt:!0}))}const Be=ke.add_special_tokens??!1,st=He?!1:ke.return_full_text??!0;this.tokenizer.padding_side="left";const lt=this.tokenizer(Xe,{add_special_tokens:Be,padding:!0,truncation:!0}),xt=await this.model.generate({...lt,...ke}),ut=this.tokenizer.batch_decode(xt,{skip_special_tokens:!0});let gt;!st&<.input_ids.dims.at(-1)>0&&(gt=this.tokenizer.batch_decode(lt.input_ids,{skip_special_tokens:!0}).map(se=>se.length));const I=Array.from({length:ue.length},se=>[]);for(let se=0;se[ke.toLowerCase(),tt])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(ue,ke,{hypothesis_template:tt="This example is {}.",multi_label:He=!1}={}){const Xe=Array.isArray(ue);Xe||(ue=[ue]),Array.isArray(ke)||(ke=[ke]);const Be=ke.map(xt=>tt.replace("{}",xt)),st=He||ke.length===1,lt=[];for(const xt of ue){const ut=[];for(const se of Be){const X=this.tokenizer(xt,{text_pair:se,padding:!0,truncation:!0}),he=await this.model(X);st?ut.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):ut.push(he.logits.data[this.entailment_id])}const I=(st?ut.map(se=>(0,b.softmax)(se)[1]):(0,b.softmax)(ut)).map((se,X)=>[se,X]).sort((se,X)=>X[0]-se[0]);lt.push({sequence:xt,labels:I.map(se=>ke[se[1]]),scores:I.map(se=>se[0])})}return Xe?lt:lt[0]}}class J extends ne{constructor(ue){super(ue)}async _call(ue,{pooling:ke="none",normalize:tt=!1,quantize:He=!1,precision:Xe="binary"}={}){const Be=this.tokenizer(ue,{padding:!0,truncation:!0}),st=await this.model(Be);let lt=st.last_hidden_state??st.logits??st.token_embeddings;if(ke!=="none")if(ke==="mean")lt=(0,M.mean_pooling)(lt,Be.attention_mask);else if(ke==="cls")lt=lt.slice(null,0);else throw Error(`Pooling method '${ke}' not supported.`);return tt&&(lt=lt.normalize(2,-1)),He&&(lt=(0,M.quantize_embeddings)(lt,Xe)),lt}}class ae extends ne{constructor(ue){super(ue)}async _call(ue,{pool:ke=null}={}){const tt=await P(ue),{pixel_values:He}=await this.processor(tt),Xe=await this.model({pixel_values:He});let Be;if(ke){if(!("pooler_output"in Xe))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Be=Xe.pooler_output}else Be=Xe.last_hidden_state??Xe.logits??Xe.image_embeds;return Be}}class me extends ne{constructor(ue){super(ue)}async _call(ue,{top_k:ke=5}={}){const tt=this.processor.feature_extractor.config.sampling_rate,He=await R(ue,tt),Xe=this.model.config.id2label,Be=[];for(const st of He){const lt=await this.processor(st),ut=(await this.model(lt)).logits[0],gt=await(0,M.topk)(new M.Tensor("float32",(0,b.softmax)(ut.data),ut.dims),ke),I=gt[0].tolist(),X=gt[1].tolist().map((he,Ae)=>({label:Xe?Xe[he]:`LABEL_${he}`,score:I[Ae]}));Be.push(X)}return Array.isArray(ue)?Be:Be[0]}}class ge extends ne{constructor(ue){super(ue)}async _call(ue,ke,{hypothesis_template:tt="This is a sound of {}."}={}){const He=!Array.isArray(ue);He&&(ue=[ue]);const Xe=ke.map(ut=>tt.replace("{}",ut)),Be=this.tokenizer(Xe,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,lt=await R(ue,st),xt=[];for(const ut of lt){const gt=await this.processor(ut),I=await this.model({...Be,...gt}),se=(0,b.softmax)(I.logits_per_audio.data);xt.push([...se].map((X,he)=>({score:X,label:ke[he]})))}return He?xt[0]:xt}}class Ee extends ne{constructor(ue){super(ue)}async _call(ue,ke={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ue,ke);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ue,ke);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ue,ke){ke.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ke.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const tt=!Array.isArray(ue);tt&&(ue=[ue]);const He=this.processor.feature_extractor.config.sampling_rate,Xe=await R(ue,He),Be=[];for(const st of Xe){const lt=await this.processor(st),ut=(await this.model(lt)).logits[0],gt=[];for(const se of ut)gt.push((0,b.max)(se.data)[1]);const I=this.tokenizer.decode(gt);Be.push({text:I})}return tt?Be[0]:Be}async _call_whisper(ue,ke){const tt=ke.return_timestamps??!1,He=ke.chunk_length_s??0,Xe=ke.force_full_sequences??!1;let Be=ke.stride_length_s??null;const st={...ke};tt==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const lt=!Array.isArray(ue);lt&&(ue=[ue]);const xt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ut=this.processor.feature_extractor.config.hop_length,gt=this.processor.feature_extractor.config.sampling_rate,I=await R(ue,gt),se=[];for(const X of I){let he=[];if(He>0){if(Be===null)Be=He/6;else if(He<=Be)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Je=gt*He,nt=gt*Be,wt=Je-2*nt;let pt=0;for(;;){const Qt=pt+Je,tr=X.subarray(pt,Qt),Tr=await this.processor(tr),mr=pt===0,Sr=Qt>=X.length;if(he.push({stride:[tr.length,mr?0:nt,Sr?0:nt],input_features:Tr.input_features,is_last:Sr}),Sr)break;pt+=wt}}else he=[{stride:[X.length,0,0],input_features:(await this.processor(X)).input_features,is_last:!0}];for(const Je of he){st.num_frames=Math.floor(Je.stride[0]/ut);const nt=await this.model.generate({inputs:Je.input_features,...st});tt==="word"?(Je.tokens=nt.sequences.tolist()[0],Je.token_timestamps=nt.token_timestamps.tolist()[0].map(wt=>(0,b.round)(wt,2))):Je.tokens=nt[0].tolist(),Je.stride=Je.stride.map(wt=>wt/gt)}const[Ae,Ge]=this.tokenizer._decode_asr(he,{time_precision:xt,return_timestamps:tt,force_full_sequences:Xe});se.push({text:Ae,...Ge})}return lt?se[0]:se}}class ve extends ne{constructor(ue){super(ue)}async _call(ue,ke={}){const tt=Array.isArray(ue),He=await P(ue),{pixel_values:Xe}=await this.processor(He),Be=[];for(const st of Xe){st.dims=[1,...st.dims];const lt=await this.model.generate({inputs:st,...ke}),xt=this.tokenizer.batch_decode(lt,{skip_special_tokens:!0}).map(ut=>({generated_text:ut.trim()}));Be.push(xt)}return tt?Be:Be[0]}}class Le extends ne{constructor(ue){super(ue)}async _call(ue,{top_k:ke=5}={}){const tt=await P(ue),{pixel_values:He}=await this.processor(tt),Xe=await this.model({pixel_values:He}),Be=this.model.config.id2label,st=[];for(const lt of Xe.logits){const xt=await(0,M.topk)(new M.Tensor("float32",(0,b.softmax)(lt.data),lt.dims),ke),ut=xt[0].tolist(),I=xt[1].tolist().map((se,X)=>({label:Be?Be[se]:`LABEL_${se}`,score:ut[X]}));st.push(I)}return Array.isArray(ue)?st:st[0]}}class fe extends ne{constructor(ue){super(ue),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ue,{threshold:ke=.5,mask_threshold:tt=.5,overlap_mask_area_threshold:He=.8,label_ids_to_fuse:Xe=null,target_sizes:Be=null,subtask:st=null}={}){if(Array.isArray(ue)&&ue.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const xt=await P(ue),ut=xt.map(Ge=>[Ge.height,Ge.width]),{pixel_values:gt,pixel_mask:I}=await this.processor(xt),se=await this.model({pixel_values:gt,pixel_mask:I});let X=null;if(st!==null)X=this.subtasks_mapping[st];else for(let[Ge,Je]of Object.entries(this.subtasks_mapping))if(Je in this.processor.image_processor){X=this.processor.image_processor[Je].bind(this.processor.image_processor),st=Ge;break}const he=this.model.config.id2label,Ae=[];if(st==="panoptic"||st==="instance"){const Ge=X(se,ke,tt,He,Xe,Be??ut)[0],Je=Ge.segmentation;for(const nt of Ge.segments_info){const wt=new Uint8ClampedArray(Je.data.length);for(let Qt=0;Qttt.replace("{}",I)),st=this.tokenizer(Be,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:lt}=await this.processor(Xe),xt=await this.model({...st,pixel_values:lt}),ut=this.model.config.model_type==="siglip"?I=>I.sigmoid().data:I=>(0,b.softmax)(I.data),gt=[];for(const I of xt.logits_per_image){const X=[...ut(I)].map((he,Ae)=>({score:he,label:ke[Ae]}));X.sort((he,Ae)=>Ae.score-he.score),gt.push(X)}return He?gt:gt[0]}}class ce extends ne{constructor(ue){super(ue)}async _call(ue,{threshold:ke=.9,percentage:tt=!1}={}){const He=Array.isArray(ue);if(He&&ue.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Xe=await P(ue),Be=tt?null:Xe.map(se=>[se.height,se.width]),{pixel_values:st,pixel_mask:lt}=await this.processor(Xe),xt=await this.model({pixel_values:st,pixel_mask:lt}),ut=this.processor.image_processor.post_process_object_detection(xt,ke,Be),gt=this.model.config.id2label,I=ut.map(se=>se.boxes.map((X,he)=>({score:se.scores[he],label:gt[se.classes[he]],box:Q(X,!tt)})));return He?I:I[0]}}class _e extends ne{constructor(ue){super(ue)}async _call(ue,ke,{threshold:tt=.1,top_k:He=null,percentage:Xe=!1}={}){const Be=Array.isArray(ue),st=await P(ue),lt=this.tokenizer(ke,{padding:!0,truncation:!0}),xt=await this.processor(st),ut=[];for(let gt=0;gt({score:Ae.scores[nt],label:ke[Ae.classes[nt]],box:Q(Je,!Xe)})).sort((Je,nt)=>nt.score-Je.score);He!==null&&(Ge=Ge.slice(0,He)),ut.push(Ge)}return Be?ut:ut[0]}}class Se extends ne{constructor(ue){super(ue)}async _call(ue,ke,tt={}){const He=(await P(ue))[0],{pixel_values:Xe}=await this.processor(He),Be=`${ke}`,st=this.tokenizer(Be,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,lt=await this.model.generate({inputs:Xe,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...tt}),ut=this.tokenizer.batch_decode(lt)[0].match(/(.*?)<\/s_answer>/);let gt=null;return ut&&ut.length>=2&&(gt=ut[1].trim()),[{answer:gt}]}}class Re extends ne{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(ue){super(ue),this.vocoder=ue.vocoder??null}async _call(ue,{speaker_embeddings:ke=null}={}){return this.processor?this._call_text_to_spectrogram(ue,{speaker_embeddings:ke}):this._call_text_to_waveform(ue)}async _call_text_to_waveform(ue){const ke=this.tokenizer(ue,{padding:!0,truncation:!0}),{waveform:tt}=await this.model(ke),He=this.model.config.sampling_rate;return{audio:tt.data,sampling_rate:He}}async _call_text_to_spectrogram(ue,{speaker_embeddings:ke}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await A.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof ke=="string"||ke instanceof URL)&&(ke=new Float32Array(await(await fetch(ke)).arrayBuffer())),ke instanceof Float32Array)ke=new M.Tensor("float32",ke,[1,ke.length]);else if(!(ke instanceof M.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:tt}=this.tokenizer(ue,{padding:!0,truncation:!0}),{waveform:He}=await this.model.generate_speech(tt,ke,{vocoder:this.vocoder}),Xe=this.processor.feature_extractor.config.sampling_rate;return{audio:He.data,sampling_rate:Xe}}}class We extends ne{constructor(ue){super(ue)}async _call(ue){const ke=await P(ue),tt=await this.processor(ke),He=await this.model(tt),Xe=[];for(const Be of He.reconstruction){const st=Be.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Xe.push(x.RawImage.fromTensor(st))}return Xe.length>1?Xe:Xe[0]}}class Qe extends ne{constructor(ue){super(ue)}async _call(ue){const ke=await P(ue),tt=await this.processor(ke),{predicted_depth:He}=await this.model(tt),Xe=[];for(let Be=0;Be1?Xe:Xe[0]}}const at=Object.freeze({"text-classification":{tokenizer:_.AutoTokenizer,pipeline:de,model:A.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:_.AutoTokenizer,pipeline:N,model:A.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:_.AutoTokenizer,pipeline:K,model:A.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:_.AutoTokenizer,pipeline:q,model:A.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:_.AutoTokenizer,pipeline:O,model:A.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:_.AutoTokenizer,pipeline:w,model:A.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:_.AutoTokenizer,pipeline:B,model:A.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:_.AutoTokenizer,pipeline:E,model:A.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:_.AutoTokenizer,pipeline:Z,model:A.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:me,model:A.AutoModelForAudioClassification,processor:j.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:_.AutoTokenizer,pipeline:ge,model:A.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:_.AutoTokenizer,pipeline:Ee,model:[A.AutoModelForSpeechSeq2Seq,A.AutoModelForCTC],processor:j.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:_.AutoTokenizer,pipeline:Re,model:[A.AutoModelForTextToWaveform,A.AutoModelForTextToSpectrogram],processor:[j.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:_.AutoTokenizer,pipeline:ve,model:A.AutoModelForVision2Seq,processor:j.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Le,model:A.AutoModelForImageClassification,processor:j.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:fe,model:[A.AutoModelForImageSegmentation,A.AutoModelForSemanticSegmentation,A.AutoModelForUniversalSegmentation],processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:_.AutoTokenizer,pipeline:W,model:A.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ce,model:A.AutoModelForObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:_.AutoTokenizer,pipeline:_e,model:A.AutoModelForZeroShotObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:_.AutoTokenizer,pipeline:Se,model:A.AutoModelForDocumentQuestionAnswering,processor:j.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:We,model:A.AutoModelForImageToImage,processor:j.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Qe,model:A.AutoModelForDepthEstimation,processor:j.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:_.AutoTokenizer,pipeline:J,model:A.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:j.AutoProcessor,pipeline:ae,model:[A.AutoModelForImageFeatureExtraction,A.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ue=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function oe(Ne,ue=null,{progress_callback:ke=null,config:tt=null,cache_dir:He=null,local_files_only:Xe=!1,revision:Be="main",device:st=null,dtype:lt=null,model_file_name:xt=null,session_options:ut={}}={}){Ne=Ue[Ne]??Ne;const gt=at[Ne.split("_",1)[0]];if(!gt)throw Error(`Unsupported pipeline: ${Ne}. Must be one of [${Object.keys(at)}]`);ue||(ue=gt.default.model,console.log(`No model specified. Using default model: "${ue}".`));const I={progress_callback:ke,config:tt,cache_dir:He,local_files_only:Xe,revision:Be,device:st,dtype:lt,model_file_name:xt,session_options:ut},se=new Map([["tokenizer",gt.tokenizer],["model",gt.model],["processor",gt.processor]]),X=await Ve(se,ue,I);X.task=Ne,(0,U.dispatchCallback)(ke,{status:"ready",task:Ne,model:ue});const he=gt.pipeline;return new he(X)}async function Ve(Ne,ue,ke){const tt=Object.create(null),He=[];for(const[Xe,Be]of Ne.entries()){if(!Be)continue;let st;Array.isArray(Be)?st=new Promise(async(lt,xt)=>{let ut;for(const gt of Be){if(gt===null){lt(null);return}try{lt(await gt.from_pretrained(ue,ke));return}catch(I){if(I.message?.includes("Unsupported model type"))ut=I;else if(I.message?.includes("Could not locate file"))ut=I;else{xt(I);return}}}xt(ut)}):st=Be.from_pretrained(ue,ke),tt[Xe]=st,He.push(st)}await Promise.all(He);for(const[Xe,Be]of Object.entries(tt))tt[Xe]=await Be;return tt}},"./src/tokenizers.js":(Me,v,s)=>{s.r(v),s.d(v,{AlbertTokenizer:()=>ys,AutoTokenizer:()=>Sn,BartTokenizer:()=>sr,BertTokenizer:()=>Rs,BlenderbotSmallTokenizer:()=>kn,BlenderbotTokenizer:()=>pn,BloomTokenizer:()=>Mn,CLIPTokenizer:()=>En,CamembertTokenizer:()=>ot,CodeGenTokenizer:()=>Tn,CodeLlamaTokenizer:()=>As,CohereTokenizer:()=>$n,ConvBertTokenizer:()=>Ms,DebertaTokenizer:()=>$s,DebertaV2Tokenizer:()=>Jr,DistilBertTokenizer:()=>os,ElectraTokenizer:()=>kt,EsmTokenizer:()=>Zr,FalconTokenizer:()=>Is,GPT2Tokenizer:()=>js,GPTNeoXTokenizer:()=>hs,GemmaTokenizer:()=>Vs,Grok1Tokenizer:()=>dn,HerbertTokenizer:()=>ls,LlamaTokenizer:()=>vn,M2M100Tokenizer:()=>Ft,MBart50Tokenizer:()=>Ss,MBartTokenizer:()=>Us,MPNetTokenizer:()=>Jn,MarianTokenizer:()=>Os,MgpstrTokenizer:()=>Ks,MobileBertTokenizer:()=>ks,NllbTokenizer:()=>un,NougatTokenizer:()=>es,PreTrainedTokenizer:()=>Ot,Qwen2Tokenizer:()=>ln,RoFormerTokenizer:()=>Ns,RobertaTokenizer:()=>Yn,SiglipTokenizer:()=>Pn,SpeechT5Tokenizer:()=>nr,SqueezeBertTokenizer:()=>bs,T5Tokenizer:()=>cr,TokenizerModel:()=>ae,VitsTokenizer:()=>hn,Wav2Vec2CTCTokenizer:()=>Cn,WhisperTokenizer:()=>cn,XLMRobertaTokenizer:()=>xn,XLMTokenizer:()=>dt,is_chinese_char:()=>q});var _=s("./src/utils/generic.js"),A=s("./src/utils/core.js"),j=s("./src/utils/hub.js"),ee=s("./src/utils/maths.js"),U=s("./src/utils/tensor.js"),b=s("./src/utils/data-structures.js"),T=s("./node_modules/@huggingface/jinja/dist/index.js"),M=s("./src/models/whisper/common_whisper.js");s("./src/utils/constants.js");async function x(xe,y){const Y=await Promise.all([(0,j.getModelJSON)(xe,"tokenizer.json",!0,y),(0,j.getModelJSON)(xe,"tokenizer_config.json",!0,y)]);return y.legacy!==null&&(Y[1].legacy=y.legacy),Y}function P(xe,y){const Y=[];let le=0;for(const we of xe.matchAll(y)){const Ie=we[0];le0&&Y.push(Ie),le=we.index+Ie.length}return le=19968&&xe<=40959||xe>=13312&&xe<=19903||xe>=131072&&xe<=173791||xe>=173824&&xe<=177983||xe>=177984&&xe<=178207||xe>=178208&&xe<=183983||xe>=63744&&xe<=64255||xe>=194560&&xe<=195103}function B(xe,y,Y){const le=[];let we=0;for(;wethis.tokens_to_ids.get(Y)??this.unk_token_id)}convert_ids_to_tokens(y){return y.map(Y=>this.vocab[Y]??this.unk_token)}}class me extends ae{constructor(y){super(y),this.tokens_to_ids=Q(y.vocab),this.unk_token_id=this.tokens_to_ids.get(y.unk_token),this.unk_token=y.unk_token,this.max_input_chars_per_word=y.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,le]of this.tokens_to_ids)this.vocab[le]=Y}encode(y){const Y=[];for(const le of y){const we=[...le];if(we.length>this.max_input_chars_per_word){Y.push(this.unk_token);continue}let Ie=!1,Ke=0;const ht=[];for(;Ke0&&(qe=this.config.continuing_subword_prefix+qe),this.tokens_to_ids.has(qe)){Mt=qe;break}--mt}if(Mt===null){Ie=!0;break}ht.push(Mt),Ke=mt}Ie?Y.push(this.unk_token):Y.push(...ht)}return Y}}class ge extends ae{constructor(y,Y){super(y);const le=y.vocab.length;this.vocab=new Array(le),this.scores=new Array(le);for(let we=0;we[we,Ie])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Y.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,ee.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new b.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(y){const Y=y.chars,le=1;let we=0;for(;we{const xe=[...Array.from({length:94},(we,Ie)=>Ie+33),...Array.from({length:12},(we,Ie)=>Ie+161),...Array.from({length:82},(we,Ie)=>Ie+174)],y=xe.slice();let Y=0;for(let we=0;we<256;++we)xe.includes(we)||(xe.push(we),y.push(256+Y),Y+=1);const le=y.map(we=>String.fromCharCode(we));return Object.fromEntries(xe.map((we,Ie)=>[we,le[Ie]]))})(),ve=(0,A.reverseDictionary)(Ee);class Le extends ae{constructor(y){super(y),this.tokens_to_ids=Q(y.vocab),this.unk_token_id=this.tokens_to_ids.get(y.unk_token),this.unk_token=y.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[le,we]of this.tokens_to_ids)this.vocab[we]=le;const Y=Array.isArray(y.merges[0]);this.merges=Y?y.merges:y.merges.map(le=>le.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((le,we)=>[JSON.stringify(le),we])),this.end_of_word_suffix=y.end_of_word_suffix,this.continuing_subword_suffix=y.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(y){if(y.length===0)return[];const Y=this.cache.get(y);if(Y!==void 0)return Y;const le=Array.from(y);this.end_of_word_suffix&&(le[le.length-1]+=this.end_of_word_suffix);let we=[];if(le.length>1){const Ie=new b.PriorityQueue((mt,Mt)=>mt.score`<0x${ht.toString(16).toUpperCase().padStart(2,"0")}>`);Ke.every(ht=>this.tokens_to_ids.has(ht))?Y.push(...Ke):Y.push(this.unk_token)}else Y.push(this.unk_token)}return Y}}class fe extends ae{constructor(y,Y){super(y),this.tokens_to_ids=Q(Y.target_lang?y.vocab[Y.target_lang]:y.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[le,we]of this.tokens_to_ids)this.vocab[we]=le}encode(y){return y}}class W extends _.Callable{constructor(y){super(),this.config=y}static fromConfig(y){if(y===null)return null;switch(y.type){case"BertNormalizer":return new Ve(y);case"Precompiled":return new mr(y);case"Sequence":return new oe(y);case"Replace":return new ce(y);case"NFC":return new _e(y);case"NFKC":return new Se(y);case"NFKD":return new Re(y);case"Strip":return new We(y);case"StripAccents":return new Qe(y);case"Lowercase":return new at(y);case"Prepend":return new Ue(y);default:throw new Error(`Unknown Normalizer type: ${y.type}`)}}normalize(y){throw Error("normalize should be implemented in subclass.")}_call(y){return this.normalize(y)}}class ce extends W{normalize(y){const Y=R(this.config.pattern);return Y===null?y:y.replaceAll(Y,this.config.content)}}class _e extends W{normalize(y){return y=y.normalize("NFC"),y}}class Se extends W{normalize(y){return y=y.normalize("NFKC"),y}}class Re extends W{normalize(y){return y=y.normalize("NFKD"),y}}class We extends W{normalize(y){return this.config.strip_left&&this.config.strip_right?y=y.trim():(this.config.strip_left&&(y=y.trimStart()),this.config.strip_right&&(y=y.trimEnd())),y}}class Qe extends W{normalize(y){return y=N(y),y}}class at extends W{normalize(y){return y=y.toLowerCase(),y}}class Ue extends W{normalize(y){return y=this.config.prepend+y,y}}class oe extends W{constructor(y){super(y),this.normalizers=y.normalizers.map(Y=>W.fromConfig(Y))}normalize(y){return this.normalizers.reduce((Y,le)=>le.normalize(Y),y)}}class Ve extends W{_tokenize_chinese_chars(y){const Y=[];for(let le=0;lethis.pre_tokenize_text(le,Y)):this.pre_tokenize_text(y,Y)).flat()}_call(y,Y){return this.pre_tokenize(y,Y)}}class ue extends Ne{constructor(y){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(y,Y){return y.trim().match(this.pattern)||[]}}class ke extends Ne{constructor(y){super(),this.config=y,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=Ee,this.text_encoder=new TextEncoder}pre_tokenize_text(y,Y){return this.add_prefix_space&&!y.startsWith(" ")&&(y=" "+y),(this.use_regex?y.match(this.pattern)||[]:[y]).map(we=>Array.from(this.text_encoder.encode(we),Ie=>this.byte_encoder[Ie]).join(""))}}class tt extends Ne{constructor(y){super(),this.config=y,this.pattern=R(this.config.pattern,this.config.invert)}pre_tokenize_text(y,Y){return this.pattern===null?[]:this.config.invert?y.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?y.split(this.pattern).filter(le=>le):P(y,this.pattern)}}class He extends Ne{constructor(y){super(),this.config=y,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(y,Y){return y.match(this.pattern)||[]}}class Xe extends Ne{constructor(y){super(),this.config=y;const Y=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Y,"gu")}pre_tokenize_text(y,Y){return y.match(this.pattern)||[]}}class Be extends _.Callable{constructor(y){super(),this.config=y}static fromConfig(y){if(y===null)return null;switch(y.type){case"TemplateProcessing":return new xt(y);case"ByteLevel":return new ut(y);case"RobertaProcessing":return new lt(y);case"BertProcessing":return new st(y);case"Sequence":return new gt(y);default:throw new Error(`Unknown PostProcessor type: ${y.type}`)}}post_process(y,...Y){throw Error("post_process should be implemented in subclass.")}_call(y,...Y){return this.post_process(y,...Y)}}class st extends Be{constructor(y){super(y),this.cls=y.cls[0],this.sep=y.sep[0]}post_process(y,Y=null,{add_special_tokens:le=!0}={}){le&&(y=(0,A.mergeArrays)([this.cls],y,[this.sep]));let we=new Array(y.length).fill(0);if(Y!==null){const Ie=le&&this instanceof lt?[this.sep]:[],Ke=le?[this.sep]:[];y=(0,A.mergeArrays)(y,Ie,Y,Ke),we=(0,A.mergeArrays)(we,new Array(Y.length+Ie.length+Ke.length).fill(1))}return{tokens:y,token_type_ids:we}}}class lt extends st{}class xt extends Be{constructor(y){super(y),this.single=y.single,this.pair=y.pair}post_process(y,Y=null,{add_special_tokens:le=!0}={}){const we=Y===null?this.single:this.pair;let Ie=[],Ke=[];for(const ht of we)"SpecialToken"in ht?le&&(Ie.push(ht.SpecialToken.id),Ke.push(ht.SpecialToken.type_id)):"Sequence"in ht&&(ht.Sequence.id==="A"?(Ie=(0,A.mergeArrays)(Ie,y),Ke=(0,A.mergeArrays)(Ke,new Array(y.length).fill(ht.Sequence.type_id))):ht.Sequence.id==="B"&&(Ie=(0,A.mergeArrays)(Ie,Y),Ke=(0,A.mergeArrays)(Ke,new Array(Y.length).fill(ht.Sequence.type_id))));return{tokens:Ie,token_type_ids:Ke}}}class ut extends Be{post_process(y,Y=null){return Y&&(y=(0,A.mergeArrays)(y,Y)),{tokens:y}}}class gt extends Be{constructor(y){super(y),this.processors=y.processors.map(Y=>Be.fromConfig(Y))}post_process(y,Y=null,le={}){let we;for(const Ie of this.processors)if(Ie instanceof ut)y=Ie.post_process(y).tokens,Y&&(Y=Ie.post_process(Y).tokens);else{const Ke=Ie.post_process(y,Y,le);y=Ke.tokens,we=Ke.token_type_ids}return{tokens:y,token_type_ids:we}}}class I extends _.Callable{constructor(y){super(),this.config=y,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=y.trim_offsets}static fromConfig(y){if(y===null)return null;switch(y.type){case"WordPiece":return new Ge(y);case"Metaspace":return new Tr(y);case"ByteLevel":return new Je(y);case"Replace":return new se(y);case"ByteFallback":return new X(y);case"Fuse":return new he(y);case"Strip":return new Ae(y);case"Sequence":return new wt(y);case"CTC":return new nt(y);case"BPEDecoder":return new pt(y);default:throw new Error(`Unknown Decoder type: ${y.type}`)}}_call(y){return this.decode(y)}decode(y){return this.decode_chain(y).join("")}decode_chain(y){throw Error("`decode_chain` should be implemented in subclass.")}}class se extends I{decode_chain(y){const Y=R(this.config.pattern);return Y===null?y:y.map(le=>le.replaceAll(Y,this.config.content))}}class X extends I{constructor(y){super(y),this.text_decoder=new TextDecoder}decode_chain(y){const Y=[];let le=[];for(const we of y){let Ie=null;if(we.length===6&&we.startsWith("<0x")&&we.endsWith(">")){const Ke=parseInt(we.slice(3,5),16);isNaN(Ke)||(Ie=Ke)}if(Ie!==null)le.push(Ie);else{if(le.length>0){const Ke=this.text_decoder.decode(Uint8Array.from(le));Y.push(Ke),le=[]}Y.push(we)}}if(le.length>0){const we=this.text_decoder.decode(Uint8Array.from(le));Y.push(we),le=[]}return Y}}class he extends I{decode_chain(y){return[y.join("")]}}class Ae extends I{constructor(y){super(y),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(y){return y.map(Y=>{let le=0;for(let Ie=0;Ie(le!==0&&(Y.startsWith(this.config.prefix)?Y=Y.replace(this.config.prefix,""):Y=" "+Y),this.cleanup&&(Y=de(Y)),Y))}}class Je extends I{constructor(y){super(y),this.byte_decoder=ve,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(y){const Y=y.join(""),le=new Uint8Array([...Y].map(Ie=>this.byte_decoder[Ie]));return this.text_decoder.decode(le)}decode_chain(y){const Y=[];let le=[];for(const we of y)this.added_tokens.find(Ie=>Ie.content===we)!==void 0?(le.length>0&&(Y.push(this.convert_tokens_to_string(le)),le=[]),Y.push(we)):le.push(we);return le.length>0&&Y.push(this.convert_tokens_to_string(le)),Y}}class nt extends I{constructor(y){super(y),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(y){if(y.length===0)return"";const Y=[y[0]];for(let Ie=1;IeIe!==this.pad_token).join("");return this.cleanup&&(we=de(we).replaceAll(this.word_delimiter_token," ").trim()),we}decode_chain(y){return[this.convert_tokens_to_string(y)]}}class wt extends I{constructor(y){super(y),this.decoders=y.decoders.map(Y=>I.fromConfig(Y))}decode_chain(y){return this.decoders.reduce((Y,le)=>le.decode_chain(Y),y)}}class pt extends I{constructor(y){super(y),this.suffix=this.config.suffix}decode_chain(y){return y.map((Y,le)=>Y.replaceAll(this.suffix,le===y.length-1?"":" "))}}class Qt extends I{decode_chain(y){let Y="";for(let le=1;lele.normalize("NFKC")).join("~"):y=y.normalize("NFKC"),y}}class Sr extends Ne{constructor(y){super(),this.tokenizers=y.pretokenizers.map(Y=>Ne.fromConfig(Y))}pre_tokenize_text(y,Y){return this.tokenizers.reduce((le,we)=>we.pre_tokenize(le,Y),[y])}}class br extends Ne{constructor(y){super()}pre_tokenize_text(y,Y){return y.match(/\w+|[^\w\s]+/g)||[]}}class Hr extends Ne{constructor(y){super()}pre_tokenize_text(y,Y){return O(y)}}class ns extends Ne{constructor(y){super(),this.config=y,this.pattern=R(this.config.pattern),this.content=this.config.content}pre_tokenize_text(y,Y){return this.pattern===null?[y]:[y.replaceAll(this.pattern,this.config.content)]}}const Bs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Cs(xe,y,Y,le){for(const we of Object.keys(xe)){const Ie=y-xe[we].length,Ke=Y(we),ht=new Array(Ie).fill(Ke);xe[we]=le==="right"?(0,A.mergeArrays)(xe[we],ht):(0,A.mergeArrays)(ht,xe[we])}}function an(xe,y){for(const Y of Object.keys(xe))xe[Y].length=y}class Ot extends _.Callable{return_token_type_ids=!1;padding_side="right";constructor(y,Y){super(),this._tokenizer_config=Y,this.normalizer=W.fromConfig(y.normalizer),this.pre_tokenizer=Ne.fromConfig(y.pre_tokenizer),this.model=ae.fromConfig(y.model,Y),this.post_processor=Be.fromConfig(y.post_processor),this.decoder=I.fromConfig(y.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const le of y.added_tokens){const we=new J(le);this.added_tokens.push(we),this.model.tokens_to_ids.set(we.content,we.id),this.model.vocab[we.id]=we.content,we.special&&(this.special_tokens.push(we.content),this.all_special_ids.push(we.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((le,we)=>we.content.length-le.content.length).map(le=>`${le.lstrip?"\\s*":""}(${(0,A.escapeRegExp)(le.content)})${le.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 le=Object.create(null);for(const{name:we,template:Ie}of this.chat_template){if(typeof we!="string"||typeof Ie!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');le[we]=Ie}this.chat_template=le}this._compiled_template_cache=new Map}getToken(...y){for(const Y of y){const le=this._tokenizer_config[Y];if(le)if(typeof le=="object"){if(le.__type==="AddedToken")return le.content;throw Error(`Unknown token: ${le}`)}else return le}return null}static async from_pretrained(y,{progress_callback:Y=null,config:le=null,cache_dir:we=null,local_files_only:Ie=!1,revision:Ke="main",legacy:ht=null}={}){const mt=await x(y,{progress_callback:Y,config:le,cache_dir:we,local_files_only:Ie,revision:Ke,legacy:ht});return new this(...mt)}_call(y,{text_pair:Y=null,add_special_tokens:le=!0,padding:we=!1,truncation:Ie=null,max_length:Ke=null,return_tensor:ht=!0,return_token_type_ids:mt=null}={}){const Mt=Array.isArray(y);let qe;if(Mt){if(y.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(y.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");qe=y.map((Xt,gr)=>this._encode_plus(Xt,{text_pair:Y[gr],add_special_tokens:le,return_token_type_ids:mt}))}else qe=y.map(Xt=>this._encode_plus(Xt,{add_special_tokens:le,return_token_type_ids:mt}))}else{if(y==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).");qe=[this._encode_plus(y,{text_pair:Y,add_special_tokens:le,return_token_type_ids:mt})]}if(Ke===null?we==="max_length"?Ke=this.model_max_length:Ke=(0,ee.max)(qe.map(Xt=>Xt.input_ids.length))[0]:Ie||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),Ke=Math.min(Ke,this.model_max_length??1/0),we||Ie)for(let Xt=0;XtKe?Ie&&an(qe[Xt],Ke):we&&Cs(qe[Xt],Ke,gr=>gr==="input_ids"?this.pad_token_id:0,this.padding_side));const It={};if(ht){if(!(we&&Ie)&&qe.some(gr=>{for(const Ce of Object.keys(gr))if(gr[Ce].length!==qe[0][Ce]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Xt=[qe.length,qe[0].input_ids.length];for(const gr of Object.keys(qe[0]))It[gr]=new U.Tensor("int64",BigInt64Array.from(qe.flatMap(Ce=>Ce[gr]).map(BigInt)),Xt)}else{for(const Xt of Object.keys(qe[0]))It[Xt]=qe.map(gr=>gr[Xt]);if(!Mt)for(const Xt of Object.keys(It))It[Xt]=It[Xt][0]}return It}_encode_text(y){return y===null?null:(this.added_tokens_regex?y.split(this.added_tokens_regex).filter(we=>we):[y]).map((we,Ie)=>{if(this.added_tokens.find(ht=>ht.content===we)!==void 0)return we;{if(this.remove_space===!0&&(we=we.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(we=K(we)),this.normalizer!==null&&(we=this.normalizer(we)),we.length===0)return[];const ht=this.pre_tokenizer!==null?this.pre_tokenizer(we,{section_index:Ie}):[we];return this.model(ht)}}).flat()}_encode_plus(y,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:we=null}={}){const{tokens:Ie,token_type_ids:Ke}=this._tokenize_helper(y,{pair:Y,add_special_tokens:le}),ht=this.model.convert_tokens_to_ids(Ie),mt={input_ids:ht,attention_mask:new Array(ht.length).fill(1)};return(we??this.return_token_type_ids)&&Ke&&(mt.token_type_ids=Ke),mt}_tokenize_helper(y,{pair:Y=null,add_special_tokens:le=!1}={}){const we=this._encode_text(y),Ie=this._encode_text(Y);return this.post_processor?this.post_processor(we,Ie,{add_special_tokens:le}):{tokens:(0,A.mergeArrays)(we??[],Ie??[])}}tokenize(y,{pair:Y=null,add_special_tokens:le=!1}={}){return this._tokenize_helper(y,{pair:Y,add_special_tokens:le}).tokens}encode(y,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:we=null}={}){return this._encode_plus(y,{text_pair:Y,add_special_tokens:le,return_token_type_ids:we}).input_ids}batch_decode(y,Y={}){return y instanceof U.Tensor&&(y=y.tolist()),y.map(le=>this.decode(le,Y))}decode(y,Y={}){if(y instanceof U.Tensor&&(y=ne(y)),!Array.isArray(y)||y.length===0||!(0,A.isIntegralNumber)(y[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(y,Y)}decode_single(y,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:le=null}){let we=this.model.convert_ids_to_tokens(y);Y&&(we=we.filter(Ke=>!this.special_tokens.includes(Ke)));let Ie=this.decoder?this.decoder(we):we.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ie=Ie.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Ie=Ie.trim())),(le??this.clean_up_tokenization_spaces)&&(Ie=de(Ie)),Ie}get_chat_template({chat_template:y=null,tools:Y=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const le=this.chat_template;if(y!==null&&Object.hasOwn(le,y))y=le[y];else if(y===null)if(Y!==null&&"tool_use"in le)y=le.tool_use;else if("default"in le)y=le.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(le).sort()}.`)}else if(y===null)if(this.chat_template)y=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return y}apply_chat_template(y,{tools:Y=null,documents:le=null,chat_template:we=null,add_generation_prompt:Ie=!1,tokenize:Ke=!0,padding:ht=!1,truncation:mt=!1,max_length:Mt=null,return_tensor:qe=!0,return_dict:It=!1,tokenizer_kwargs:Xt={},...gr}={}){if(we=this.get_chat_template({chat_template:we,tools:Y}),typeof we!="string")throw Error(`chat_template must be a string, but got ${typeof we}`);let Ce=this._compiled_template_cache.get(we);Ce===void 0&&(Ce=new T.Template(we),this._compiled_template_cache.set(we,Ce));const Er=Object.create(null);for(const Rr of Bs){const ds=this.getToken(Rr);ds&&(Er[Rr]=ds)}const jr=Ce.render({messages:y,add_generation_prompt:Ie,tools:Y,documents:le,...Er,...gr});if(Ke){const Rr=this._call(jr,{add_special_tokens:!1,padding:ht,truncation:mt,max_length:Mt,return_tensor:qe,...Xt});return It?Rr:Rr.input_ids}return jr}}class Rs extends Ot{return_token_type_ids=!0}class ys extends Ot{return_token_type_ids=!0}class ks extends Ot{return_token_type_ids=!0}class bs extends Ot{return_token_type_ids=!0}class $s extends Ot{return_token_type_ids=!0}class Jr extends Ot{return_token_type_ids=!0}class ls extends Ot{return_token_type_ids=!0}class Ms extends Ot{return_token_type_ids=!0}class Ns extends Ot{return_token_type_ids=!0}class os extends Ot{}class ot extends Ot{}class dt extends Ot{return_token_type_ids=!0;constructor(y,Y){super(y,Y),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class kt extends Ot{return_token_type_ids=!0}class cr extends Ot{}class js extends Ot{}class sr extends Ot{}class Us extends Ot{constructor(y,Y){super(y,Y),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(le=>this.languageRegex.test(le)),this.lang_to_token=le=>le}_build_translation_inputs(y,Y,le){return Gs(this,y,Y,le)}}class Ss extends Us{}class Yn extends Ot{}class Mn extends Ot{}const Ws="▁";class vn extends Ot{padding_side="left";constructor(y,Y){super(y,Y),this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new tr({replacement:Ws,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(y){if(y===null)return null;if(this.legacy||y.length===0)return super._encode_text(y);let Y=super._encode_text(Ws+y.replaceAll(Ws," "));return Y.length>1&&Y[0]===Ws&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class As extends Ot{}class xn extends Ot{}class Jn extends Ot{}class Is extends Ot{}class hs extends Ot{}class Zr extends Ot{}class ln extends Ot{}class Vs extends Ot{}class dn extends Ot{}function Gs(xe,y,Y,le){if(!("language_codes"in xe)||!Array.isArray(xe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in xe)||!(xe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in xe)||typeof xe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const we=le.src_lang,Ie=le.tgt_lang;if(!xe.language_codes.includes(Ie))throw new Error(`Target language code "${Ie}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);if(we!==void 0){if(!xe.language_codes.includes(we))throw new Error(`Source language code "${we}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);for(const Ke of xe.post_processor.config.single)if("SpecialToken"in Ke&&xe.languageRegex.test(Ke.SpecialToken.id)){Ke.SpecialToken.id=xe.lang_to_token(we);break}}return le.forced_bos_token_id=xe.model.convert_tokens_to_ids([xe.lang_to_token(Ie)])[0],xe._call(y,Y)}class un extends Ot{constructor(y,Y){super(y,Y),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(le=>this.languageRegex.test(le)),this.lang_to_token=le=>le}_build_translation_inputs(y,Y,le){return Gs(this,y,Y,le)}}class Ft extends Ot{constructor(y,Y){super(y,Y),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(le=>this.languageRegex.test(le)).map(le=>le.slice(2,-2)),this.lang_to_token=le=>`__${le}__`}_build_translation_inputs(y,Y,le){return Gs(this,y,Y,le)}}class cn extends Ot{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(y,{return_timestamps:Y=!1,return_language:le=!1,time_precision:we=null,force_full_sequences:Ie=!0}={}){if(we===null)throw Error("Must specify time_precision");let Ke=null;const ht=Y==="word";function mt(){return{language:Ke,timestamp:[null,null],text:""}}const Mt=[];let qe=mt(),It=0;const Xt=this.timestamp_begin,Ce=Xt+1500;let Er=[],jr=[],Rr=!1,ds=null;const zt=new Set(this.all_special_ids);for(const Zt of y){const dr=Zt.tokens,Tt=ht?Zt.token_timestamps:null;let or=null,fs=Xt;if("stride"in Zt){const[yt,Pr,Oe]=Zt.stride;if(It-=Pr,ds=yt-Oe,Pr&&(fs=Pr/we+Xt),Oe)for(let ft=dr.length-1;ft>=0;--ft){const ts=Number(dr[ft]);if(ts>=Xt){if(or!==null&&(ts-Xt)*we=Xt&&Pr<=Ce){const Oe=(Pr-Xt)*we+It,ft=(0,ee.round)(Oe,2);if(or!==null&&Pr>=or)Rr=!0;else if(Rr||Er.length>0&&Pr0?(Er.push(Ar),ht&&jr.push(Gr)):Er.every(yt=>yt.length===0)&&(qe=mt(),Er=[],Ar=[],jr=[],Gr=[])}if(Er.length>0){if(Ie&&Y)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Zt,dr]=this.findLongestCommonSequence(Er,jr),Tt=this.decode(Zt);qe.text=Tt,ht&&(qe.words=this.collateWordTimestamps(Zt,dr,Ke)),Mt.push(qe)}let Lr=Object.create(null);const ms=Mt.map(Zt=>Zt.text).join("");if(Y||le){for(let Zt=0;Zt0;let ht=Ke?[]:null,mt=Ke?Y[0]:null;for(let Mt=1;MtPr===fs[Oe]&&mt[ms+Oe]<=Y[Mt][Tt+Oe]).length:Ar=dr.filter((Pr,Oe)=>Pr===fs[Oe]).length;const Gr=Lr/1e4,yt=Ar/Lr+Gr;Ar>1&&yt>It&&(It=yt,Xt=[ms,Zt,Tt,or])}const[Ce,Er,jr,Rr]=Xt,ds=Math.floor((Er+Ce)/2),zt=Math.floor((Rr+jr)/2);Ie.push(...le.slice(0,ds)),le=qe.slice(zt),we=le.length,Ke&&(ht.push(...mt.slice(0,ds)),mt=Y[Mt].slice(zt))}return Ie.push(...le),Ke?(ht.push(...mt),[Ie,ht]):[Ie,[]]}collateWordTimestamps(y,Y,le){const[we,Ie,Ke]=this.combineTokensIntoWords(y,le),ht=[];for(let mt=0;mt=we){const ht=((Ke-we)*le).toFixed(2);Ie.push(`<|${ht}|>`),Ie.push([])}else Ie[Ie.length-1].push(Ke);return Ie=Ie.map(Ke=>typeof Ke=="string"?Ke:super.decode(Ke,Y)),Ie.join("")}splitTokensOnUnicode(y){const Y=this.decode(y,{decode_with_timestamps:!0}),le="�",we=[],Ie=[],Ke=[];let ht=[],mt=[],Mt=0;for(let qe=0;qe=this.model.tokens_to_ids.get("<|endoftext|>"),Ce=qe.startsWith(" "),Er=qe.trim(),jr=mt.test(Er);if(gr||Ce||jr||Ie.length===0)Ie.push(qe),Ke.push(It),ht.push(Xt);else{const Rr=Ie.length-1;Ie[Rr]+=qe,Ke[Rr].push(...It),ht[Rr].push(...Xt)}}return[Ie,Ke,ht]}mergePunctuations(y,Y,le,we,Ie){const Ke=structuredClone(y),ht=structuredClone(Y),mt=structuredClone(le);let Mt=Ke.length-2,qe=Ke.length-1;for(;Mt>=0;)Ke[Mt].startsWith(" ")&&we.includes(Ke[Mt].trim())?(Ke[qe]=Ke[Mt]+Ke[qe],ht[qe]=(0,A.mergeArrays)(ht[Mt],ht[qe]),mt[qe]=(0,A.mergeArrays)(mt[Mt],mt[qe]),Ke[Mt]="",ht[Mt]=[],mt[Mt]=[]):qe=Mt,--Mt;for(Mt=0,qe=1;qeIt),ht.filter(It=>It.length>0),mt.filter(It=>It.length>0)]}}class Tn extends Ot{}class En extends Ot{}class Pn extends Ot{}class Os extends Ot{constructor(y,Y){super(y,Y),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(le=>this.languageRegex.test(le)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(y){if(y===null)return null;const[Y,...le]=y.trim().split(this.languageRegex);if(le.length===0)return super._encode_text(Y);if(le.length===2){const[we,Ie]=le;return this.supported_language_codes.includes(we)||console.warn(`Unsupported language code "${we}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,A.mergeArrays)([we],super._encode_text(Ie))}}}class Cn extends Ot{}class pn extends Ot{}class kn extends Ot{}class nr extends Ot{}class es extends Ot{}class hn extends Ot{constructor(y,Y){super(y,Y),this.decoder=new Qt({})}}class $n extends Ot{}class Ks extends Ot{}class Sn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:cr,DistilBertTokenizer:os,CamembertTokenizer:ot,DebertaTokenizer:$s,DebertaV2Tokenizer:Jr,BertTokenizer:Rs,HerbertTokenizer:ls,ConvBertTokenizer:Ms,RoFormerTokenizer:Ns,XLMTokenizer:dt,ElectraTokenizer:kt,MobileBertTokenizer:ks,SqueezeBertTokenizer:bs,AlbertTokenizer:ys,GPT2Tokenizer:js,BartTokenizer:sr,MBartTokenizer:Us,MBart50Tokenizer:Ss,RobertaTokenizer:Yn,WhisperTokenizer:cn,CodeGenTokenizer:Tn,CLIPTokenizer:En,SiglipTokenizer:Pn,MarianTokenizer:Os,BloomTokenizer:Mn,NllbTokenizer:un,M2M100Tokenizer:Ft,LlamaTokenizer:vn,CodeLlamaTokenizer:As,XLMRobertaTokenizer:xn,MPNetTokenizer:Jn,FalconTokenizer:Is,GPTNeoXTokenizer:hs,EsmTokenizer:Zr,Wav2Vec2CTCTokenizer:Cn,BlenderbotTokenizer:pn,BlenderbotSmallTokenizer:kn,SpeechT5Tokenizer:nr,NougatTokenizer:es,VitsTokenizer:hn,Qwen2Tokenizer:ln,GemmaTokenizer:Vs,Grok1Tokenizer:dn,CohereTokenizer:$n,MgpstrTokenizer:Ks,PreTrainedTokenizer:Ot};static async from_pretrained(y,{progress_callback:Y=null,config:le=null,cache_dir:we=null,local_files_only:Ie=!1,revision:Ke="main",legacy:ht=null}={}){const[mt,Mt]=await x(y,{progress_callback:Y,config:le,cache_dir:we,local_files_only:Ie,revision:Ke,legacy:ht}),qe=Mt.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let It=this.TOKENIZER_CLASS_MAPPING[qe];return It||(console.warn(`Unknown tokenizer class "${qe}", attempting to construct from base class.`),It=Ot),new It(mt,Mt)}}},"./src/utils/audio.js":(Me,v,s)=>{s.r(v),s.d(v,{hamming:()=>M,hanning:()=>T,mel_filter_bank:()=>N,read_audio:()=>U,spectrogram:()=>w,window_function:()=>$});var _=s("./src/utils/hub.js"),A=s("./src/utils/maths.js"),j=s("./src/utils/core.js"),ee=s("./src/utils/tensor.js");async function U(E,Z){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 J=await(await(0,_.getFile)(E)).arrayBuffer(),ae=new AudioContext({sampleRate:Z});typeof Z>"u"&&console.warn(`No sampling rate provided, using default of ${ae.sampleRate}Hz.`);const me=await ae.decodeAudioData(J);let ge;if(me.numberOfChannels===2){const Ee=Math.sqrt(2),ve=me.getChannelData(0),Le=me.getChannelData(1);ge=new Float32Array(ve.length);for(let fe=0;fe2595*Math.log10(1+E/700),kaldi:E=>1127*Math.log(1+E/700),slaney:(E,Z=1e3,J=15,ae=27/Math.log(6.4))=>E>=Z?J+Math.log(E/Z)*ae:3*E/200};function P(E,Z="htk"){const J=x[Z];if(!J)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?J(E):E.map(ae=>J(ae))}const R={htk:E=>700*(10**(E/2595)-1),kaldi:E=>700*(Math.exp(E/1127)-1),slaney:(E,Z=1e3,J=15,ae=Math.log(6.4)/27)=>E>=J?Z*Math.exp(ae*(E-J)):200*E/3};function Q(E,Z="htk"){const J=R[Z];if(!J)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?J(E):E.map(ae=>J(ae))}function ne(E,Z){const J=Float64Array.from({length:Z.length-1},(Ee,ve)=>Z[ve+1]-Z[ve]),ae=Array.from({length:E.length},()=>new Array(Z.length));for(let Ee=0;Eenew Array(E.length));for(let Ee=0;EeE+ae*ge)}function N(E,Z,J,ae,me,ge=null,Ee="htk",ve=!1){if(ge!==null&&ge!=="slaney")throw new Error('norm must be one of null or "slaney"');const Le=P(J,Ee),fe=P(ae,Ee),W=de(Le,fe,Z+2);let ce=Q(W,Ee),_e;if(ve){const Re=me/(E*2);_e=P(Float64Array.from({length:E},(We,Qe)=>Qe*Re),Ee),ce=W}else _e=de(0,Math.floor(me/2),E);const Se=ne(_e,ce);if(ge!==null&&ge==="slaney")for(let Re=0;Reme)throw Error(`frame_length (${J}) may not be larger than fft_length (${me})`);if(Ne!==J)throw new Error(`Length of the window (${Ne}) must equal frame_length (${J})`);if(ae<=0)throw new Error("hop_length must be greater than zero");if(ge===null&&W!==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(Ee){if(ve!=="reflect")throw new Error(`pad_mode="${ve}" not implemented yet.`);const I=Math.floor((me-1)/2)+1;E=K(E,I,I)}let ue=Math.floor(1+Math.floor((E.length-J)/ae));at!==null&&ueue?oe&&(He=Ue):He=tt=Ue);const Xe=new A.FFT(me),Be=new Float64Array(me),st=new Float64Array(Xe.outputBufferSize),lt=new Float32Array(ke*He);for(let I=0;I=1;--he)Be[he]-=fe*Be[he-1];Be[0]*=1-fe}for(let he=0;heMath.pow(ve,.85));break;default:throw new Error(`Unknown window type ${Z}.`)}if(J&&(Ee=Ee.subarray(0,E)),ae===null)return Ee;if(E>ae)throw new Error(`Length of the window (${E}) may not be larger than frame_length (${ae})`);return Ee}},"./src/utils/constants.js":(Me,v,s)=>{s.r(v),s.d(v,{CHAT_TEMPLATE_NAME:()=>b,CONFIG_NAME:()=>A,FEATURE_EXTRACTOR_NAME:()=>j,GENERATION_CONFIG_NAME:()=>T,GITHUB_ISSUE_URL:()=>_,IMAGE_PROCESSOR_NAME:()=>ee,PROCESSOR_NAME:()=>U});const _="https://github.com/huggingface/transformers.js/issues/new/choose",A="config.json",j="preprocessor_config.json",ee=j,U="processor_config.json",b="chat_template.json",T="generation_config.json"},"./src/utils/core.js":(Me,v,s)=>{s.r(v),s.d(v,{calculateDimensions:()=>T,calculateReflectOffset:()=>R,count:()=>de,dispatchCallback:()=>_,escapeRegExp:()=>j,isIntegralNumber:()=>U,isNullishDimension:()=>b,isTypedArray:()=>ee,len:()=>ne,mergeArrays:()=>x,pick:()=>Q,pop:()=>M,product:()=>P,reverseDictionary:()=>A});function _(N,K){N&&N(K)}function A(N){return Object.fromEntries(Object.entries(N).map(([K,q])=>[q,K]))}function j(N){return N.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ee(N){return N?.prototype?.__proto__?.constructor?.name==="TypedArray"}function U(N){return Number.isInteger(N)||typeof N=="bigint"}function b(N){return N==null||N===-1}function T(N){const K=[];let q=N;for(;Array.isArray(q);)K.push(q.length),q=q[0];return K}function M(N,K,q=void 0){const B=N[K];if(B!==void 0)return delete N[K],B;if(q===void 0)throw Error(`Key ${K} does not exist in object.`);return q}function x(...N){return Array.prototype.concat.apply([],N)}function P(...N){return N.reduce((K,q)=>K.flatMap(B=>q.map(O=>[B,O])))}function R(N,K){return Math.abs((N+K)%(2*K)-K)}function Q(N,K){return Object.assign({},...K.map(q=>{if(N[q]!==void 0)return{[q]:N[q]}}))}function ne(N){let K=0;for(const q of N)++K;return K}function de(N,K){let q=0;for(const B of N)B===K&&++q;return q}},"./src/utils/data-structures.js":(Me,v,s)=>{s.r(v),s.d(v,{CharTrie:()=>A,PriorityQueue:()=>_,TokenLattice:()=>ee});class _{constructor(T=(x,P)=>x>P,M=1/0){this._heap=[],this._comparator=T,this._maxSize=M}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 M of T)if(this.size0&&this._swap(0,M),this._heap.pop(),this._siftDown(),T}replace(T){const M=this.peek();return this._heap[0]=T,this._siftDown(),M}_parent(T){return(T+1>>>1)-1}_left(T){return(T<<1)+1}_right(T){return T+1<<1}_greater(T,M){return this._comparator(this._heap[T],this._heap[M])}_swap(T,M){const x=this._heap[T];this._heap[T]=this._heap[M],this._heap[M]=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 P=new U(this.bosTokenId,0,0,0,0),R=new U(this.eosTokenId,1,this.len,0,0);this.nodes.push(P.clone()),this.nodes.push(R.clone()),this.beginNodes[this.len].push(R),this.endNodes[0].push(P)}insert(T,M,x,P){const R=this.nodes.length,Q=new U(P,R,T,M,x);this.beginNodes[T].push(Q),this.endNodes[T+M].push(Q),this.nodes.push(Q)}viterbi(){const T=this.len;let M=0;for(;M<=T;){if(this.beginNodes[M].length==0)return[];for(let ne of this.beginNodes[M]){ne.prev=null;let de=0,N=null;for(let K of this.endNodes[M]){const q=K.backtraceScore+ne.score;(N===null||q>de)&&(N=K.clone(),de=q)}if(N!==null)ne.prev=N,ne.backtraceScore=de;else return[]}++M}const x=[],R=this.beginNodes[T][0].prev;if(R===null)return[];let Q=R.clone();for(;Q.prev!==null;)x.push(Q.clone()),Q=Q.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(M=>this.piece(M))}tokenIds(){return this.viterbi().map(M=>M.tokenId)}}class U{constructor(T,M,x,P,R){this.tokenId=T,this.nodeId=M,this.pos=x,this.length=P,this.score=R,this.prev=null,this.backtraceScore=0}clone(){const T=new U(this.tokenId,this.nodeId,this.pos,this.length,this.score);return T.prev=this.prev,T.backtraceScore=this.backtraceScore,T}}},"./src/utils/devices.js":(Me,v,s)=>{s.r(v),s.d(v,{DEVICE_TYPES:()=>_});const _=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":(Me,v,s)=>{s.r(v),s.d(v,{DATA_TYPES:()=>ee,DEFAULT_DEVICE_DTYPE_MAPPING:()=>U,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>b,isWebGpuFp16Supported:()=>j});var _=s("./src/env.js"),A=s("./src/utils/devices.js");const j=function(){let T;return async function(){if(T===void 0)if(!_.apis.IS_WEBGPU_AVAILABLE)T=!1;else try{T=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{T=!1}return T}}(),ee=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),U=Object.freeze({[A.DEVICE_TYPES.wasm]:ee.q8}),b=Object.freeze({[ee.fp32]:"",[ee.fp16]:"_fp16",[ee.int8]:"_int8",[ee.uint8]:"_uint8",[ee.q8]:"_quantized",[ee.q4]:"_q4",[ee.q4f16]:"_q4f16",[ee.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Me,v,s)=>{s.r(v),s.d(v,{Callable:()=>_});const _=class{constructor(){let A=function(...j){return A._call(...j)};return Object.setPrototypeOf(A,new.target.prototype)}_call(...A){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Me,v,s)=>{s.r(v),s.d(v,{getFile:()=>M,getModelFile:()=>ne,getModelJSON:()=>de});var _=s("?7a2c"),A=s("?a42a"),j=s("./src/env.js"),ee=s("./src/utils/core.js");const U={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class b{constructor(B){if(this.filePath=B,this.headers=new Headers,this.exists=_.existsSync(B),this.exists){this.status=200,this.statusText="OK";let O=_.statSync(B);this.headers.set("content-length",O.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start($){w.arrayBuffer().then(E=>{$.enqueue(new Uint8Array(E)),$.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const B=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",U[B]??"application/octet-stream")}clone(){let B=new b(this.filePath);return B.exists=this.exists,B.status=this.status,B.statusText=this.statusText,B.headers=new Headers(this.headers),B}async arrayBuffer(){return(await _.promises.readFile(this.filePath)).buffer}async blob(){const B=await _.promises.readFile(this.filePath);return new Blob([B],{type:this.headers.get("content-type")})}async text(){return await _.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function T(q,B=null,O=null){let w;try{w=new URL(q)}catch{return!1}return!(B&&!B.includes(w.protocol)||O&&!O.includes(w.hostname))}async function M(q){if(j.env.useFS&&!T(q,["http:","https:","blob:"]))return new b(q);if(typeof process<"u"&&process?.release?.name==="node"){const B=!!sp?.TESTING_REMOTELY,O=j.env.version,w=new Headers;if(w.set("User-Agent",`transformers.js/${O}; is_ci/${B};`),T(q,["http:","https:"],["huggingface.co","hf.co"])){const E=sp?.HF_TOKEN??sp?.HF_ACCESS_TOKEN;E&&w.set("Authorization",`Bearer ${E}`)}return fetch(q,{headers:w})}else return fetch(q)}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 P(q,B,O){if(!O)return null;const w=x[q]??`Error (${q}) occurred while trying to load file`;throw Error(`${w}: "${B}".`)}class R{constructor(B){this.path=B}async match(B){let O=A.join(this.path,B),w=new b(O);if(w.exists)return w}async put(B,O){const w=Buffer.from(await O.arrayBuffer());let $=A.join(this.path,B);try{await _.promises.mkdir(A.dirname($),{recursive:!0}),await _.promises.writeFile($,w)}catch(E){console.warn("An error occurred while writing the file to cache:",E)}}}async function Q(q,...B){for(let O of B)try{let w=await q.match(O);if(w)return w}catch{continue}}async function ne(q,B,O=!0,w={}){if(!j.env.allowLocalModels){if(w.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!j.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,ee.dispatchCallback)(w.progress_callback,{status:"initiate",name:q,file:B});let $;if(!$&&j.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{$=await caches.open("transformers-cache")}catch(ce){console.warn("An error occurred while opening the browser cache:",ce)}}if(!$&&j.env.useFSCache&&($=new R(w.cache_dir??j.env.cacheDir)),!$&&j.env.useCustomCache){if(!j.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!j.env.customCache.match||!j.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");$=j.env.customCache}const E=w.revision??"main";let Z=K(q,B),J=K(j.env.localModelPath,Z),ae=K(j.env.remoteHost,j.env.remotePathTemplate.replaceAll("{model}",q).replaceAll("{revision}",encodeURIComponent(E)),B),me=E==="main"?Z:K(q,E,B),ge,Ee=$ instanceof R?me:ae,ve=!1,Le;$&&(Le=await Q($,J,Ee));const fe=Le!==void 0;if(Le===void 0){if(j.env.allowLocalModels)if(T(Z,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Z}.`);if(!j.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Z}.`)}else try{Le=await M(J),ge=J}catch(_e){console.warn(`Unable to load from local path "${J}": "${_e}"`)}if(Le===void 0||Le.status===404){if(w.local_files_only||!j.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(Le=await M(ae),Le.status!==200)return P(Le.status,ae,O);ge=Ee}ve=$&&typeof Response<"u"&&Le instanceof Response&&Le.status===200}(0,ee.dispatchCallback)(w.progress_callback,{status:"download",name:q,file:B});let W;return w.progress_callback?fe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(W=new Uint8Array(await Le.arrayBuffer()),(0,ee.dispatchCallback)(w.progress_callback,{status:"progress",name:q,file:B,progress:100,loaded:W.length,total:W.length})):W=await N(Le,ce=>{(0,ee.dispatchCallback)(w.progress_callback,{status:"progress",name:q,file:B,...ce})}):W=new Uint8Array(await Le.arrayBuffer()),ve&&ge&&await $.match(ge)===void 0&&await $.put(ge,new Response(W,{headers:Le.headers})).catch(ce=>{console.warn(`Unable to add response to browser cache: ${ce}.`)}),(0,ee.dispatchCallback)(w.progress_callback,{status:"done",name:q,file:B}),W}async function de(q,B,O=!0,w={}){let $=await ne(q,B,O,w);if($===null)return{};let Z=new TextDecoder("utf-8").decode($);return JSON.parse(Z)}async function N(q,B){const O=q.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt(O??"0"),$=new Uint8Array(w),E=0;const Z=q.body.getReader();async function J(){const{done:ae,value:me}=await Z.read();if(ae)return;let ge=E+me.length;if(ge>w){w=ge;let ve=new Uint8Array(w);ve.set($),$=ve}$.set(me,E),E=ge;const Ee=E/w*100;return B({progress:Ee,loaded:E,total:w}),J()}return await J(),$}function K(...q){return q=q.map((B,O)=>(O&&(B=B.replace(new RegExp("^/"),"")),O!==q.length-1&&(B=B.replace(new RegExp("/$"),"")),B)),q.join("/")}},"./src/utils/image.js":(Me,v,s)=>{s.r(v),s.d(v,{RawImage:()=>Q,load_image:()=>ne});var _=s("./src/utils/core.js"),A=s("./src/utils/hub.js"),j=s("./src/env.js"),ee=s("./src/utils/tensor.js"),U=s("?2b25");let b,T,M;const x=j.apis.IS_BROWSER_ENV||j.apis.IS_WEBWORKER_ENV;if(x)b=(de,N)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(de,N)},M=self.createImageBitmap,T=self.ImageData;else if(U)M=async de=>{const K=(await de.metadata()).channels,{data:q,info:B}=await de.rotate().raw().toBuffer({resolveWithObject:!0}),O=new Q(new Uint8ClampedArray(q),B.width,B.height,B.channels);return K!==void 0&&K!==B.channels&&O.convert(K),O};else throw new Error("Unable to load image processing library.");const P={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},R=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class Q{constructor(N,K,q,B){this.data=N,this.width=K,this.height=q,this.channels=B}get size(){return[this.width,this.height]}static async read(N){if(N instanceof Q)return N;if(typeof N=="string"||N instanceof URL)return await this.fromURL(N);throw new Error(`Unsupported input type: ${typeof N}`)}static fromCanvas(N){if(!x)throw new Error("fromCanvas() is only supported in browser environments.");const q=N.getContext("2d").getImageData(0,0,N.width,N.height).data;return new Q(q,N.width,N.height,4)}static async fromURL(N){const K=await(0,A.getFile)(N);if(K.status!==200)throw new Error(`Unable to read image from "${N}" (${K.status} ${K.statusText})`);const q=await K.blob();return this.fromBlob(q)}static async fromBlob(N){if(x){const K=await M(N),q=b(K.width,K.height).getContext("2d");return q.drawImage(K,0,0),new this(q.getImageData(0,0,K.width,K.height).data,K.width,K.height,4)}else{const K=U(await N.arrayBuffer());return await M(K)}}static fromTensor(N,K="CHW"){if(N.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${N.dims.length} dimensions.`);if(K==="CHW")N=N.transpose(1,2,0);else if(K!=="HWC")throw new Error(`Unsupported channel format: ${K}`);if(!(N.data instanceof Uint8ClampedArray||N.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${N.type}`);switch(N.dims[2]){case 1:case 2:case 3:case 4:return new Q(N.data,N.dims[1],N.dims[0],N.dims[2]);default:throw new Error(`Unsupported number of channels: ${N.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const N=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let K=0,q=0;K=0?E=q:J=-q,B>=0?Z=B:ae=-B,$.drawImage(w,E,Z,N,K,J,ae,N,K),new Q($.getImageData(0,0,N,K).data,N,K,4).convert(O)}else{let O=this.toSharp();if(q>=0&&B>=0)O=O.extract({left:Math.floor(q),top:Math.floor(B),width:N,height:K});else if(q<=0&&B<=0){const w=Math.floor(-B),$=Math.floor(-q);O=O.extend({top:w,left:$,right:N-this.width-$,bottom:K-this.height-w})}else{let w=[0,0],$=0;B<0?(w[0]=Math.floor(-B),w[1]=K-this.height-w[0]):$=Math.floor(B);let E=[0,0],Z=0;q<0?(E[0]=Math.floor(-q),E[1]=N-this.width-E[0]):Z=Math.floor(q),O=O.extend({top:w[0],bottom:w[1],left:E[0],right:E[1]}).extract({left:Z,top:$,width:N,height:K})}return await M(O)}}async toBlob(N="image/png",K=1){if(!x)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:N,quality:K})}toTensor(N="CHW"){let K=new ee.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(N!=="HWC")if(N==="CHW")K=K.permute(2,0,1);else throw new Error(`Unsupported channel format: ${N}`);return K}toCanvas(){if(!x)throw new Error("toCanvas() is only supported in browser environments.");const N=this.clone().rgba(),K=b(N.width,N.height),q=new T(N.data,N.width,N.height);return K.getContext("2d").putImageData(q,0,0),K}split(){const{data:N,width:K,height:q,channels:B}=this,O=N.constructor,w=N.length/B,$=Array.from({length:B},()=>new O(w));for(let E=0;Enew Q(E,K,q,1))}_update(N,K,q,B=null){return this.data=N,this.width=K,this.height=q,B!==null&&(this.channels=B),this}clone(){return new Q(this.data.slice(),this.width,this.height,this.channels)}convert(N){if(this.channels===N)return this;switch(N){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(N){if(x){if(j.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const K=N.split(".").pop().toLowerCase(),q=R.get(K)??"image/png",B=await this.toBlob(q),O=URL.createObjectURL(B),w=document.createElement("a");w.href=O,w.download=N,w.click(),w.remove()}else{if(j.env.useFS)return await this.toSharp().toFile(N);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 U(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const ne=Q.read.bind(Q)},"./src/utils/maths.js":(Me,v,s)=>{s.r(v),s.d(v,{FFT:()=>ne,bankers_round:()=>K,cos_sim:()=>b,dot:()=>U,dynamic_time_warping:()=>q,interpolate_data:()=>_,log_softmax:()=>ee,magnitude:()=>T,max:()=>x,medianFilter:()=>de,min:()=>M,permute_data:()=>A,round:()=>N,softmax:()=>j});function _(B,[O,w,$],[E,Z],J="bilinear",ae=!1){const me=Z/$,ge=E/w,Ee=new B.constructor(E*Z*O),ve=w*$,Le=E*Z;for(let fe=0;fe=0;--ae)E[ae]=me,$[ae]=O[w[ae]],me*=$[ae];const Z=w.map((ae,me)=>E[w.indexOf(me)]),J=new B.constructor(B.length);for(let ae=0;ae=0;--ge)me+=Ee%O[ge]*Z[ge],Ee=Math.floor(Ee/O[ge]);J[me]=B[ae]}return[J,$]}function j(B){const O=x(B)[0],w=B.map(Z=>Math.exp(Z-O)),$=w.reduce((Z,J)=>Z+J,0);return w.map(Z=>Z/$)}function ee(B){const O=x(B)[0];let w=0;for(let Z=0;ZZ-O-$)}function U(B,O){let w=0;for(let $=0;$O+w*w,0))}function M(B){if(B.length===0)throw Error("Array must not be empty");let O=B[0],w=0;for(let $=1;$O&&(O=B[$],w=$);return[Number(O),w]}function P(B){return B>0&&(B&B-1)===0}class R{constructor(O){if(this.size=O|0,this.size<=1||!P(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=O<<1,this.table=new Float64Array(this.size*2);for(let $=0;$$;$<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>E&3)<>>1);for(let E=0;E>>1]=O[E];return $}toComplexArray(O,w){const $=w||this.createComplexArray();for(let E=0;E<$.length;E+=2)$[E]=O[E>>>1],$[E+1]=0;return $}transform(O,w){if(O===w)throw new Error("Input and output buffers must be different");this._transform4(O,w,1)}realTransform(O,w){if(O===w)throw new Error("Input and output buffers must be different");this._realTransform4(O,w,1)}inverseTransform(O,w){if(O===w)throw new Error("Input and output buffers must be different");this._transform4(O,w,-1);for(let $=0;$>=2;J>=2;J>>=2){ae=E/J<<1;const Le=ae>>>2;for(me=0;me>>1,J>>>1)}else for(me=0,ge=0;me>>1,J>>>1,$)}const ve=this.table;for(J>>=2;J>=2;J>>=2){ae=E/J<<1;const fe=ae>>>1,W=fe>>>1,ce=W>>>1;for(me=0;me>>1;for(let fe=2;fe>1;++Ee){const ve=(Ee+1-O)**2/2,Le=Math.sqrt(me**2+ge**2)**ve,fe=ve*Math.atan2(ge,me),W=2*Ee;Z[W]=Le*Math.cos(fe),Z[W+1]=Le*Math.sin(fe),J[W]=Z[W],J[W+1]=-Z[W+1]}this._slicedChirpBuffer=Z.subarray(w,$),this._f=new R(E>>1),this._f.transform(this._chirpBuffer,J)}_transform(O,w,$){const E=this._buffer1,Z=this._buffer2,J=this._outBuffer1,ae=this._outBuffer2,me=this._chirpBuffer,ge=this._slicedChirpBuffer,Ee=this._a;if($)for(let ve=0;ve>1,W=w[fe];E[ve]=W*ge[ve],E[Le]=W*ge[Le]}else for(let ve=0;ve=B.length&&(me=2*(B.length-1)-me),$[J++]=B[me]}$.sort(),w[Z]=$[E]}return w}function N(B,O){const w=Math.pow(10,O);return Math.round(B*w)/w}function K(B){const O=Math.round(B);return Math.abs(B)%1===.5?O%2===0?O:O-1:O}function q(B){const O=B.length,w=B[0].length,$=[O+1,w+1],E=Array.from({length:$[0]},()=>Array($[1]).fill(1/0));E[0][0]=0;const Z=Array.from({length:$[0]},()=>Array($[1]).fill(-1));for(let Ee=1;Ee<$[1];++Ee)for(let ve=1;ve<$[0];++ve){const Le=E[ve-1][Ee-1],fe=E[ve-1][Ee],W=E[ve][Ee-1];let ce,_e;Le0||ae>0;)switch(me.push(J-1),ge.push(ae-1),Z[J][ae]){case 0:--J,--ae;break;case 1:--J;break;case 2:--ae;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${J}, ${ae}]. Please file a bug report.`)}return me.reverse(),ge.reverse(),[me,ge]}},"./src/utils/tensor.js":(Me,v,s)=>{s.r(v),s.d(v,{Tensor:()=>U,cat:()=>B,full:()=>J,full_like:()=>ae,interpolate:()=>M,interpolate_4d:()=>x,layer_norm:()=>de,matmul:()=>P,mean:()=>$,mean_pooling:()=>ne,ones:()=>me,ones_like:()=>ge,permute:()=>T,quantize_embeddings:()=>Le,rfft:()=>R,stack:()=>O,std_mean:()=>w,topk:()=>Q,zeros:()=>Ee,zeros_like:()=>ve});var _=s("./src/utils/maths.js"),A=s("./src/backends/onnx.js"),j=s("./src/ops/registry.js");const ee=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class U{get dims(){return this.ort_tensor.dims}set dims(W){this.ort_tensor.dims=W}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(...W){return(0,A.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new A.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(ce,_e)=>{if(typeof _e=="string"){let Se=Number(_e);if(Number.isInteger(Se))return ce._getitem(Se)}return ce[_e]},set:(ce,_e,Se)=>ce[_e]=Se})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[W,...ce]=this.dims;if(ce.length>0){const _e=ce.reduce((Se,Re)=>Se*Re);for(let Se=0;Se0){const Se=_e.reduce((Re,We)=>Re*We);return this._subarray(W,Se,_e)}else return new U(this.type,[this.data[W]],_e)}indexOf(W){const ce=this.data;for(let _e=0;_eNe)throw new Error(`Invalid slice: ${oe}`);const ue=[Math.max(Ve,0),Math.min(Ne,this.dims[Ue])];_e.push(ue),ce.push(ue[1]-ue[0])}else throw new Error(`Invalid slice: ${oe}`)}const Se=_e.map(([Ue,oe])=>oe-Ue),Re=Se.reduce((Ue,oe)=>Ue*oe),We=this.data,Qe=new We.constructor(Re),at=this.stride();for(let Ue=0;Ue=0;--Ve){const ue=Se[Ve];oe+=(Ne%ue+_e[Ve][0])*at[Ve],Ne=Math.floor(Ne/ue)}Qe[Ue]=We[oe]}return new U(this.type,Qe,ce)}permute(...W){return T(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,ce=!1){return this.norm(1,W,ce)}norm(W="fro",ce=null,_e=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const Se=this.data;if(ce===null){let Qe=Se.reduce((at,Ue)=>at+Ue**W,0)**(1/W);return new U(this.type,[Qe],[])}ce=q(ce,this.dims.length);const Re=this.dims.slice();Re[ce]=1;const We=new Se.constructor(Se.length/this.dims[ce]);for(let Qe=0;Qe=0;--Ue){const Ne=this.dims[Ue];if(Ue!==ce){const ue=oe%Ne;at+=ue*Ve,Ve*=Re[Ue]}oe=Math.floor(oe/Ne)}We[at]+=Se[Qe]**W}if(W!==1)for(let Qe=0;Qe=0;--at){const Ve=this.dims[at];if(at!==ce){const Ne=Ue%Ve;Qe+=Ne*oe,oe*=this.dims[at]}Ue=Math.floor(Ue/Ve)}Se[We]/=Re[Qe]}return this}normalize(W=2,ce=1){return this.clone().normalize_(W,ce)}stride(){return E(this.dims)}squeeze(W=null){return new U(this.type,this.data,N(this.dims,W))}squeeze_(W=null){return this.dims=N(this.dims,W),this}unsqueeze(W=null){return new U(this.type,this.data,K(this.dims,W))}unsqueeze_(W=null){return this.dims=K(this.dims,W),this}flatten_(W=0,ce=-1){ce=(ce+this.dims.length)%this.dims.length;let _e=this.dims.slice(0,W),Se=this.dims.slice(W,ce+1),Re=this.dims.slice(ce+1);return this.dims=[..._e,Se.reduce((We,Qe)=>We*Qe,1),...Re],this}flatten(W=0,ce=-1){return this.clone().flatten_(W,ce)}view(...W){let ce=-1;for(let Se=0;SeQe!==ce?Re*We:Re,1);W[ce]=_e.length/Se}return new U(this.type,_e,W)}neg_(){const W=this.data;for(let ce=0;ceRe*We);if(ce!==_e)throw Error(`cannot reshape array of size ${ce} into shape (${W})`);let Se=fe;for(let Re=W.length-1;Re>=0;Re--)Se=Se.reduce((We,Qe)=>{let at=We[We.length-1];return at.lengthce!==1):typeof W=="number"?fe[W]===1&&fe.splice(W,1):Array.isArray(W)&&(fe=fe.filter((ce,_e)=>ce!==1||!W.includes(_e))),fe}function K(fe,W){return W=q(W,fe.length+1),fe=fe.slice(),fe.splice(W,0,1),fe}function q(fe,W,ce=null,_e=!0){if(_e&&(fe<-W||fe>=W))throw new Error(`IndexError: index ${fe} is out of bounds for dimension${ce===null?"":" "+ce} with size ${W}`);return fe<0&&(fe=(fe%W+W)%W),fe}function B(fe,W=0){W=q(W,fe[0].dims.length);const ce=fe[0].dims.slice();ce[W]=fe.reduce((We,Qe)=>We+Qe.dims[W],0);const _e=ce.reduce((We,Qe)=>We*Qe,1),Se=new fe[0].data.constructor(_e),Re=fe[0].type;if(W===0){let We=0;for(const Qe of fe){const at=Qe.data;Se.set(at,We),We+=at.length}}else{let We=0;for(let Qe=0;Qe=0;--Ne){const tt=Ue[Ne];let He=ue%tt;Ne===W&&(He+=We),Ve+=He*ke,ke*=ce[Ne],ue=Math.floor(ue/tt)}Se[Ve]=at[oe]}We+=Ue[W]}}return new U(Re,Se,ce)}function O(fe,W=0){return B(fe.map(ce=>ce.unsqueeze(W)),W)}function w(fe,W=null,ce=1,_e=!1){const Se=fe.data,Re=fe.dims;if(W===null){const Ne=Se.reduce((He,Xe)=>He+Xe,0)/Se.length,ue=Math.sqrt(Se.reduce((He,Xe)=>He+(Xe-Ne)**2,0)/(Se.length-ce)),ke=new U(fe.type,[Ne],[]);return[new U(fe.type,[ue],[]),ke]}W=q(W,Re.length);const We=$(fe,W,_e),Qe=We.data,at=Re.slice();at[W]=1;const Ue=new Se.constructor(Se.length/Re[W]);for(let Ve=0;Ve=0;--ue){const He=Re[ue];if(ue!==W){const Xe=ke%He;Ne+=Xe*tt,tt*=at[ue]}ke=Math.floor(ke/He)}Ue[Ne]+=(Se[Ve]-Qe[Ne])**2}for(let Ve=0;Veat+Ue,0);return new U(fe.type,[Qe/_e.length],[])}const Se=fe.dims;W=q(W,Se.length);const Re=Se.slice();Re[W]=1;const We=new _e.constructor(_e.length/Se[W]);for(let Qe=0;Qe<_e.length;++Qe){let at=0;for(let Ue=Se.length-1,oe=Qe,Ve=1;Ue>=0;--Ue){const Ne=Se[Ue];if(Ue!==W){const ue=oe%Ne;at+=ue*Ve,Ve*=Re[Ue]}oe=Math.floor(oe/Ne)}We[at]+=_e[Qe]}if(Se[W]!==1)for(let Qe=0;Qe=0;--ce)W[ce]=_e,_e*=fe[ce];return W}function Z(fe,W,ce,_e){const Se=fe.reduce((Re,We)=>Re*We,1);return new U(ce,new _e(Se).fill(W),fe)}function J(fe,W){let ce,_e;if(typeof W=="number")ce="float32",_e=Float32Array;else if(typeof W=="bigint")ce="int64",_e=BigInt64Array;else if(typeof W=="boolean")ce="bool",_e=Uint8Array;else throw new Error(`Unsupported data type: ${typeof W}`);return Z(fe,W,ce,_e)}function ae(fe,W){return J(fe.dims,W)}function me(fe){return Z(fe,1n,"int64",BigInt64Array)}function ge(fe){return me(fe.dims)}function Ee(fe){return Z(fe,0n,"int64",BigInt64Array)}function ve(fe){return Ee(fe.dims)}function Le(fe,W){if(fe.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(fe.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(W))throw new Error("The precision must be either 'binary' or 'ubinary'");const ce=W==="binary",_e=ce?"int8":"uint8",Se=ce?Int8Array:Uint8Array,Re=fe.data,We=new Se(Re.length/8);for(let Qe=0;Qe0?1:0,Ue=Math.floor(Qe/8),oe=Qe%8;We[Ue]|=at<<7-oe,ce&&oe===0&&(We[Ue]-=128)}return new U(_e,We,[fe.dims[0],fe.dims[1]/8])}}},Yh={};function ur(Me){var v=Yh[Me];if(v!==void 0)return v.exports;var s=Yh[Me]={exports:{}};return em[Me](s,s.exports,ur),s.exports}ur.m=em;(()=>{var Me=Object.getPrototypeOf?s=>Object.getPrototypeOf(s):s=>s.__proto__,v;ur.t=function(s,_){if(_&1&&(s=this(s)),_&8||typeof s=="object"&&s&&(_&4&&s.__esModule||_&16&&typeof s.then=="function"))return s;var A=Object.create(null);ur.r(A);var j={};v=v||[null,Me({}),Me([]),Me(Me)];for(var ee=_&2&&s;typeof ee=="object"&&!~v.indexOf(ee);ee=Me(ee))Object.getOwnPropertyNames(ee).forEach(U=>j[U]=()=>s[U]);return j.default=()=>s,ur.d(A,j),A}})();ur.d=(Me,v)=>{for(var s in v)ur.o(v,s)&&!ur.o(Me,s)&&Object.defineProperty(Me,s,{enumerable:!0,get:v[s]})};ur.o=(Me,v)=>Object.prototype.hasOwnProperty.call(Me,v);ur.r=Me=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Me,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Me,"__esModule",{value:!0})};(()=>{var Me;if(typeof import.meta.url=="string"&&(Me=import.meta.url),!Me)throw new Error("Automatic publicPath is not supported in this browser");Me=Me.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),ur.p=Me})();ur.b=new URL("./",import.meta.url);var c={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/ur.r(c),ur.d(c,{ASTFeatureExtractor:()=>M.ASTFeatureExtractor,ASTForAudioClassification:()=>s.ASTForAudioClassification,ASTModel:()=>s.ASTModel,ASTPreTrainedModel:()=>s.ASTPreTrainedModel,AlbertForMaskedLM:()=>s.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>s.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>s.AlbertForSequenceClassification,AlbertModel:()=>s.AlbertModel,AlbertPreTrainedModel:()=>s.AlbertPreTrainedModel,AlbertTokenizer:()=>_.AlbertTokenizer,AudioClassificationPipeline:()=>v.AudioClassificationPipeline,AutoConfig:()=>A.AutoConfig,AutoFeatureExtractor:()=>x.AutoFeatureExtractor,AutoImageProcessor:()=>Q.AutoImageProcessor,AutoModel:()=>s.AutoModel,AutoModelForAudioClassification:()=>s.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>s.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>s.AutoModelForCTC,AutoModelForCausalLM:()=>s.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>s.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>s.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>s.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>s.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>s.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>s.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>s.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>s.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>s.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>s.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>s.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>s.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>s.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>s.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>s.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>s.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>s.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>s.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>s.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>s.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>s.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>s.AutoModelForVision2Seq,AutoModelForXVector:()=>s.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>s.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>N.AutoProcessor,AutoTokenizer:()=>_.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>v.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>s.BartForConditionalGeneration,BartForSequenceClassification:()=>s.BartForSequenceClassification,BartModel:()=>s.BartModel,BartPretrainedModel:()=>s.BartPretrainedModel,BartTokenizer:()=>_.BartTokenizer,BaseModelOutput:()=>s.BaseModelOutput,BaseStreamer:()=>K.BaseStreamer,BeitFeatureExtractor:()=>R.BeitFeatureExtractor,BeitForImageClassification:()=>s.BeitForImageClassification,BeitModel:()=>s.BeitModel,BeitPreTrainedModel:()=>s.BeitPreTrainedModel,BertForMaskedLM:()=>s.BertForMaskedLM,BertForQuestionAnswering:()=>s.BertForQuestionAnswering,BertForSequenceClassification:()=>s.BertForSequenceClassification,BertForTokenClassification:()=>s.BertForTokenClassification,BertModel:()=>s.BertModel,BertPreTrainedModel:()=>s.BertPreTrainedModel,BertTokenizer:()=>_.BertTokenizer,BitImageProcessor:()=>R.BitImageProcessor,BlenderbotForConditionalGeneration:()=>s.BlenderbotForConditionalGeneration,BlenderbotModel:()=>s.BlenderbotModel,BlenderbotPreTrainedModel:()=>s.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>s.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>s.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>s.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>_.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>_.BlenderbotTokenizer,BloomForCausalLM:()=>s.BloomForCausalLM,BloomModel:()=>s.BloomModel,BloomPreTrainedModel:()=>s.BloomPreTrainedModel,BloomTokenizer:()=>_.BloomTokenizer,CLIPFeatureExtractor:()=>R.CLIPFeatureExtractor,CLIPImageProcessor:()=>R.CLIPImageProcessor,CLIPModel:()=>s.CLIPModel,CLIPPreTrainedModel:()=>s.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>s.CLIPSegForImageSegmentation,CLIPSegModel:()=>s.CLIPSegModel,CLIPSegPreTrainedModel:()=>s.CLIPSegPreTrainedModel,CLIPTextModel:()=>s.CLIPTextModel,CLIPTextModelWithProjection:()=>s.CLIPTextModelWithProjection,CLIPTokenizer:()=>_.CLIPTokenizer,CLIPVisionModel:()=>s.CLIPVisionModel,CLIPVisionModelWithProjection:()=>s.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>s.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>s.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>s.CamembertForSequenceClassification,CamembertForTokenClassification:()=>s.CamembertForTokenClassification,CamembertModel:()=>s.CamembertModel,CamembertPreTrainedModel:()=>s.CamembertPreTrainedModel,CamembertTokenizer:()=>_.CamembertTokenizer,CausalLMOutput:()=>s.CausalLMOutput,CausalLMOutputWithPast:()=>s.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>R.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>s.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>s.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>s.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>M.ClapFeatureExtractor,ClapModel:()=>s.ClapModel,ClapPreTrainedModel:()=>s.ClapPreTrainedModel,ClapTextModelWithProjection:()=>s.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>B.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>s.CodeGenForCausalLM,CodeGenModel:()=>s.CodeGenModel,CodeGenPreTrainedModel:()=>s.CodeGenPreTrainedModel,CodeGenTokenizer:()=>_.CodeGenTokenizer,CodeLlamaTokenizer:()=>_.CodeLlamaTokenizer,CohereForCausalLM:()=>s.CohereForCausalLM,CohereModel:()=>s.CohereModel,CoherePreTrainedModel:()=>s.CoherePreTrainedModel,CohereTokenizer:()=>_.CohereTokenizer,ConvBertForMaskedLM:()=>s.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>s.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>s.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>s.ConvBertForTokenClassification,ConvBertModel:()=>s.ConvBertModel,ConvBertPreTrainedModel:()=>s.ConvBertPreTrainedModel,ConvBertTokenizer:()=>_.ConvBertTokenizer,ConvNextFeatureExtractor:()=>R.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>s.ConvNextForImageClassification,ConvNextImageProcessor:()=>R.ConvNextImageProcessor,ConvNextModel:()=>s.ConvNextModel,ConvNextPreTrainedModel:()=>s.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>s.ConvNextV2ForImageClassification,ConvNextV2Model:()=>s.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>s.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>R.DPTFeatureExtractor,DPTForDepthEstimation:()=>s.DPTForDepthEstimation,DPTImageProcessor:()=>R.DPTImageProcessor,DPTModel:()=>s.DPTModel,DPTPreTrainedModel:()=>s.DPTPreTrainedModel,DebertaForMaskedLM:()=>s.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>s.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>s.DebertaForSequenceClassification,DebertaForTokenClassification:()=>s.DebertaForTokenClassification,DebertaModel:()=>s.DebertaModel,DebertaPreTrainedModel:()=>s.DebertaPreTrainedModel,DebertaTokenizer:()=>_.DebertaTokenizer,DebertaV2ForMaskedLM:()=>s.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>s.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>s.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>s.DebertaV2ForTokenClassification,DebertaV2Model:()=>s.DebertaV2Model,DebertaV2PreTrainedModel:()=>s.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>_.DebertaV2Tokenizer,DecisionTransformerModel:()=>s.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>s.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>R.DeiTFeatureExtractor,DeiTForImageClassification:()=>s.DeiTForImageClassification,DeiTImageProcessor:()=>R.DeiTImageProcessor,DeiTModel:()=>s.DeiTModel,DeiTPreTrainedModel:()=>s.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>s.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>s.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>v.DepthEstimationPipeline,DepthProForDepthEstimation:()=>s.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>s.DepthProPreTrainedModel,DetrFeatureExtractor:()=>R.DetrFeatureExtractor,DetrForObjectDetection:()=>s.DetrForObjectDetection,DetrForSegmentation:()=>s.DetrForSegmentation,DetrImageProcessor:()=>R.DetrImageProcessor,DetrModel:()=>s.DetrModel,DetrObjectDetectionOutput:()=>s.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>s.DetrPreTrainedModel,DetrSegmentationOutput:()=>s.DetrSegmentationOutput,Dinov2ForImageClassification:()=>s.Dinov2ForImageClassification,Dinov2Model:()=>s.Dinov2Model,Dinov2PreTrainedModel:()=>s.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>s.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>s.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>s.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>s.DistilBertForTokenClassification,DistilBertModel:()=>s.DistilBertModel,DistilBertPreTrainedModel:()=>s.DistilBertPreTrainedModel,DistilBertTokenizer:()=>_.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>v.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>R.DonutFeatureExtractor,DonutImageProcessor:()=>R.DonutImageProcessor,DonutSwinModel:()=>s.DonutSwinModel,DonutSwinPreTrainedModel:()=>s.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>s.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>R.EfficientNetImageProcessor,EfficientNetModel:()=>s.EfficientNetModel,EfficientNetPreTrainedModel:()=>s.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>s.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>s.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>s.ElectraForSequenceClassification,ElectraForTokenClassification:()=>s.ElectraForTokenClassification,ElectraModel:()=>s.ElectraModel,ElectraPreTrainedModel:()=>s.ElectraPreTrainedModel,ElectraTokenizer:()=>_.ElectraTokenizer,EosTokenCriteria:()=>q.EosTokenCriteria,EsmForMaskedLM:()=>s.EsmForMaskedLM,EsmForSequenceClassification:()=>s.EsmForSequenceClassification,EsmForTokenClassification:()=>s.EsmForTokenClassification,EsmModel:()=>s.EsmModel,EsmPreTrainedModel:()=>s.EsmPreTrainedModel,EsmTokenizer:()=>_.EsmTokenizer,FFT:()=>b.FFT,FalconForCausalLM:()=>s.FalconForCausalLM,FalconModel:()=>s.FalconModel,FalconPreTrainedModel:()=>s.FalconPreTrainedModel,FalconTokenizer:()=>_.FalconTokenizer,FastViTForImageClassification:()=>s.FastViTForImageClassification,FastViTModel:()=>s.FastViTModel,FastViTPreTrainedModel:()=>s.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>v.FeatureExtractionPipeline,FeatureExtractor:()=>T.FeatureExtractor,FillMaskPipeline:()=>v.FillMaskPipeline,Florence2ForConditionalGeneration:()=>s.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>s.Florence2PreTrainedModel,Florence2Processor:()=>de.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>B.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>B.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>R.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>s.GLPNForDepthEstimation,GLPNModel:()=>s.GLPNModel,GLPNPreTrainedModel:()=>s.GLPNPreTrainedModel,GPT2LMHeadModel:()=>s.GPT2LMHeadModel,GPT2Model:()=>s.GPT2Model,GPT2PreTrainedModel:()=>s.GPT2PreTrainedModel,GPT2Tokenizer:()=>_.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>s.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>s.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>s.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>s.GPTJForCausalLM,GPTJModel:()=>s.GPTJModel,GPTJPreTrainedModel:()=>s.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>s.GPTNeoForCausalLM,GPTNeoModel:()=>s.GPTNeoModel,GPTNeoPreTrainedModel:()=>s.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>s.GPTNeoXForCausalLM,GPTNeoXModel:()=>s.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>s.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>_.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>s.Gemma2ForCausalLM,Gemma2Model:()=>s.Gemma2Model,Gemma2PreTrainedModel:()=>s.Gemma2PreTrainedModel,GemmaForCausalLM:()=>s.GemmaForCausalLM,GemmaModel:()=>s.GemmaModel,GemmaPreTrainedModel:()=>s.GemmaPreTrainedModel,GemmaTokenizer:()=>_.GemmaTokenizer,GraniteForCausalLM:()=>s.GraniteForCausalLM,GraniteModel:()=>s.GraniteModel,GranitePreTrainedModel:()=>s.GranitePreTrainedModel,Grok1Tokenizer:()=>_.Grok1Tokenizer,GroupViTModel:()=>s.GroupViTModel,GroupViTPreTrainedModel:()=>s.GroupViTPreTrainedModel,HerbertTokenizer:()=>_.HerbertTokenizer,HieraForImageClassification:()=>s.HieraForImageClassification,HieraModel:()=>s.HieraModel,HieraPreTrainedModel:()=>s.HieraPreTrainedModel,HubertForCTC:()=>s.HubertForCTC,HubertForSequenceClassification:()=>s.HubertForSequenceClassification,HubertModel:()=>s.HubertModel,HubertPreTrainedModel:()=>s.HubertPreTrainedModel,IJepaForImageClassification:()=>s.IJepaForImageClassification,IJepaModel:()=>s.IJepaModel,IJepaPreTrainedModel:()=>s.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>s.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>R.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>s.Idefics3PreTrainedModel,Idefics3Processor:()=>de.Idefics3Processor,ImageClassificationPipeline:()=>v.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>v.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>M.ImageFeatureExtractor,ImageMattingOutput:()=>s.ImageMattingOutput,ImageProcessor:()=>P.ImageProcessor,ImageSegmentationPipeline:()=>v.ImageSegmentationPipeline,ImageToImagePipeline:()=>v.ImageToImagePipeline,ImageToTextPipeline:()=>v.ImageToTextPipeline,InterruptableStoppingCriteria:()=>q.InterruptableStoppingCriteria,JAISLMHeadModel:()=>s.JAISLMHeadModel,JAISModel:()=>s.JAISModel,JAISPreTrainedModel:()=>s.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>R.JinaCLIPImageProcessor,JinaCLIPModel:()=>s.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>s.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>de.JinaCLIPProcessor,JinaCLIPTextModel:()=>s.JinaCLIPTextModel,JinaCLIPVisionModel:()=>s.JinaCLIPVisionModel,LlamaForCausalLM:()=>s.LlamaForCausalLM,LlamaModel:()=>s.LlamaModel,LlamaPreTrainedModel:()=>s.LlamaPreTrainedModel,LlamaTokenizer:()=>_.LlamaTokenizer,LlavaForConditionalGeneration:()=>s.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>s.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>R.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>s.LlavaPreTrainedModel,LogitsProcessor:()=>B.LogitsProcessor,LogitsProcessorList:()=>B.LogitsProcessorList,LogitsWarper:()=>B.LogitsWarper,LongT5ForConditionalGeneration:()=>s.LongT5ForConditionalGeneration,LongT5Model:()=>s.LongT5Model,LongT5PreTrainedModel:()=>s.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>s.M2M100ForConditionalGeneration,M2M100Model:()=>s.M2M100Model,M2M100PreTrainedModel:()=>s.M2M100PreTrainedModel,M2M100Tokenizer:()=>_.M2M100Tokenizer,MBart50Tokenizer:()=>_.MBart50Tokenizer,MBartForCausalLM:()=>s.MBartForCausalLM,MBartForConditionalGeneration:()=>s.MBartForConditionalGeneration,MBartForSequenceClassification:()=>s.MBartForSequenceClassification,MBartModel:()=>s.MBartModel,MBartPreTrainedModel:()=>s.MBartPreTrainedModel,MBartTokenizer:()=>_.MBartTokenizer,MPNetForMaskedLM:()=>s.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>s.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>s.MPNetForSequenceClassification,MPNetForTokenClassification:()=>s.MPNetForTokenClassification,MPNetModel:()=>s.MPNetModel,MPNetPreTrainedModel:()=>s.MPNetPreTrainedModel,MPNetTokenizer:()=>_.MPNetTokenizer,MT5ForConditionalGeneration:()=>s.MT5ForConditionalGeneration,MT5Model:()=>s.MT5Model,MT5PreTrainedModel:()=>s.MT5PreTrainedModel,MarianMTModel:()=>s.MarianMTModel,MarianModel:()=>s.MarianModel,MarianPreTrainedModel:()=>s.MarianPreTrainedModel,MarianTokenizer:()=>_.MarianTokenizer,Mask2FormerImageProcessor:()=>R.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>R.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>s.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>R.MaskFormerImageProcessor,MaskFormerModel:()=>s.MaskFormerModel,MaskFormerPreTrainedModel:()=>s.MaskFormerPreTrainedModel,MaskedLMOutput:()=>s.MaskedLMOutput,MaxLengthCriteria:()=>q.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>s.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>s.MgpstrModelOutput,MgpstrPreTrainedModel:()=>s.MgpstrPreTrainedModel,MgpstrProcessor:()=>de.MgpstrProcessor,MgpstrTokenizer:()=>_.MgpstrTokenizer,MinLengthLogitsProcessor:()=>B.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>B.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>s.MistralForCausalLM,MistralModel:()=>s.MistralModel,MistralPreTrainedModel:()=>s.MistralPreTrainedModel,MobileBertForMaskedLM:()=>s.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>s.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>s.MobileBertForSequenceClassification,MobileBertModel:()=>s.MobileBertModel,MobileBertPreTrainedModel:()=>s.MobileBertPreTrainedModel,MobileBertTokenizer:()=>_.MobileBertTokenizer,MobileLLMForCausalLM:()=>s.MobileLLMForCausalLM,MobileLLMModel:()=>s.MobileLLMModel,MobileLLMPreTrainedModel:()=>s.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>R.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>s.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>R.MobileNetV1ImageProcessor,MobileNetV1Model:()=>s.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>s.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>R.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>s.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>R.MobileNetV2ImageProcessor,MobileNetV2Model:()=>s.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>s.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>R.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>s.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>R.MobileNetV3ImageProcessor,MobileNetV3Model:()=>s.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>s.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>R.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>s.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>R.MobileNetV4ImageProcessor,MobileNetV4Model:()=>s.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>s.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>R.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>s.MobileViTForImageClassification,MobileViTImageProcessor:()=>R.MobileViTImageProcessor,MobileViTModel:()=>s.MobileViTModel,MobileViTPreTrainedModel:()=>s.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>s.MobileViTV2ForImageClassification,MobileViTV2Model:()=>s.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>s.MobileViTV2PreTrainedModel,ModelOutput:()=>s.ModelOutput,Moondream1ForConditionalGeneration:()=>s.Moondream1ForConditionalGeneration,MptForCausalLM:()=>s.MptForCausalLM,MptModel:()=>s.MptModel,MptPreTrainedModel:()=>s.MptPreTrainedModel,MultiModalityCausalLM:()=>s.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>s.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>s.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>s.MusicgenForConditionalGeneration,MusicgenModel:()=>s.MusicgenModel,MusicgenPreTrainedModel:()=>s.MusicgenPreTrainedModel,NllbTokenizer:()=>_.NllbTokenizer,NoBadWordsLogitsProcessor:()=>B.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>B.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>s.NomicBertModel,NomicBertPreTrainedModel:()=>s.NomicBertPreTrainedModel,NougatImageProcessor:()=>R.NougatImageProcessor,NougatTokenizer:()=>_.NougatTokenizer,OPTForCausalLM:()=>s.OPTForCausalLM,OPTModel:()=>s.OPTModel,OPTPreTrainedModel:()=>s.OPTPreTrainedModel,ObjectDetectionPipeline:()=>v.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>s.Olmo2ForCausalLM,Olmo2Model:()=>s.Olmo2Model,Olmo2PreTrainedModel:()=>s.Olmo2PreTrainedModel,OlmoForCausalLM:()=>s.OlmoForCausalLM,OlmoModel:()=>s.OlmoModel,OlmoPreTrainedModel:()=>s.OlmoPreTrainedModel,OpenELMForCausalLM:()=>s.OpenELMForCausalLM,OpenELMModel:()=>s.OpenELMModel,OpenELMPreTrainedModel:()=>s.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>R.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>s.OwlViTForObjectDetection,OwlViTImageProcessor:()=>R.OwlViTImageProcessor,OwlViTModel:()=>s.OwlViTModel,OwlViTPreTrainedModel:()=>s.OwlViTPreTrainedModel,OwlViTProcessor:()=>de.OwlViTProcessor,Owlv2ForObjectDetection:()=>s.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>R.Owlv2ImageProcessor,Owlv2Model:()=>s.Owlv2Model,Owlv2PreTrainedModel:()=>s.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>s.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>s.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>de.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>s.PatchTSMixerForPrediction,PatchTSMixerModel:()=>s.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>s.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>s.PatchTSTForPrediction,PatchTSTModel:()=>s.PatchTSTModel,PatchTSTPreTrainedModel:()=>s.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>s.Phi3ForCausalLM,Phi3Model:()=>s.Phi3Model,Phi3PreTrainedModel:()=>s.Phi3PreTrainedModel,PhiForCausalLM:()=>s.PhiForCausalLM,PhiModel:()=>s.PhiModel,PhiPreTrainedModel:()=>s.PhiPreTrainedModel,Pipeline:()=>v.Pipeline,PreTrainedModel:()=>s.PreTrainedModel,PreTrainedTokenizer:()=>_.PreTrainedTokenizer,PretrainedConfig:()=>A.PretrainedConfig,PretrainedMixin:()=>s.PretrainedMixin,Processor:()=>ne.Processor,PvtForImageClassification:()=>s.PvtForImageClassification,PvtImageProcessor:()=>R.PvtImageProcessor,PvtModel:()=>s.PvtModel,PvtPreTrainedModel:()=>s.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>M.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>s.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>s.PyAnnoteModel,PyAnnotePreTrainedModel:()=>s.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>de.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>s.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>v.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>s.Qwen2ForCausalLM,Qwen2Model:()=>s.Qwen2Model,Qwen2PreTrainedModel:()=>s.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>_.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>s.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>R.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>s.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>de.Qwen2VLProcessor,RTDetrForObjectDetection:()=>s.RTDetrForObjectDetection,RTDetrImageProcessor:()=>R.RTDetrImageProcessor,RTDetrModel:()=>s.RTDetrModel,RTDetrObjectDetectionOutput:()=>s.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>s.RTDetrPreTrainedModel,RawImage:()=>ee.RawImage,RepetitionPenaltyLogitsProcessor:()=>B.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>s.ResNetForImageClassification,ResNetModel:()=>s.ResNetModel,ResNetPreTrainedModel:()=>s.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>s.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>s.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>s.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>s.RoFormerForTokenClassification,RoFormerModel:()=>s.RoFormerModel,RoFormerPreTrainedModel:()=>s.RoFormerPreTrainedModel,RoFormerTokenizer:()=>_.RoFormerTokenizer,RobertaForMaskedLM:()=>s.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>s.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>s.RobertaForSequenceClassification,RobertaForTokenClassification:()=>s.RobertaForTokenClassification,RobertaModel:()=>s.RobertaModel,RobertaPreTrainedModel:()=>s.RobertaPreTrainedModel,RobertaTokenizer:()=>_.RobertaTokenizer,SamImageProcessor:()=>R.SamImageProcessor,SamImageSegmentationOutput:()=>s.SamImageSegmentationOutput,SamModel:()=>s.SamModel,SamPreTrainedModel:()=>s.SamPreTrainedModel,SamProcessor:()=>de.SamProcessor,SapiensForDepthEstimation:()=>s.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>s.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>s.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>s.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>M.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>R.SegformerFeatureExtractor,SegformerForImageClassification:()=>s.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>s.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>R.SegformerImageProcessor,SegformerModel:()=>s.SegformerModel,SegformerPreTrainedModel:()=>s.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>s.Seq2SeqLMOutput,SequenceClassifierOutput:()=>s.SequenceClassifierOutput,SiglipImageProcessor:()=>R.SiglipImageProcessor,SiglipModel:()=>s.SiglipModel,SiglipPreTrainedModel:()=>s.SiglipPreTrainedModel,SiglipTextModel:()=>s.SiglipTextModel,SiglipTokenizer:()=>_.SiglipTokenizer,SiglipVisionModel:()=>s.SiglipVisionModel,SpeechT5FeatureExtractor:()=>M.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>s.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>s.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>s.SpeechT5HifiGan,SpeechT5Model:()=>s.SpeechT5Model,SpeechT5PreTrainedModel:()=>s.SpeechT5PreTrainedModel,SpeechT5Processor:()=>de.SpeechT5Processor,SpeechT5Tokenizer:()=>_.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>s.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>s.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>s.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>s.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>s.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>_.SqueezeBertTokenizer,StableLmForCausalLM:()=>s.StableLmForCausalLM,StableLmModel:()=>s.StableLmModel,StableLmPreTrainedModel:()=>s.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>s.Starcoder2ForCausalLM,Starcoder2Model:()=>s.Starcoder2Model,Starcoder2PreTrainedModel:()=>s.Starcoder2PreTrainedModel,StoppingCriteria:()=>q.StoppingCriteria,StoppingCriteriaList:()=>q.StoppingCriteriaList,SummarizationPipeline:()=>v.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>B.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>s.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>R.Swin2SRImageProcessor,Swin2SRModel:()=>s.Swin2SRModel,Swin2SRPreTrainedModel:()=>s.Swin2SRPreTrainedModel,SwinForImageClassification:()=>s.SwinForImageClassification,SwinModel:()=>s.SwinModel,SwinPreTrainedModel:()=>s.SwinPreTrainedModel,T5ForConditionalGeneration:()=>s.T5ForConditionalGeneration,T5Model:()=>s.T5Model,T5PreTrainedModel:()=>s.T5PreTrainedModel,T5Tokenizer:()=>_.T5Tokenizer,TableTransformerForObjectDetection:()=>s.TableTransformerForObjectDetection,TableTransformerModel:()=>s.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>s.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>s.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>B.TemperatureLogitsWarper,Tensor:()=>U.Tensor,Text2TextGenerationPipeline:()=>v.Text2TextGenerationPipeline,TextClassificationPipeline:()=>v.TextClassificationPipeline,TextGenerationPipeline:()=>v.TextGenerationPipeline,TextStreamer:()=>K.TextStreamer,TextToAudioPipeline:()=>v.TextToAudioPipeline,TokenClassificationPipeline:()=>v.TokenClassificationPipeline,TokenClassifierOutput:()=>s.TokenClassifierOutput,TokenizerModel:()=>_.TokenizerModel,TopKLogitsWarper:()=>B.TopKLogitsWarper,TopPLogitsWarper:()=>B.TopPLogitsWarper,TrOCRForCausalLM:()=>s.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>s.TrOCRPreTrainedModel,TranslationPipeline:()=>v.TranslationPipeline,UniSpeechForCTC:()=>s.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>s.UniSpeechForSequenceClassification,UniSpeechModel:()=>s.UniSpeechModel,UniSpeechPreTrainedModel:()=>s.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>s.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>s.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>s.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>s.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>s.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>de.VLChatProcessor,VLMImageProcessor:()=>R.VLMImageProcessor,ViTFeatureExtractor:()=>R.ViTFeatureExtractor,ViTForImageClassification:()=>s.ViTForImageClassification,ViTImageProcessor:()=>R.ViTImageProcessor,ViTMAEModel:()=>s.ViTMAEModel,ViTMAEPreTrainedModel:()=>s.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>s.ViTMSNForImageClassification,ViTMSNModel:()=>s.ViTMSNModel,ViTMSNPreTrainedModel:()=>s.ViTMSNPreTrainedModel,ViTModel:()=>s.ViTModel,ViTPreTrainedModel:()=>s.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>s.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>s.VitMatteForImageMatting,VitMatteImageProcessor:()=>R.VitMatteImageProcessor,VitMattePreTrainedModel:()=>s.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>s.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>R.VitPoseImageProcessor,VitPosePreTrainedModel:()=>s.VitPosePreTrainedModel,VitsModel:()=>s.VitsModel,VitsModelOutput:()=>s.VitsModelOutput,VitsPreTrainedModel:()=>s.VitsPreTrainedModel,VitsTokenizer:()=>_.VitsTokenizer,Wav2Vec2BertForCTC:()=>s.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>s.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>s.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>s.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>_.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>M.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>s.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>s.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>s.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>s.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>s.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>de.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>s.WavLMForAudioFrameClassification,WavLMForCTC:()=>s.WavLMForCTC,WavLMForSequenceClassification:()=>s.WavLMForSequenceClassification,WavLMForXVector:()=>s.WavLMForXVector,WavLMModel:()=>s.WavLMModel,WavLMPreTrainedModel:()=>s.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>M.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>s.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>s.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>s.WhisperForConditionalGeneration,WhisperModel:()=>s.WhisperModel,WhisperPreTrainedModel:()=>s.WhisperPreTrainedModel,WhisperProcessor:()=>de.WhisperProcessor,WhisperTextStreamer:()=>K.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>B.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>_.WhisperTokenizer,XLMForQuestionAnswering:()=>s.XLMForQuestionAnswering,XLMForSequenceClassification:()=>s.XLMForSequenceClassification,XLMForTokenClassification:()=>s.XLMForTokenClassification,XLMModel:()=>s.XLMModel,XLMPreTrainedModel:()=>s.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>s.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>s.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>s.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>s.XLMRobertaForTokenClassification,XLMRobertaModel:()=>s.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>s.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>_.XLMRobertaTokenizer,XLMTokenizer:()=>_.XLMTokenizer,XLMWithLMHeadModel:()=>s.XLMWithLMHeadModel,XVectorOutput:()=>s.XVectorOutput,YolosFeatureExtractor:()=>R.YolosFeatureExtractor,YolosForObjectDetection:()=>s.YolosForObjectDetection,YolosImageProcessor:()=>R.YolosImageProcessor,YolosModel:()=>s.YolosModel,YolosObjectDetectionOutput:()=>s.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>s.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>v.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>v.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>v.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>v.ZeroShotObjectDetectionPipeline,bankers_round:()=>b.bankers_round,cat:()=>U.cat,cos_sim:()=>b.cos_sim,dot:()=>b.dot,dynamic_time_warping:()=>b.dynamic_time_warping,env:()=>Me.env,full:()=>U.full,full_like:()=>U.full_like,getKeyValueShapes:()=>A.getKeyValueShapes,hamming:()=>j.hamming,hanning:()=>j.hanning,interpolate:()=>U.interpolate,interpolate_4d:()=>U.interpolate_4d,interpolate_data:()=>b.interpolate_data,is_chinese_char:()=>_.is_chinese_char,layer_norm:()=>U.layer_norm,load_image:()=>ee.load_image,log_softmax:()=>b.log_softmax,magnitude:()=>b.magnitude,matmul:()=>U.matmul,max:()=>b.max,mean:()=>U.mean,mean_pooling:()=>U.mean_pooling,medianFilter:()=>b.medianFilter,mel_filter_bank:()=>j.mel_filter_bank,min:()=>b.min,ones:()=>U.ones,ones_like:()=>U.ones_like,permute:()=>U.permute,permute_data:()=>b.permute_data,pipeline:()=>v.pipeline,quantize_embeddings:()=>U.quantize_embeddings,read_audio:()=>j.read_audio,rfft:()=>U.rfft,round:()=>b.round,softmax:()=>b.softmax,spectrogram:()=>j.spectrogram,stack:()=>U.stack,std_mean:()=>U.std_mean,topk:()=>U.topk,window_function:()=>j.window_function,zeros:()=>U.zeros,zeros_like:()=>U.zeros_like});var Me=ur("./src/env.js"),v=ur("./src/pipelines.js"),s=ur("./src/models.js"),_=ur("./src/tokenizers.js"),A=ur("./src/configs.js"),j=ur("./src/utils/audio.js"),ee=ur("./src/utils/image.js"),U=ur("./src/utils/tensor.js"),b=ur("./src/utils/maths.js"),T=ur("./src/base/feature_extraction_utils.js"),M=ur("./src/models/feature_extractors.js"),x=ur("./src/models/auto/feature_extraction_auto.js"),P=ur("./src/base/image_processors_utils.js"),R=ur("./src/models/image_processors.js"),Q=ur("./src/models/auto/image_processing_auto.js"),ne=ur("./src/base/processing_utils.js"),de=ur("./src/models/processors.js"),N=ur("./src/models/auto/processing_auto.js"),K=ur("./src/generation/streamers.js"),q=ur("./src/generation/stopping_criteria.js"),B=ur("./src/generation/logits_process.js")})();c.ASTFeatureExtractor;c.ASTForAudioClassification;c.ASTModel;c.ASTPreTrainedModel;c.AlbertForMaskedLM;c.AlbertForQuestionAnswering;c.AlbertForSequenceClassification;c.AlbertModel;c.AlbertPreTrainedModel;c.AlbertTokenizer;c.AudioClassificationPipeline;c.AutoConfig;c.AutoFeatureExtractor;c.AutoImageProcessor;c.AutoModel;c.AutoModelForAudioClassification;c.AutoModelForAudioFrameClassification;c.AutoModelForCTC;var If=c.AutoModelForCausalLM;c.AutoModelForDepthEstimation;c.AutoModelForDocumentQuestionAnswering;c.AutoModelForImageClassification;c.AutoModelForImageFeatureExtraction;c.AutoModelForImageMatting;c.AutoModelForImageSegmentation;c.AutoModelForImageToImage;c.AutoModelForMaskGeneration;c.AutoModelForMaskedLM;c.AutoModelForNormalEstimation;c.AutoModelForObjectDetection;c.AutoModelForPoseEstimation;c.AutoModelForQuestionAnswering;c.AutoModelForSemanticSegmentation;c.AutoModelForSeq2SeqLM;c.AutoModelForSequenceClassification;c.AutoModelForSpeechSeq2Seq;c.AutoModelForTextToSpectrogram;c.AutoModelForTextToWaveform;c.AutoModelForTokenClassification;c.AutoModelForUniversalSegmentation;c.AutoModelForVision2Seq;c.AutoModelForXVector;c.AutoModelForZeroShotObjectDetection;c.AutoProcessor;var Of=c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline;c.BartForConditionalGeneration;c.BartForSequenceClassification;c.BartModel;c.BartPretrainedModel;c.BartTokenizer;c.BaseModelOutput;c.BaseStreamer;c.BeitFeatureExtractor;c.BeitForImageClassification;c.BeitModel;c.BeitPreTrainedModel;c.BertForMaskedLM;c.BertForQuestionAnswering;c.BertForSequenceClassification;c.BertForTokenClassification;c.BertModel;c.BertPreTrainedModel;c.BertTokenizer;c.BitImageProcessor;c.BlenderbotForConditionalGeneration;c.BlenderbotModel;c.BlenderbotPreTrainedModel;c.BlenderbotSmallForConditionalGeneration;c.BlenderbotSmallModel;c.BlenderbotSmallPreTrainedModel;c.BlenderbotSmallTokenizer;c.BlenderbotTokenizer;c.BloomForCausalLM;c.BloomModel;c.BloomPreTrainedModel;c.BloomTokenizer;c.CLIPFeatureExtractor;c.CLIPImageProcessor;c.CLIPModel;c.CLIPPreTrainedModel;c.CLIPSegForImageSegmentation;c.CLIPSegModel;c.CLIPSegPreTrainedModel;c.CLIPTextModel;c.CLIPTextModelWithProjection;c.CLIPTokenizer;c.CLIPVisionModel;c.CLIPVisionModelWithProjection;c.CamembertForMaskedLM;c.CamembertForQuestionAnswering;c.CamembertForSequenceClassification;c.CamembertForTokenClassification;c.CamembertModel;c.CamembertPreTrainedModel;c.CamembertTokenizer;c.CausalLMOutput;c.CausalLMOutputWithPast;c.ChineseCLIPFeatureExtractor;c.ChineseCLIPModel;c.ChineseCLIPPreTrainedModel;c.ClapAudioModelWithProjection;c.ClapFeatureExtractor;c.ClapModel;c.ClapPreTrainedModel;c.ClapTextModelWithProjection;c.ClassifierFreeGuidanceLogitsProcessor;c.CodeGenForCausalLM;c.CodeGenModel;c.CodeGenPreTrainedModel;c.CodeGenTokenizer;c.CodeLlamaTokenizer;c.CohereForCausalLM;c.CohereModel;c.CoherePreTrainedModel;c.CohereTokenizer;c.ConvBertForMaskedLM;c.ConvBertForQuestionAnswering;c.ConvBertForSequenceClassification;c.ConvBertForTokenClassification;c.ConvBertModel;c.ConvBertPreTrainedModel;c.ConvBertTokenizer;c.ConvNextFeatureExtractor;c.ConvNextForImageClassification;c.ConvNextImageProcessor;c.ConvNextModel;c.ConvNextPreTrainedModel;c.ConvNextV2ForImageClassification;c.ConvNextV2Model;c.ConvNextV2PreTrainedModel;c.DPTFeatureExtractor;c.DPTForDepthEstimation;c.DPTImageProcessor;c.DPTModel;c.DPTPreTrainedModel;c.DebertaForMaskedLM;c.DebertaForQuestionAnswering;c.DebertaForSequenceClassification;c.DebertaForTokenClassification;c.DebertaModel;c.DebertaPreTrainedModel;c.DebertaTokenizer;c.DebertaV2ForMaskedLM;c.DebertaV2ForQuestionAnswering;c.DebertaV2ForSequenceClassification;c.DebertaV2ForTokenClassification;c.DebertaV2Model;c.DebertaV2PreTrainedModel;c.DebertaV2Tokenizer;c.DecisionTransformerModel;c.DecisionTransformerPreTrainedModel;c.DeiTFeatureExtractor;c.DeiTForImageClassification;c.DeiTImageProcessor;c.DeiTModel;c.DeiTPreTrainedModel;c.DepthAnythingForDepthEstimation;c.DepthAnythingPreTrainedModel;c.DepthEstimationPipeline;c.DepthProForDepthEstimation;c.DepthProPreTrainedModel;c.DetrFeatureExtractor;c.DetrForObjectDetection;c.DetrForSegmentation;c.DetrImageProcessor;c.DetrModel;c.DetrObjectDetectionOutput;c.DetrPreTrainedModel;c.DetrSegmentationOutput;c.Dinov2ForImageClassification;c.Dinov2Model;c.Dinov2PreTrainedModel;c.DistilBertForMaskedLM;c.DistilBertForQuestionAnswering;c.DistilBertForSequenceClassification;c.DistilBertForTokenClassification;c.DistilBertModel;c.DistilBertPreTrainedModel;c.DistilBertTokenizer;c.DocumentQuestionAnsweringPipeline;c.DonutFeatureExtractor;c.DonutImageProcessor;c.DonutSwinModel;c.DonutSwinPreTrainedModel;c.EfficientNetForImageClassification;c.EfficientNetImageProcessor;c.EfficientNetModel;c.EfficientNetPreTrainedModel;c.ElectraForMaskedLM;c.ElectraForQuestionAnswering;c.ElectraForSequenceClassification;c.ElectraForTokenClassification;c.ElectraModel;c.ElectraPreTrainedModel;c.ElectraTokenizer;c.EosTokenCriteria;c.EsmForMaskedLM;c.EsmForSequenceClassification;c.EsmForTokenClassification;c.EsmModel;c.EsmPreTrainedModel;c.EsmTokenizer;c.FFT;c.FalconForCausalLM;c.FalconModel;c.FalconPreTrainedModel;c.FalconTokenizer;c.FastViTForImageClassification;c.FastViTModel;c.FastViTPreTrainedModel;c.FeatureExtractionPipeline;c.FeatureExtractor;c.FillMaskPipeline;c.Florence2ForConditionalGeneration;c.Florence2PreTrainedModel;c.Florence2Processor;c.ForcedBOSTokenLogitsProcessor;c.ForcedEOSTokenLogitsProcessor;c.GLPNFeatureExtractor;c.GLPNForDepthEstimation;c.GLPNModel;c.GLPNPreTrainedModel;c.GPT2LMHeadModel;c.GPT2Model;c.GPT2PreTrainedModel;c.GPT2Tokenizer;c.GPTBigCodeForCausalLM;c.GPTBigCodeModel;c.GPTBigCodePreTrainedModel;c.GPTJForCausalLM;c.GPTJModel;c.GPTJPreTrainedModel;c.GPTNeoForCausalLM;c.GPTNeoModel;c.GPTNeoPreTrainedModel;c.GPTNeoXForCausalLM;c.GPTNeoXModel;c.GPTNeoXPreTrainedModel;c.GPTNeoXTokenizer;c.Gemma2ForCausalLM;c.Gemma2Model;c.Gemma2PreTrainedModel;c.GemmaForCausalLM;c.GemmaModel;c.GemmaPreTrainedModel;c.GemmaTokenizer;c.GraniteForCausalLM;c.GraniteModel;c.GranitePreTrainedModel;c.Grok1Tokenizer;c.GroupViTModel;c.GroupViTPreTrainedModel;c.HerbertTokenizer;c.HieraForImageClassification;c.HieraModel;c.HieraPreTrainedModel;c.HubertForCTC;c.HubertForSequenceClassification;c.HubertModel;c.HubertPreTrainedModel;c.IJepaForImageClassification;c.IJepaModel;c.IJepaPreTrainedModel;c.Idefics3ForConditionalGeneration;c.Idefics3ImageProcessor;c.Idefics3PreTrainedModel;c.Idefics3Processor;c.ImageClassificationPipeline;c.ImageFeatureExtractionPipeline;c.ImageFeatureExtractor;c.ImageMattingOutput;c.ImageProcessor;c.ImageSegmentationPipeline;c.ImageToImagePipeline;c.ImageToTextPipeline;c.InterruptableStoppingCriteria;c.JAISLMHeadModel;c.JAISModel;c.JAISPreTrainedModel;c.JinaCLIPImageProcessor;c.JinaCLIPModel;c.JinaCLIPPreTrainedModel;c.JinaCLIPProcessor;c.JinaCLIPTextModel;c.JinaCLIPVisionModel;c.LlamaForCausalLM;c.LlamaModel;c.LlamaPreTrainedModel;c.LlamaTokenizer;c.LlavaForConditionalGeneration;c.LlavaOnevisionForConditionalGeneration;c.LlavaOnevisionImageProcessor;c.LlavaPreTrainedModel;c.LogitsProcessor;c.LogitsProcessorList;c.LogitsWarper;c.LongT5ForConditionalGeneration;c.LongT5Model;c.LongT5PreTrainedModel;c.M2M100ForConditionalGeneration;c.M2M100Model;c.M2M100PreTrainedModel;c.M2M100Tokenizer;c.MBart50Tokenizer;c.MBartForCausalLM;c.MBartForConditionalGeneration;c.MBartForSequenceClassification;c.MBartModel;c.MBartPreTrainedModel;c.MBartTokenizer;c.MPNetForMaskedLM;c.MPNetForQuestionAnswering;c.MPNetForSequenceClassification;c.MPNetForTokenClassification;c.MPNetModel;c.MPNetPreTrainedModel;c.MPNetTokenizer;c.MT5ForConditionalGeneration;c.MT5Model;c.MT5PreTrainedModel;c.MarianMTModel;c.MarianModel;c.MarianPreTrainedModel;c.MarianTokenizer;c.Mask2FormerImageProcessor;c.MaskFormerFeatureExtractor;c.MaskFormerForInstanceSegmentation;c.MaskFormerImageProcessor;c.MaskFormerModel;c.MaskFormerPreTrainedModel;c.MaskedLMOutput;c.MaxLengthCriteria;c.MgpstrForSceneTextRecognition;c.MgpstrModelOutput;c.MgpstrPreTrainedModel;c.MgpstrProcessor;c.MgpstrTokenizer;c.MinLengthLogitsProcessor;c.MinNewTokensLengthLogitsProcessor;c.MistralForCausalLM;c.MistralModel;c.MistralPreTrainedModel;c.MobileBertForMaskedLM;c.MobileBertForQuestionAnswering;c.MobileBertForSequenceClassification;c.MobileBertModel;c.MobileBertPreTrainedModel;c.MobileBertTokenizer;c.MobileLLMForCausalLM;c.MobileLLMModel;c.MobileLLMPreTrainedModel;c.MobileNetV1FeatureExtractor;c.MobileNetV1ForImageClassification;c.MobileNetV1ImageProcessor;c.MobileNetV1Model;c.MobileNetV1PreTrainedModel;c.MobileNetV2FeatureExtractor;c.MobileNetV2ForImageClassification;c.MobileNetV2ImageProcessor;c.MobileNetV2Model;c.MobileNetV2PreTrainedModel;c.MobileNetV3FeatureExtractor;c.MobileNetV3ForImageClassification;c.MobileNetV3ImageProcessor;c.MobileNetV3Model;c.MobileNetV3PreTrainedModel;c.MobileNetV4FeatureExtractor;c.MobileNetV4ForImageClassification;c.MobileNetV4ImageProcessor;c.MobileNetV4Model;c.MobileNetV4PreTrainedModel;c.MobileViTFeatureExtractor;c.MobileViTForImageClassification;c.MobileViTImageProcessor;c.MobileViTModel;c.MobileViTPreTrainedModel;c.MobileViTV2ForImageClassification;c.MobileViTV2Model;c.MobileViTV2PreTrainedModel;c.ModelOutput;c.Moondream1ForConditionalGeneration;c.MptForCausalLM;c.MptModel;c.MptPreTrainedModel;c.MultiModalityCausalLM;c.MultiModalityPreTrainedModel;c.MusicgenForCausalLM;c.MusicgenForConditionalGeneration;c.MusicgenModel;c.MusicgenPreTrainedModel;c.NllbTokenizer;c.NoBadWordsLogitsProcessor;c.NoRepeatNGramLogitsProcessor;c.NomicBertModel;c.NomicBertPreTrainedModel;c.NougatImageProcessor;c.NougatTokenizer;c.OPTForCausalLM;c.OPTModel;c.OPTPreTrainedModel;c.ObjectDetectionPipeline;c.Olmo2ForCausalLM;c.Olmo2Model;c.Olmo2PreTrainedModel;c.OlmoForCausalLM;c.OlmoModel;c.OlmoPreTrainedModel;c.OpenELMForCausalLM;c.OpenELMModel;c.OpenELMPreTrainedModel;c.OwlViTFeatureExtractor;c.OwlViTForObjectDetection;c.OwlViTImageProcessor;c.OwlViTModel;c.OwlViTPreTrainedModel;c.OwlViTProcessor;c.Owlv2ForObjectDetection;c.Owlv2ImageProcessor;c.Owlv2Model;c.Owlv2PreTrainedModel;c.PaliGemmaForConditionalGeneration;c.PaliGemmaPreTrainedModel;c.PaliGemmaProcessor;c.PatchTSMixerForPrediction;c.PatchTSMixerModel;c.PatchTSMixerPreTrainedModel;c.PatchTSTForPrediction;c.PatchTSTModel;c.PatchTSTPreTrainedModel;c.Phi3ForCausalLM;c.Phi3Model;c.Phi3PreTrainedModel;c.PhiForCausalLM;c.PhiModel;c.PhiPreTrainedModel;c.Pipeline;var Ff=c.PreTrainedModel;c.PreTrainedTokenizer;c.PretrainedConfig;c.PretrainedMixin;c.Processor;c.PvtForImageClassification;c.PvtImageProcessor;c.PvtModel;c.PvtPreTrainedModel;c.PyAnnoteFeatureExtractor;c.PyAnnoteForAudioFrameClassification;c.PyAnnoteModel;c.PyAnnotePreTrainedModel;c.PyAnnoteProcessor;c.QuestionAnsweringModelOutput;c.QuestionAnsweringPipeline;c.Qwen2ForCausalLM;c.Qwen2Model;c.Qwen2PreTrainedModel;c.Qwen2Tokenizer;c.Qwen2VLForConditionalGeneration;c.Qwen2VLImageProcessor;c.Qwen2VLPreTrainedModel;c.Qwen2VLProcessor;c.RTDetrForObjectDetection;c.RTDetrImageProcessor;c.RTDetrModel;c.RTDetrObjectDetectionOutput;c.RTDetrPreTrainedModel;c.RawImage;c.RepetitionPenaltyLogitsProcessor;c.ResNetForImageClassification;c.ResNetModel;c.ResNetPreTrainedModel;c.RoFormerForMaskedLM;c.RoFormerForQuestionAnswering;c.RoFormerForSequenceClassification;c.RoFormerForTokenClassification;c.RoFormerModel;c.RoFormerPreTrainedModel;c.RoFormerTokenizer;c.RobertaForMaskedLM;c.RobertaForQuestionAnswering;c.RobertaForSequenceClassification;c.RobertaForTokenClassification;c.RobertaModel;c.RobertaPreTrainedModel;c.RobertaTokenizer;c.SamImageProcessor;c.SamImageSegmentationOutput;c.SamModel;c.SamPreTrainedModel;c.SamProcessor;c.SapiensForDepthEstimation;c.SapiensForNormalEstimation;c.SapiensForSemanticSegmentation;c.SapiensPreTrainedModel;c.SeamlessM4TFeatureExtractor;c.SegformerFeatureExtractor;c.SegformerForImageClassification;c.SegformerForSemanticSegmentation;c.SegformerImageProcessor;c.SegformerModel;c.SegformerPreTrainedModel;c.Seq2SeqLMOutput;c.SequenceClassifierOutput;c.SiglipImageProcessor;c.SiglipModel;c.SiglipPreTrainedModel;c.SiglipTextModel;c.SiglipTokenizer;c.SiglipVisionModel;c.SpeechT5FeatureExtractor;c.SpeechT5ForSpeechToText;c.SpeechT5ForTextToSpeech;c.SpeechT5HifiGan;c.SpeechT5Model;c.SpeechT5PreTrainedModel;c.SpeechT5Processor;c.SpeechT5Tokenizer;c.SqueezeBertForMaskedLM;c.SqueezeBertForQuestionAnswering;c.SqueezeBertForSequenceClassification;c.SqueezeBertModel;c.SqueezeBertPreTrainedModel;c.SqueezeBertTokenizer;c.StableLmForCausalLM;c.StableLmModel;c.StableLmPreTrainedModel;c.Starcoder2ForCausalLM;c.Starcoder2Model;c.Starcoder2PreTrainedModel;c.StoppingCriteria;c.StoppingCriteriaList;c.SummarizationPipeline;c.SuppressTokensAtBeginLogitsProcessor;c.Swin2SRForImageSuperResolution;c.Swin2SRImageProcessor;c.Swin2SRModel;c.Swin2SRPreTrainedModel;c.SwinForImageClassification;c.SwinModel;c.SwinPreTrainedModel;c.T5ForConditionalGeneration;c.T5Model;c.T5PreTrainedModel;c.T5Tokenizer;c.TableTransformerForObjectDetection;c.TableTransformerModel;c.TableTransformerObjectDetectionOutput;c.TableTransformerPreTrainedModel;c.TemperatureLogitsWarper;var Df=c.Tensor;c.Text2TextGenerationPipeline;c.TextClassificationPipeline;c.TextGenerationPipeline;c.TextStreamer;c.TextToAudioPipeline;c.TokenClassificationPipeline;c.TokenClassifierOutput;c.TokenizerModel;c.TopKLogitsWarper;c.TopPLogitsWarper;c.TrOCRForCausalLM;c.TrOCRPreTrainedModel;c.TranslationPipeline;c.UniSpeechForCTC;c.UniSpeechForSequenceClassification;c.UniSpeechModel;c.UniSpeechPreTrainedModel;c.UniSpeechSatForAudioFrameClassification;c.UniSpeechSatForCTC;c.UniSpeechSatForSequenceClassification;c.UniSpeechSatModel;c.UniSpeechSatPreTrainedModel;c.VLChatProcessor;c.VLMImageProcessor;c.ViTFeatureExtractor;c.ViTForImageClassification;c.ViTImageProcessor;c.ViTMAEModel;c.ViTMAEPreTrainedModel;c.ViTMSNForImageClassification;c.ViTMSNModel;c.ViTMSNPreTrainedModel;c.ViTModel;c.ViTPreTrainedModel;c.VisionEncoderDecoderModel;c.VitMatteForImageMatting;c.VitMatteImageProcessor;c.VitMattePreTrainedModel;c.VitPoseForPoseEstimation;c.VitPoseImageProcessor;c.VitPosePreTrainedModel;c.VitsModel;c.VitsModelOutput;c.VitsPreTrainedModel;c.VitsTokenizer;c.Wav2Vec2BertForCTC;c.Wav2Vec2BertForSequenceClassification;c.Wav2Vec2BertModel;c.Wav2Vec2BertPreTrainedModel;c.Wav2Vec2CTCTokenizer;c.Wav2Vec2FeatureExtractor;c.Wav2Vec2ForAudioFrameClassification;c.Wav2Vec2ForCTC;c.Wav2Vec2ForSequenceClassification;c.Wav2Vec2Model;c.Wav2Vec2PreTrainedModel;c.Wav2Vec2ProcessorWithLM;c.WavLMForAudioFrameClassification;c.WavLMForCTC;c.WavLMForSequenceClassification;c.WavLMForXVector;c.WavLMModel;c.WavLMPreTrainedModel;c.WeSpeakerFeatureExtractor;c.WeSpeakerResNetModel;c.WeSpeakerResNetPreTrainedModel;c.WhisperFeatureExtractor;c.WhisperForConditionalGeneration;c.WhisperModel;c.WhisperPreTrainedModel;c.WhisperProcessor;c.WhisperTextStreamer;c.WhisperTimeStampLogitsProcessor;c.WhisperTokenizer;c.XLMForQuestionAnswering;c.XLMForSequenceClassification;c.XLMForTokenClassification;c.XLMModel;c.XLMPreTrainedModel;c.XLMRobertaForMaskedLM;c.XLMRobertaForQuestionAnswering;c.XLMRobertaForSequenceClassification;c.XLMRobertaForTokenClassification;c.XLMRobertaModel;c.XLMRobertaPreTrainedModel;c.XLMRobertaTokenizer;c.XLMTokenizer;c.XLMWithLMHeadModel;c.XVectorOutput;c.YolosFeatureExtractor;c.YolosForObjectDetection;c.YolosImageProcessor;c.YolosModel;c.YolosObjectDetectionOutput;c.YolosPreTrainedModel;c.ZeroShotAudioClassificationPipeline;c.ZeroShotClassificationPipeline;c.ZeroShotImageClassificationPipeline;c.ZeroShotObjectDetectionPipeline;c.bankers_round;c.cat;c.cos_sim;c.dot;c.dynamic_time_warping;c.env;c.full;c.full_like;c.getKeyValueShapes;c.hamming;c.hanning;c.interpolate;c.interpolate_4d;c.interpolate_data;c.is_chinese_char;c.layer_norm;c.load_image;c.log_softmax;c.magnitude;c.matmul;c.max;c.mean;c.mean_pooling;c.medianFilter;c.mel_filter_bank;c.min;c.ones;c.ones_like;c.permute;c.permute_data;c.pipeline;c.quantize_embeddings;c.read_audio;c.rfft;c.round;c.softmax;c.spectrogram;c.stack;c.std_mean;c.topk;c.window_function;c.zeros;c.zeros_like;const Lf=" Uhm, now being the one to say, I know the worst of you and I've been directly affected by people like you, but it's a clean slate with me, buddy. You know, like that's really powerful in and of itself.",zf=[{word:"uhm",duration:.36,codes:[447,223,967,301,965,827,393,908,764,1167,711,1222,324,1318,806,498,1198,1127,1178,916,1234,1411,1428,706,427,1605,1578]},{word:"now",duration:.36,codes:[1049,327,385,1070,732,1480,450,1025,1469,174,1013,1710,1674,775,771,251,778,1400,897,1487,366,441,1e3,393,271,1e3,768]},{word:"being",duration:.27,codes:[926,406,1457,437,1231,672,1785,521,1179,1559,198,1086,733,122,1344,845,348,1389,470,1773]},{word:"the",duration:.08,codes:[1775,562,768,1222,768,963]},{word:"one",duration:.21,codes:[1757,744,144,1610,655,616,1317,225,1325,913,1342,992,1018,80,1777,883]},{word:"to",duration:.08,codes:[487,1363,1682,1426,655,1483]},{word:"say",duration:.27,codes:[1644,1804,731,273,1592,731,1523,1404,984,1207,430,1132,1123,768,1116,829,1082,1095,440,1162]},{word:"i",duration:.33,codes:[1330,335,1162,1155,308,1162,1150,1481,612,674,712,1745,1188,1787,1135,1275,1237,1143,408,1063,393,927,1298,132,1686]},{word:"know",duration:.27,codes:[983,1677,586,1528,1435,835,1396,706,987,22,1172,218,1404,1001,521,1389,775,1416,877,120]},{word:"the",duration:.16,codes:[916,1756,513,1245,1392,89,1266,12,1045,1075,904,35]},{word:"worst",duration:.32,codes:[1607,174,1231,144,932,490,771,1504,798,674,364,80,1314,1636,449,1704,713,1795,968,1527,1302,1529,1176,795]},{word:"of",duration:.12,codes:[1193,1205,390,1128,1091,883,322,377,1070]},{word:"you",duration:.17,codes:[1016,1332,926,281,927,1368,1687,918,67,1638,1317,1265,1770]},{word:"and",duration:.28,codes:[1129,1633,1373,1207,405,879,1030,1253,1071,612,724,1770,665,1046,1351,1450,1541,1384,111,1477,284]},{word:"ive",duration:.35,codes:[674,266,89,1333,1183,1526,1143,883,1135,732,827,1119,594,1261,1024,1347,92,1392,825,1710,1289,1598,1070,1525,1442,555]},{word:"been",duration:.17,codes:[1461,194,337,1128,188,892,848,1280,959,754,231,649,1304]},{word:"directly",duration:.87,codes:[1030,353,570,1331,470,1832,1362,1809,1383,101,325,1557,1242,1512,180,227,1242,643,209,464,171,1219,174,1723,734,118,1269,643,209,187,612,1231,68,567,1242,505,319,1268,794,678,40,1286,470,1454,199,965,188,300,1234,1125,794,1289,1224,257,469,1121,101,823,1769,1683,95,255,59,67,832]},{word:"affected",duration:.44,codes:[510,873,787,1228,771,1428,501,751,696,258,845,1818,1112,498,1111,985,1073,832,1427,168,163,447,119,567,1626,1820,903,635,1060,10,1632,35,1635]},{word:"by",duration:.19,codes:[144,144,460,185,1112,1044,498,1192,656,1333,1001,1186,1186,454]},{word:"people",duration:.48,codes:[1260,747,351,526,612,1151,1262,1791,344,1752,1547,930,1302,1703,1289,92,1407,1482,508,1431,355,1696,337,199,1157,223,464,568,845,411,826,718,1786,545,712,580]},{word:"like",duration:.32,codes:[630,532,526,607,526,839,1305,660,459,339,717,1178,1148,687,149,1390,229,199,513,712,1451,731,582,1551]},{word:"you",duration:.21,codes:[1389,954,1781,1047,1236,930,809,1621,1268,384,242,587,869,816,1680,405]},{word:"but",duration:.59,codes:[1089,1590,908,80,594,1046,1706,1025,1150,405,548,893,1285,464,301,939,643,23,285,161,209,453,72,167,417,244,151,643,391,199,651,1023,337,1010,54,331,1167,756,388,934,1060,18,1624,1060]},{word:"its",duration:.16,codes:[1102,183,1199,1258,1285,35,659,180,426,1587,1733,942]},{word:"a",duration:.04,codes:[791,1012,818]},{word:"clean",duration:.61,codes:[1819,976,163,447,316,223,763,457,1208,1808,1697,1162,1660,1833,1054,1734,1121,1309,1643,924,1677,1548,869,1268,223,674,111,792,1670,912,174,1554,90,80,1563,1621,1698,1544,992,988,175,793,1661,1026,80,1761]},{word:"slate",duration:.4,codes:[1802,322,1689,1577,1302,1552,1529,1722,1580,582,1642,1529,1020,582,1538,970,437,1141,1477,988,335,1611,922,1558,1120,1189,423,188,171,562]},{word:"with",duration:.15,codes:[963,1347,1274,747,1230,712,1408,1290,957,1279,258]},{word:"me",duration:.09,codes:[638,1058,174,1452,1038,894,1571]},{word:"buddy",duration:.32,codes:[1003,130,1341,938,40,804,167,89,1456,1189,1155,1171,1434,1077,1029,1455,1622,1037,163,1411,1165,1463,837,1202]},{word:"you",duration:.36,codes:[1354,1165,615,1588,1192,1445,1033,982,401,1079,684,1570,266,31,420,163,893,845,905,1827,1804,153,627,243,1179,298,1147]},{word:"know",duration:.19,codes:[163,1542,1366,698,1753,206,916,1499,245,665,600,894,587,1741]},{word:"like",duration:.24,codes:[1106,1280,1062,1304,945,809,598,104,1001,822,965,189,693,1810,1293,199,1277,44]},{word:"thats",duration:.24,codes:[121,1789,1443,370,1154,393,1178,1200,1264,424,1391,381,978,1346,704,1808,1579,1492]},{word:"really",duration:.56,codes:[1177,1761,1723,1360,1413,830,551,193,59,332,598,734,1684,1802,60,1590,353,89,1636,1396,893,143,455,1501,435,1082,621,1593,677,474,971,1513,913,828,1381,1148,1798,1186,1443,38,335,883]},{word:"powerful",duration:.63,codes:[1773,458,1070,964,826,1220,1012,1738,1125,669,490,1169,922,958,1204,489,1001,886,1045,675,1471,1652,732,698,1124,480,897,1484,1028,35,594,1465,505,1669,436,851,1288,31,1501,1187,394,909,1541,1793,1720,922,840]},{word:"in",duration:.16,codes:[1317,523,630,1343,1187,719,907,636,111,1524,188,1382]},{word:"and",duration:.13,codes:[1074,922,1280,1496,1050,832,133,1435,1049,1774]},{word:"of",duration:.12,codes:[960,1052,1192,1303,1112,970,417,60,1155]},{word:"itself",duration:.47,codes:[1682,1209,1410,513,1222,861,167,406,1551,582,634,1529,786,1363,1578,1739,873,424,1041,1328,955,1110,1490,1424,1199,988,1162,1133,1193,978,470,832,963,1251,733]}],Bf="en";var Rf={text:Lf,words:zf,language:Bf};const Nf="So we have five words here, um, all to do with a plumber and water pipes. Now the first word they talked about that there was water leaking everywhere.",jf=[{word:"so",duration:.15,codes:[391,1319,1478,895,1580,533,166,1015,1169,1186,380]},{word:"we",duration:.12,codes:[1403,1150,80,1187,1230,529,182,398,853]},{word:"have",duration:.17,codes:[243,1049,759,1477,371,1158,422,1516,203,449,1351,1546,1130]},{word:"five",duration:.51,codes:[1241,719,239,886,1795,1160,1412,1638,943,1588,497,1162,106,1185,1183,477,840,164,581,775,474,518,361,764,628,153,234,125,584,1029,149,276,1243,1800,1468,1728,1439,1772]},{word:"words",duration:.45,codes:[1455,1366,1734,920,703,111,1497,1521,302,111,128,747,687,747,104,66,208,1727,545,69,684,380,1666,1368,183,145,1771,1613,1807,1238,1549,1393,1027,736]},{word:"here",duration:.36,codes:[117,399,1325,1447,1226,1761,778,1120,1764,47,348,1416,921,50,372,437,104,771,218,982,162,754,997,162,912,907,245]},{word:"um",duration:.39,codes:[1234,511,81,1270,1475,841,595,64,1268,1461,680,1320,573,818,764,1068,637,684,402,1222,877,537,1103,779,300,1629,177,529,1672]},{word:"all",duration:.41,codes:[653,1811,131,516,1525,727,1338,1749,758,1097,173,116,102,660,693,1177,159,799,221,1187,984,152,95,942,1046,236,756,1042,1159,1159,1297]},{word:"to",duration:.24,codes:[577,1542,1356,1122,58,47,1759,566,1478,1814,599,276,1403,62,822,1568,95,691]},{word:"do",duration:.23,codes:[65,1619,1606,1584,251,85,1802,1250,350,714,1814,631,510,1463,307,202,50]},{word:"with",duration:.45,codes:[853,893,213,4,143,120,1141,38,1637,182,389,747,890,1637,1618,843,145,1445,381,234,1274,228,1484,374,245,1131,254,1062,844,1635,1491,1795,345,891]},{word:"a",duration:.19,codes:[1693,1462,874,1511,1408,1284,450,274,1466,1682,1173,1062,1073,1675]},{word:"plumber",duration:.6,codes:[935,1389,1178,1803,1006,1419,1614,1495,1711,1779,1423,874,1407,1626,1351,1748,1145,1768,555,1389,252,1274,1356,717,2,1147,1076,1333,234,23,1453,704,143,1243,1174,1483,1247,157,37,393,988,1141,206,1052,818]},{word:"and",duration:.43,codes:[329,1801,926,756,1469,1040,1313,516,1166,1129,1369,263,1144,1026,318,1809,803,364,1646,383,1074,109,113,775,1415,863,1352,1369,1796,1385,1765,1618]},{word:"water",duration:.48,codes:[315,1075,1675,86,970,679,1491,1635,1833,60,1619,1595,414,126,908,425,277,1159,798,186,1179,321,349,497,1611,157,1480,1502,1075,1162,993,74,520,113,1731,1314]},{word:"pipes",duration:.53,codes:[1415,150,1705,1813,401,1456,1325,1671,1820,1170,1489,1328,931,410,359,836,1253,1074,1192,1283,1055,298,1711,937,1375,1144,1321,1672,630,1623,1828,1041,230,519,1139,749,1638,1139,1641,1393]},{word:"now",duration:.63,codes:[231,1688,788,333,1830,938,1461,1668,1355,1666,1412,1701,1705,1088,1746,1397,1002,1793,1259,1459,1803,927,1790,1720,985,1803,1259,1400,1803,927,1638,1438,1411,1010,933,851,1764,1493,485,74,1794,1181,208,1492,1046,1193,774]},{word:"the",duration:.08,codes:[1657,1022,76,1116,1272,95]},{word:"first",duration:.49,codes:[1730,1823,1447,1217,1751,1098,1287,1795,1342,1711,1735,788,1383,1532,1252,173,1173,661,695,412,1139,913,113,1668,1437,848,1364,962,132,719,1018,863,1379,1535,696,1486,715]},{word:"word",duration:.43,codes:[1364,1287,1698,1100,526,443,199,1644,302,98,1625,1025,682,629,307,170,671,254,1218,574,565,788,993,427,626,1398,738,587,1755,1453,1617,406]},{word:"they",duration:.2,codes:[969,1400,1491,486,1693,426,1287,569,1168,550,1563,278,79,1718,1321]},{word:"talked",duration:.4,codes:[286,1023,673,1419,1776,599,1041,1629,1125,1671,1687,1320,1473,1260,1254,297,1004,1611,840,969,1759,772,1556,1809,869,1704,986,1450,335,1477]},{word:"about",duration:.24,codes:[839,376,1553,301,426,1346,1671,215,1194,971,25,838,152,1501,1665,1757,1092,710]},{word:"that",duration:.12,codes:[436,1166,53,1153,324,576,1689,1717,566]},{word:"there",duration:.16,codes:[1108,1338,1634,903,1355,228,813,881,102,396,1415,518]},{word:"was",duration:.12,codes:[793,87,1252,911,83,1793,634,183,124]},{word:"water",duration:.59,codes:[110,1301,1639,520,1219,509,1662,748,363,224,1753,877,1802,1185,500,1148,1435,128,951,942,531,1075,324,1402,1159,1202,711,218,901,441,571,1317,1753,1722,1001,157,1137,254,607,808,125,661,51,798]},{word:"leaking",duration:.96,codes:[1171,1743,1260,1331,91,1118,1782,555,1385,505,121,1234,998,1360,836,214,1048,423,13,439,686,303,1352,864,727,107,1038,1767,479,1685,806,1639,719,125,365,1237,1732,298,1471,485,1141,1734,1803,971,1798,691,1648,1166,1082,1535,1645,1154,388,11,110,890,449,736,276,1103,714,407,1749,243,1694,479,426,1368,1348,700,562,519]},{word:"everywhere",duration:1,codes:[4,952,856,755,1686,372,570,1816,1675,227,1675,1145,674,1419,933,346,956,1739,1519,192,1778,346,1106,1174,1403,175,1491,1758,1451,1777,1411,1773,1716,1407,1743,1186,1031,902,1174,7,231,737,1106,1189,592,481,1659,1339,1155,110,384,583,1656,626,279,1172,326,560,326,755,1097,1105,1203,675,208,1002,1158,1204,1132,1063,595,1102,1216,855,1229]}],Uf="en";var Wf={text:Nf,words:jf,language:Uf};const Vf="The overall package from just two people is pretty remarkable. Sure I have some critiques about some of the gameplay aspects, but it's still really enjoyable and it looks lovely.",Gf=[{word:"the",duration:.08,codes:[257,740,636,913,788,1703]},{word:"overall",duration:.36,codes:[127,201,191,774,700,532,1056,557,798,298,1741,747,1662,1617,1702,1527,368,1588,1049,1008,1625,747,1576,728,1019,1696,1765]},{word:"package",duration:.56,codes:[935,584,1319,627,1016,1491,1344,1117,1526,1040,239,1435,951,498,723,1180,535,789,1649,1637,78,465,1668,901,595,1675,117,1009,1667,320,840,79,507,1762,1508,1228,1768,802,1450,1457,232,639]},{word:"from",duration:.19,codes:[604,782,1682,872,1532,1600,1036,1761,647,1554,1371,653,1595,950]},{word:"just",duration:.25,codes:[1782,1670,317,786,1748,631,599,1155,1364,1524,36,1591,889,1535,541,440,1532,50,870]},{word:"two",duration:.24,codes:[1681,1510,673,799,805,1342,330,519,62,640,1138,565,1552,1497,1552,572,1715,1732]},{word:"people",duration:.39,codes:[593,274,136,740,691,633,1484,1061,1138,1485,344,428,397,1562,645,917,1035,1449,1669,487,442,1484,1329,1832,1704,600,761,653,269]},{word:"is",duration:.16,codes:[566,583,1755,646,1337,709,802,1008,485,1583,652,10]},{word:"pretty",duration:.32,codes:[1818,1747,692,733,1010,534,406,1697,1053,1521,1355,1274,816,1398,211,1218,817,1472,1703,686,13,822,445,1068]},{word:"remarkable",duration:.68,codes:[230,1048,1705,355,706,1149,1535,1787,1356,1396,835,1583,486,1249,286,937,1076,1150,614,42,1058,705,681,798,934,490,514,1399,572,1446,1703,1346,1040,1426,1304,664,171,1530,625,64,1708,1830,1030,443,1509,1063,1605,1785,721,1440,923]},{word:"sure",duration:.36,codes:[792,1780,923,1640,265,261,1525,567,1491,1250,1730,362,919,1766,543,1,333,113,970,252,1606,133,302,1810,1046,1190,1675]},{word:"i",duration:.08,codes:[123,439,1074,705,1799,637]},{word:"have",duration:.16,codes:[1509,599,518,1170,552,1029,1267,864,419,143,1061,0]},{word:"some",duration:.16,codes:[619,400,1270,62,1370,1832,917,1661,167,269,1366,1508]},{word:"critiques",duration:.6,codes:[559,584,1163,1129,1313,1728,721,1146,1093,577,928,27,630,1080,1346,1337,320,1382,1175,1682,1556,990,1683,860,1721,110,786,376,1085,756,1523,234,1334,1506,1578,659,612,1108,1466,1647,308,1470,746,556,1061]},{word:"about",duration:.29,codes:[26,1649,545,1367,1263,1728,450,859,1434,497,1220,1285,179,755,1154,779,179,1229,1213,922,1774,1408]},{word:"some",duration:.23,codes:[986,28,1649,778,858,1519,1,18,26,1042,1174,1309,1499,1712,1692,1516,1574]},{word:"of",duration:.07,codes:[197,716,1039,1662,64]},{word:"the",duration:.08,codes:[1811,1568,569,886,1025,1374]},{word:"gameplay",duration:.48,codes:[1269,1092,933,1362,1762,1700,1675,215,781,1086,461,838,1022,759,649,1416,1004,551,909,787,343,830,1391,1040,1622,1779,1360,1231,1187,1317,76,997,989,978,737,189]},{word:"aspects",duration:.56,codes:[1423,797,1316,1222,147,719,1347,386,1390,1558,154,440,634,592,1097,1718,712,763,1118,1721,1311,868,580,362,1435,868,247,221,886,1145,1274,1284,457,1043,1459,1818,62,599,1035,62,1649,778]},{word:"but",duration:.2,codes:[780,1825,1681,1007,861,710,702,939,1669,1491,613,1739,823,1469,648]},{word:"its",duration:.09,codes:[92,688,1623,962,1670,527,599]},{word:"still",duration:.27,codes:[636,10,1217,344,713,957,823,154,1649,1286,508,214,1760,1250,456,1352,1368,921,615,5]},{word:"really",duration:.36,codes:[55,420,1008,1659,27,644,1266,617,761,1712,109,1465,1587,503,1541,619,197,1019,817,269,377,362,1381,507,1488,4,1695]},{word:"enjoyable",duration:.49,codes:[678,501,864,319,288,1472,1341,686,562,1463,619,1563,471,911,730,1811,1006,520,861,1274,125,1431,638,621,153,876,1770,437,987,1653,1109,898,1285,80,593,1709,843]},{word:"and",duration:.15,codes:[1285,987,303,1037,730,1164,502,120,1737,1655,1318]},{word:"it",duration:.09,codes:[848,1366,395,1601,1513,593,1302]},{word:"looks",duration:.27,codes:[1281,1266,1755,572,248,1751,1257,695,1380,457,659,585,1315,1105,1776,736,24,736,654,1027]},{word:"lovely",duration:.56,codes:[634,596,1766,1556,1306,1285,1481,1721,1123,438,1246,1251,795,659,1381,1658,217,1772,562,952,107,1129,1112,467,550,1079,840,1615,1469,1380,168,917,836,1827,437,583,67,595,1087,1646,1493,1677]}],Kf="en";var Hf={text:Vf,words:Gf,language:Kf};const qf="Difficult action game. While you have your melee attacks, the majority of combat takes place using your guns. From long rifles to shotguns and my trusty magnum. There is an emphasis on cooperative play.",Xf=[{word:"difficult",duration:.44,codes:[1567,714,1238,243,810,104,1826,1081,865,1627,1176,1535,1238,1832,346,647,36,631,1750,1273,1806,861,1429,1332,1633,326,1530,1661,503,1597,326,733,1715]},{word:"action",duration:.48,codes:[1319,1792,1238,939,1765,1282,847,621,1147,595,514,1180,1235,1438,1057,1472,1489,1822,1092,1178,796,1511,290,1018,687,290,1403,253,1755,1107,780,1376,341,1614,176,317]},{word:"game",duration:.4,codes:[1617,703,1617,662,101,1530,1678,782,1829,146,1175,1771,422,370,1079,1069,282,996,1134,814,430,296,1534,1742,947,1285,1710,1465,1152,640]},{word:"while",duration:.32,codes:[1506,1765,1451,1590,1637,1390,727,1010,766,1007,1585,1341,48,600,1715,1226,887,840,310,362,972,1765,67,1572]},{word:"you",duration:.11,codes:[1581,527,1513,1267,774,108,29,1366]},{word:"have",duration:.21,codes:[1591,434,949,1407,117,907,874,1105,1132,498,1161,13,742,1528,1653,1710]},{word:"your",duration:.15,codes:[1337,990,234,831,4,616,1820,1083,1710,1564,529]},{word:"melee",duration:.33,codes:[75,682,311,455,786,834,804,292,492,947,474,1720,142,1628,614,758,789,117,1372,402,896,1537,128,927,1108]},{word:"attacks",duration:.56,codes:[1218,218,907,1005,1793,1520,1694,458,1428,276,315,639,231,1455,347,1447,1361,370,1224,498,1509,499,588,1188,993,775,1004,1591,716,999,1548,1464,1720,681,1043,639,639,543,592,546,356,1217]},{word:"the",duration:.24,codes:[654,335,1524,350,493,1644,1724,591,799,1176,1023,694,1585,806,1344,596,503,1557]},{word:"majority",duration:.52,codes:[1416,240,62,443,1660,549,160,1729,567,32,1703,1553,1337,45,631,335,184,395,576,1068,759,548,587,427,1455,775,673,983,1791,647,398,1595,1664,592,1310,356,440,495,812]},{word:"of",duration:.11,codes:[1415,455,1452,821,1300,1048,1485,1626]},{word:"combat",duration:.44,codes:[1588,1649,861,727,1671,609,847,1004,0,1535,1801,1100,1494,1178,1224,623,1620,742,1507,1794,932,1634,1285,1192,764,1245,587,521,55,1230,1532,1469,1758]},{word:"takes",duration:.32,codes:[1408,681,1385,1737,858,46,1649,1091,1320,1015,756,269,787,230,1777,911,91,1152,1412,1710,232,46,1337,782]},{word:"place",duration:.4,codes:[1496,1821,1681,1725,1324,1088,1668,1568,1801,1275,1776,741,621,1749,901,829,640,940,1464,541,1008,1747,631,1653,7,202,416,198,1337,202]},{word:"using",duration:.4,codes:[290,1459,778,1819,1689,175,1569,182,1512,361,778,716,231,1446,1240,1763,1734,189,631,654,440,1280,1439,986,753,1387,805,338,1606,1679]},{word:"your",duration:.16,codes:[1520,1250,1440,47,1374,1731,963,1368,1426,1506,1545,1730]},{word:"guns",duration:.48,codes:[450,1553,1570,651,1648,899,971,1573,1684,28,107,1744,236,1067,1312,412,1110,1112,1014,1241,1726,875,1830,1792,1219,1565,1534,751,1726,1598,1600,320,26,1018,1337,1270]},{word:"from",duration:.32,codes:[372,1238,6,1436,1654,1637,799,1244,1525,1285,1390,1657,1790,1061,634,493,972,977,1036,158,540,749,317,1552]},{word:"long",duration:.24,codes:[875,529,710,63,1822,158,1647,809,1022,1155,774,1118,63,669,1069,1513,1469,47]},{word:"rifles",duration:.59,codes:[1007,1650,1015,954,843,1075,803,1078,839,1382,424,1674,800,657,1487,382,95,41,979,1619,1485,362,1646,1400,333,1761,1827,806,389,1562,789,481,1606,647,1597,1340,593,1627,1401,1791,202,368,213,356]},{word:"to",duration:.12,codes:[1485,6,1817,1623,440,631,1366,547,1479]},{word:"shotguns",duration:.64,codes:[987,62,154,790,290,1161,430,543,1332,24,1270,1700,412,462,1629,595,260,1819,1435,1828,1752,1380,1803,1465,1321,1300,1330,1459,547,913,719,303,1811,595,716,344,909,784,203,1269,1394,734,415,1633,233,202,1649,409]},{word:"and",duration:.36,codes:[858,416,328,1793,1390,957,1262,1601,1628,1346,1466,764,621,1459,844,158,626,827,1466,1110,18,1540,1515,615,593,1627,1145]},{word:"my",duration:.21,codes:[1445,481,1035,1593,1718,1464,1808,644,1344,1381,466,936,123,604,1545,1340]},{word:"trusty",duration:.44,codes:[1583,572,1749,1114,1462,308,1332,471,863,1410,993,1524,1100,1758,958,1453,768,1638,1625,1002,117,1364,213,631,202,454,957,820,1748,822,1335,295,1039]},{word:"magnum",duration:.48,codes:[1285,1679,1626,1257,694,1339,678,1815,271,1656,535,607,383,550,1372,769,815,1763,1525,513,1637,1782,1439,539,867,297,1476,1620,65,1361,804,577,1700,91,1583,1745]},{word:"there",duration:.36,codes:[761,1532,32,1828,950,761,1037,1293,1023,1510,1657,1821,1284,603,1669,634,757,940,782,955,18,296,1636,455,108,1629,333]},{word:"is",duration:.23,codes:[1571,1517,399,863,1649,302,103,213,1409,1733,356,736,104,184,1778,198,298]},{word:"an",duration:.12,codes:[654,276,1462,104,1388,815,736,889,1069]},{word:"emphasis",duration:.51,codes:[695,678,319,262,1396,583,473,1728,1706,865,1616,1270,1078,1487,911,319,1586,335,519,507,356,26,1,937,1833,335,909,990,132,616,1814,1,1563,38,276,368,7,335]},{word:"on",duration:.24,codes:[183,844,1477,1720,1751,1302,1743,1435,1789,997,644,1828,1253,688,1672,473,835,26]},{word:"cooperative",duration:.61,codes:[856,22,1425,1461,901,357,1174,1175,1691,1661,626,1776,1286,429,1702,757,1702,730,1015,86,321,1628,763,1792,1760,1499,1053,1825,1661,1364,1553,1609,409,315,166,1027,1295,927,1231,113,1513,1747,1753,1617,1614,274]},{word:"play",duration:.32,codes:[1669,1764,1298,1411,1487,454,1035,1814,1295,973,787,834,798,617,1720,1331,768,252,1757,318,695,884,775,631]}],Qf="en";var Yf={text:qf,words:Xf,language:Qf};const Jf="Uhm, your way of celebrating your mum, but also I think, you know, spreading awareness, which is so important. And so, you know, I think you've taken.",Zf=[{word:"uhm",duration:.31,codes:[119,548,926,164,142,214,979,142,1497,498,616,1160,359,1812,571,1336,498,456,1741,1708,1371,1646,878]},{word:"your",duration:.49,codes:[615,1470,853,1607,685,1640,1717,1626,1052,1467,1536,845,257,180,1657,1586,659,54,666,235,1747,1405,935,714,1665,1618,340,286,211,1485,1018,83,280,1650,1278,569,439]},{word:"way",duration:.2,codes:[1609,1701,395,748,1696,1001,280,1517,306,803,499,373,947,179,1449]},{word:"of",duration:.08,codes:[232,472,796,825,1299,1225]},{word:"celebrating",duration:.84,codes:[1650,821,117,1436,330,687,979,407,886,596,430,1139,253,69,777,370,1072,755,81,222,1804,1216,1506,945,1013,520,179,1272,683,1812,564,1570,1664,959,791,306,413,966,252,326,349,492,570,948,789,24,1129,1407,781,99,1633,522,63,190,753,683,368,644,1679,1168,1295,788,1793]},{word:"your",duration:.35,codes:[1350,4,515,1520,317,1573,1383,615,815,896,1157,1684,392,641,733,1538,1725,530,154,1785,297,463,1743,407,623,1371]},{word:"mum",duration:.21,codes:[1009,519,211,98,1101,364,106,429,827,1143,367,221,211,1709,1024,515]},{word:"but",duration:.16,codes:[183,1069,539,1796,1151,1676,525,1127,366,618,1695,127]},{word:"also",duration:.28,codes:[850,393,413,1673,868,291,1673,1344,462,385,1073,1398,906,592,519,448,592,348,1258,711,115]},{word:"i",duration:.16,codes:[539,1519,390,389,441,413,715,390,410,294,726,269]},{word:"think",duration:.32,codes:[1791,1781,1619,1393,1649,1741,1535,1703,1721,1134,1435,112,1660,232,98,654,593,485,593,368,530,1584,379,338]},{word:"you",duration:.4,codes:[379,387,1767,543,1410,546,1117,614,65,793,414,284,396,538,1039,226,1277,1632,1152,1796,888,953,888,464,1762,1446,10,876,184,1009]},{word:"know",duration:.11,codes:[473,623,383,352,1814,147,1289,164]},{word:"spreading",duration:.44,codes:[482,796,134,1387,232,1310,308,330,400,162,535,197,1039,274,1442,1701,1138,723,39,280,410,412,160,645,225,1519,581,815,415,835,884,312,1779]},{word:"awareness",duration:.48,codes:[173,988,93,1727,374,1442,312,436,482,1752,373,1727,173,1706,522,909,543,590,773,210,1057,215,1020,623,1379,147,1427,1182,1816,1221,877,1626,178,175,780,985]},{word:"which",duration:.19,codes:[1214,1031,698,1820,547,211,605,1152,442,837,1774,232,522,876]},{word:"is",duration:.16,codes:[1649,581,211,884,110,1530,1217,1409,4,1027,1624,849]},{word:"so",duration:.53,codes:[1337,1034,656,1410,979,790,1436,471,1403,750,782,1697,1748,1380,288,668,17,585,866,457,975,534,401,1570,401,1474,1762,1352,1545,178,362,356,206,276,263,356,253,492,441,1101]},{word:"important",duration:.64,codes:[474,211,1797,626,1396,571,593,1160,530,1624,317,1568,835,1570,1327,892,1208,1463,1577,895,1378,897,1781,82,539,1748,238,416,390,1732,306,312,1832,445,338,418,60,1502,1808,503,1334,1581,1554,1781,506,1519,1681,269]},{word:"and",duration:.24,codes:[989,1121,932,1393,1103,1164,1185,32,1459,671,874,872,1056,539,1626,1091,539,1569]},{word:"so",duration:.16,codes:[1620,1594,10,599,746,172,1175,980,1317,1402,115,148]},{word:"you",duration:.63,codes:[1094,248,1384,393,611,522,425,947,326,930,503,1215,1813,99,284,1070,447,1168,732,1120,1749,900,743,1684,1360,1225,490,743,1268,673,793,490,620,1279,469,649,717,986,669,174,555,284,139,1479,1463,79,214]},{word:"know",duration:.08,codes:[368,471,112,1077,299,472]},{word:"i",duration:.08,codes:[1170,210,1526,499,615,1287]},{word:"think",duration:.17,codes:[1654,1709,1057,1817,1012,1076,1470,768,539,778,1698,1507,888]},{word:"youve",duration:.16,codes:[1797,62,605,1800,576,1444,434,952,485,512,1751,691]},{word:"taken",duration:.39,codes:[1806,822,537,700,999,1462,791,159,1477,558,291,1797,901,1336,599,1408,1555,707,1677,919,1411,1381,512,525,1583,847,78,1596,810]}],e_="en";var t_={text:Jf,words:Zf,language:e_};const r_="Corrosion by running water opens a window to a subterranean world. Jijin Cave covers an area of more than 700,000 square meters, which is equivalent to 100 football fields.",s_=[{word:"corrosion",duration:.56,codes:[1231,1183,393,1069,773,1394,217,200,211,783,1616,814,1680,1381,1372,648,211,433,57,679,375,1496,1149,328,289,748,300,1692,1286,318,1633,463,596,1436,454,1417,1414,593,848,1422,738,1412]},{word:"by",duration:.31,codes:[1526,1674,1411,1048,1829,1473,804,1355,1453,1396,1390,78,1722,1113,1206,1063,703,609,1129,1373,983,271,668]},{word:"running",duration:.33,codes:[514,239,304,1008,673,850,1506,1315,768,280,1403,206,112,1336,1436,1801,52,46,200,503,1773,1305,1663,348,312]},{word:"water",duration:.44,codes:[742,1782,1176,1352,1597,1365,662,1614,1281,90,1692,843,397,891,1219,1347,644,1415,1816,1581,1153,1702,1139,357,175,780,1372,1361,1063,876,1160,1795,1013]},{word:"opens",duration:.71,codes:[1404,1680,1745,1125,1357,1774,1126,1392,1314,758,5,1738,516,1199,1393,1758,1330,1212,550,1488,384,439,1712,587,389,1768,32,59,795,1319,1331,349,1427,1124,1278,753,192,539,1818,1228,1732,439,1472,1215,473,211,1800,790,143,1376,202,6,430]},{word:"a",duration:.13,codes:[996,1245,1790,1010,669,1741,1431,997,225,1005]},{word:"window",duration:.55,codes:[239,92,539,1446,1786,909,633,1727,150,1244,385,1781,1535,55,539,1240,1310,966,640,1590,230,455,1597,755,97,200,719,144,952,1546,1605,1125,1222,892,1400,1368,1077,1393,1427,1058,1738]},{word:"to",duration:.2,codes:[1830,653,1638,1227,355,852,566,559,1447,206,1300,989,1823,1052,1456]},{word:"a",duration:.09,codes:[703,1612,810,657,27,102,1261]},{word:"subterranean",duration:.91,codes:[1315,882,276,183,769,452,493,471,844,454,596,870,889,592,1018,596,328,1358,626,179,95,214,1536,1827,1239,1775,32,850,1145,1732,1215,986,187,1360,1498,206,1139,1769,874,148,1104,877,487,1506,414,359,131,569,1039,876,637,423,63,844,316,264,183,1401,1734,1489,1013,263,1485,1488,1707,363,987,1741]},{word:"world",duration:.45,codes:[1813,738,343,859,1006,406,893,716,1762,909,973,1684,834,1078,1813,1013,1320,1435,1663,1282,361,1584,19,1454,1708,1489,1454,1647,1505,1312,1225,1433,1741,581]},{word:"jijin",duration:1.05,codes:[1382,927,1426,744,1735,1525,1294,1699,1684,1414,1543,1025,1478,1543,1301,1428,1655,1433,1479,1248,805,1273,17,862,899,1440,1293,1348,1684,1010,1231,1348,1007,1231,957,1293,1236,869,810,585,964,954,1601,670,861,1601,729,1479,1348,870,434,117,614,398,395,764,343,200,863,627,91,691,1727,943,769,502,599,1781,367,968,217,335,1674,500,1121,150,1345,1742,850]},{word:"cave",duration:.64,codes:[1799,1084,1488,1034,987,1491,1486,850,686,1352,944,596,1671,1451,1393,1404,829,512,402,801,1370,822,518,1713,328,877,333,1346,529,938,1285,1708,1528,1490,416,1639,1014,231,1581,1666,1432,1406,1496,1422,1811,1012,1399,1256]},{word:"covers",duration:.52,codes:[535,1344,958,1259,1285,1305,1465,727,1390,1767,958,658,1700,1651,910,570,146,222,825,1098,1789,314,1715,506,1710,532,688,1563,588,117,1397,58,129,214,1695,687,473,778,18]},{word:"an",duration:.13,codes:[176,1002,466,827,1138,297,399,1467,1490,1031]},{word:"area",duration:.39,codes:[1295,1811,1215,761,793,1705,1476,632,1501,262,173,225,434,599,146,280,1224,821,1678,280,1801,350,429,231,402,686,212,522,1271]},{word:"of",duration:.49,codes:[705,535,438,261,929,355,1303,1412,1736,1098,1820,1801,1170,1785,1393,1104,1152,1130,1448,1096,1153,1433,1361,19,1380,1752,950,131,465,1613,635,860,277,618,1712,639,1610]},{word:"more",duration:.23,codes:[1779,820,302,1564,1688,1401,74,395,268,683,644,397,1482,397,834,629,332]},{word:"than",duration:.16,codes:[501,1604,607,1755,549,222,1773,300,835,556,593,863]},{word:"seven",duration:.44,codes:[617,1240,1449,1387,202,858,796,844,1519,471,1166,796,543,0,1124,147,768,836,324,361,1350,1824,763,392,1796,684,1698,1091,1790,1371,1670,662,1516]},{word:"hundred",duration:.48,codes:[1810,1640,1741,1689,1540,1355,1723,1282,1171,1794,1651,944,248,1281,535,616,1510,203,1550,678,64,123,551,716,1667,1614,757,1631,617,76,838,653,1769,505,1803,1139]},{word:"zero",duration:.61,codes:[1769,1752,1400,1718,1040,1175,1724,1832,525,1040,352,1034,411,570,825,271,624,87,461,1282,706,877,782,1433,1627,782,1606,778,1436,1817,1256,617,1787,999,1048,1720,1277,1357,1808,1731,1756,328,1518,1061,400,416]},{word:"square",duration:.33,codes:[463,1166,640,1292,659,1277,1429,1285,921,664,148,320,635,1241,1497,147,869,1013,330,1372,1427,1212,1427,1492,878]},{word:"meters",duration:.44,codes:[663,1185,1084,1463,1660,659,682,290,1267,667,1312,428,986,1625,823,1734,999,889,782,809,985,935,243,1281,1449,1476,1109,1638,1002,1542,308,67,927]},{word:"which",duration:1.84,codes:[581,1766,669,1573,824,707,567,551,1038,68,559,1154,445,680,563,235,516,378,275,967,68,513,378,94,516,526,68,1154,223,566,1137,167,717,378,241,967,223,445,1137,167,513,526,241,717,223,275,1137,187,516,316,445,1003,551,1601,1741,257,693,995,5,735,669,729,976,799,171,1589,484,1114,1510,5,1322,633,638,669,562,1114,820,1070,995,1080,832,995,458,957,1634,1157,1003,676,486,1305,169,735,1390,470,795,795,548,1652,169,751,1033,538,1251,651,486,1118,624,681,751,845,735,939,651,1033,1080,1652,1600,1157,981,933,655,838,1076,171,459,548,1327,427,1406,858,87,211,1468,533,1603,96,844,520]},{word:"is",duration:.09,codes:[152,92,47,132,1452,432,631]},{word:"equivalent",duration:.55,codes:[1473,364,522,783,1508,1543,1023,964,1285,1260,1122,1663,495,1710,1392,557,276,389,48,1732,1564,1538,1370,105,1481,443,1533,1770,1019,1041,1102,1494,1247,1388,1637,1736,733,1735,1381,1364,656]},{word:"to",duration:.24,codes:[1748,1082,901,1568,1329,1231,666,1822,486,1305,1813,822,358,368,1823,547,539,775]},{word:"one",duration:.36,codes:[193,126,1717,338,1807,121,807,758,59,395,1321,909,836,690,1741,339,443,623,1542,1230,1357,485,1625,455,317,1826,1282]},{word:"hundred",duration:.44,codes:[1365,1502,1126,1709,1053,1125,1466,1041,1117,1459,1034,955,291,797,1177,1635,1599,197,312,1564,636,1520,1695,1320,1765,959,142,1496,810,926,325,240,1671]},{word:"football",duration:.41,codes:[1379,1807,1313,1681,1788,1355,1825,1088,1337,941,798,1224,806,1450,850,240,1011,627,1033,1779,1532,599,1490,1014,1311,1384,1574,354,264,1758,738]},{word:"fields",duration:.4,codes:[1439,895,1748,715,1535,1034,919,770,1035,36,784,217,380,121,1257,384,1141,385,1258,1312,1732,1820,1605,1724,1812,318,858,28,858,1342]}],n_="en";var o_={text:r_,words:s_,language:n_};const i_="下ネタ、これは少しエッチなこととか少し下品なことですね。彼らですから男の人ですね。",a_=[{word:"xianeta",duration:.75,codes:[651,343,975,1703,1561,1250,1527,176,1568,1450,1287,1375,1238,485,416,1435,1634,521,1068,377,1457,662,265,158,60,149,1424,1810,775,1417,1172,326,1278,961,1753,905,1509,1038,1124,29,1403,1265,910,182,1447,971,1003,1181,630,1719,841,610,142,110,1177,1044]},{word:"kore",duration:.65,codes:[697,841,1429,723,1304,1121,1276,1123,915,1505,693,1162,338,717,1328,674,1367,1227,334,1309,651,964,1223,445,1108,334,612,751,31,458,651,223,670,331,651,1697,1219,1159,149,152,523,794,807,995,934,1205,408,950,868]},{word:"ha",duration:.19,codes:[516,794,1198,1430,1389,261,981,1289,632,1137,1136,951,1277,446]},{word:"shaoshi",duration:.85,codes:[1076,847,1368,1479,1758,761,1043,1076,169,1162,845,967,1486,331,1121,1071,169,1071,538,673,627,445,555,542,1669,1617,1602,1681,1568,1602,1329,863,1439,1495,1523,1244,1461,696,1739,41,978,1058,1156,1189,55,753,1815,1738,1238,749,1059,416,22,1638,749,0,636,176,1600,1690,1431,1774,1172,1172]},{word:"etchi",duration:.67,codes:[1492,1344,1761,707,65,1205,996,1318,1620,1639,879,1432,1255,717,1731,287,936,1346,337,1023,287,1437,642,1421,110,826,1492,1075,1753,1710,1741,1649,1719,1154,1771,591,1289,1553,601,681,859,950,1734,634,415,4,1710,973,1045,1341]},{word:"na",duration:.12,codes:[945,905,1335,1525,1392,321,1216,1172,1264]},{word:"koto",duration:.37,codes:[658,755,1112,693,1344,1006,301,1505,486,1448,1655,744,818,699,1330,510,1487,457,1199,1373,447,1144,606,1824,1253,321,443,238]},{word:"to",duration:.51,codes:[1257,687,723,1096,1443,1092,1199,1277,526,1199,845,1038,1311,68,1065,744,601,1433,612,651,1023,316,1163,458,275,1248,68,633,923,601,566,925,1725,1743,907,93,188,955]},{word:"ka",duration:.37,codes:[1494,91,681,1464,526,1065,381,1080,1651,1402,1065,271,916,1097,1222,1180,1222,1206,1112,997,984,628,1038,408,971,446,1044,1306]},{word:"shaoshi",duration:1.03,codes:[142,813,973,303,811,1517,565,1258,1291,1204,1138,1181,1666,193,1162,568,674,1347,331,1108,1333,334,1397,1683,630,1226,727,869,1438,566,1223,712,670,301,21,1080,686,101,1250,1552,1641,1329,183,1403,1225,85,1010,686,1514,680,763,676,1726,1234,717,93,31,1015,396,1457,1100,867,428,1642,1600,1580,1519,1524,1711,1638,368,1568,867,1753,1179,1645,1317]},{word:"xiapin",duration:.84,codes:[1726,416,1475,286,1372,663,1783,572,936,1684,351,523,1550,458,936,1572,337,534,1299,223,1157,633,316,1413,538,566,591,401,1354,1287,1636,252,143,1647,473,890,828,935,1633,1278,1651,319,1438,1653,1470,1654,634,1259,1528,1450,1513,1641,1424,127,679,1209,310,508,1224,1509,1281,1427,594]},{word:"na",duration:.17,codes:[1497,1103,1133,1401,594,1341,1601,1112,95,1220,743,441,1438]},{word:"koto",duration:.36,codes:[545,1067,931,160,1486,1767,762,1745,594,1499,529,73,709,1457,940,17,1185,1762,378,1181,505,1654,700,424,883,319,868]},{word:"desu",duration:.55,codes:[489,1052,1075,1347,169,1486,670,1148,1464,171,1260,923,54,1071,538,624,1373,54,651,486,285,923,1677,957,1502,1083,1152,1027,1785,1776,1524,1522,1752,1603,1634,1677,1586,1724,1556,1273,1060]},{word:"ne",duration:.17,codes:[729,1800,338,1772,987,449,1624,1761,774,678,789,376,303]},{word:"bi",duration:1.31,codes:[616,1083,1187,1511,1057,1784,1494,240,1291,1079,337,1505,566,301,1499,445,717,1251,285,735,727,168,891,287,54,1346,334,121,933,566,1721,1338,534,1176,54,673,785,464,696,933,331,933,31,275,939,336,676,601,469,686,1428,824,1362,1461,710,1037,490,724,680,316,1142,612,981,727,464,1233,1080,458,676,171,538,287,484,585,31,643,54,31,950,603,445,735,1820,1278,1769,1117,1720,697,1108,441,1621,973,603,609,879,407,708,823]},{word:"ra",duration:.19,codes:[524,1187,1028,1310,1087,1015,1804,1052,847,1423,565,660,1103,393]},{word:"desu",duration:.48,codes:[1356,874,955,1384,1195,1438,727,1201,1289,5,1195,776,1271,1414,336,1121,824,1658,700,492,926,1441,1216,1671,1728,1731,1729,1759,1714,1602,1360,1649,1577,1720,1511,377]},{word:"kara",duration:.25,codes:[1154,1725,151,555,1738,1511,466,294,1140,349,993,1005,777,494,1462,499,797,754,874]},{word:"nan",duration:.32,codes:[386,970,1258,1258,891,1328,1251,627,1318,1045,361,9,1190,239,1534,338,1486,420,121,1308,1307,300,82,724]},{word:"no",duration:.27,codes:[1245,381,1108,1023,555,1111,1033,115,1052,1214,408,322,885,1022,747,724,985,545,1142,535]},{word:"ren",duration:.2,codes:[1055,666,642,603,1468,1598,1412,1091,1519,1820,121,334,1233,1338,1141]},{word:"desu",duration:.36,codes:[1105,1191,962,115,1716,1410,1799,663,1745,1211,1187,1411,1121,1486,1784,1065,1820,450,1739,1691,1578,1738,1685,16,1478,987,405]},{word:"ne",duration:.13,codes:[1486,1240,77,1504,452,1429,1353,1204,1424,1331]}],l_="ja";var d_={text:i_,words:a_,language:l_};const u_="なのに弟が邪魔をしてきます。ねえ、お兄ちゃん遊ぼうよ。ねえ、お兄ちゃん出かけようよ。邪魔をしてきます。なので、全然集中ができません。",c_=[{word:"na",duration:.19,codes:[1176,566,278,584,336,394,601,1403,269,961,1347,1313,466,1352]},{word:"no",duration:.28,codes:[1204,1007,637,1502,984,1264,1690,1240,1078,1316,1051,1227,1780,1509,1670,1767,642,1318,978,1191,1065]},{word:"ni",duration:.32,codes:[1489,794,1506,80,523,565,1656,169,565,287,1047,226,1743,706,1244,532,1010,1698,759,1148,1731,549,1393,1494]},{word:"di",duration:.81,codes:[1462,1200,1743,915,1317,1468,1675,774,1808,1051,1280,1162,301,153,1777,355,1766,1043,1793,1067,259,1780,486,490,1640,316,169,1408,171,633,799,336,692,601,458,981,31,805,603,209,673,638,690,516,474,894,1754,1075,830,923,32,523,1277,27,287,1679,1075,446,149,152,449]},{word:"ga",duration:.55,codes:[13,470,321,259,83,526,95,1042,526,186,883,1037,1388,396,1199,136,405,1684,377,1470,1308,997,1137,236,630,466,1063,1038,768,953,1142,1575,1003,1447,1656,306,826,1178,254,1202,879]},{word:"xiemo",duration:.64,codes:[1256,324,9,1207,1046,1259,658,1647,1196,1194,1179,1200,1264,1059,595,1245,1356,1132,1307,1265,1265,1367,858,1811,1070,1484,78,42,1711,34,362,1821,1261,82,809,892,1267,1497,1156,935,1792,385,935,1368,728,724,339,729]},{word:"o",duration:.12,codes:[1180,994,1324,1189,1136,1137,521,1207,1003]},{word:"shi",duration:.13,codes:[565,1435,1144,319,1599,1400,1296,1818,1739,1595]},{word:"te",duration:.08,codes:[933,1746,1543,910,1297,1328]},{word:"ki",duration:.16,codes:[104,1154,416,86,1096,1418,168,1832,1552,1686,495,660]},{word:"masu",duration:.39,codes:[781,907,316,1235,66,1303,904,1188,1124,1171,978,791,1213,791,1181,565,1137,1226,741,229,1268,1753,1548,719,1615,1821,1466,1413,1038]},{word:"nee",duration:.24,codes:[1421,458,1123,1142,360,1346,771,548,1807,1323,143,1280,1045,852,947,777,1471,781]},{word:"o",duration:.01,codes:[764]},{word:"xiong",duration:.35,codes:[1055,1360,979,660,1179,1028,628,963,1411,829,669,1069,681,655,1097,1714,1043,1492,1136,677,1066,1818,1429,1389,1788,241]},{word:"chan",duration:.24,codes:[1762,1602,101,1374,1431,1132,1309,1203,1178,1197,1477,1105,1063,1204,1391,902,206,1816]},{word:"youbou",duration:.48,codes:[1095,1106,1041,1351,729,1137,1468,1619,1735,1773,274,1749,1454,1192,19,248,1668,1195,1295,1771,490,266,1453,1013,774,1232,839,217,1280,973,1324,942,798,969,1108,818]},{word:"yo",duration:.21,codes:[903,1277,1332,816,743,1254,1308,1633,242,1265,1141,1411,829,1447,829,1399]},{word:"nee",duration:.79,codes:[1192,13,1195,910,983,1275,123,1314,424,1746,569,1417,1172,705,13,1202,1154,446,792,1483,1315,627,1317,226,1193,1505,396,1331,1144,548,1259,674,1489,1489,674,1395,772,1079,1259,630,1226,924,601,1770,360,490,387,119,954,40,1179,1468,1090,1351,1090,1232,1426,1276,1423]},{word:"o",duration:.01,codes:[1089]},{word:"xiong",duration:.28,codes:[1051,1208,1309,1651,1498,1499,1210,1193,1131,1645,1233,887,995,1090,789,1349,1100,1583,829,976,1096]},{word:"chan",duration:.2,codes:[1092,1474,379,1588,1753,1066,19,1184,755,1097,1195,1229,1333,1165,1738]},{word:"chukakeyou",duration:.72,codes:[1451,1526,594,89,1374,1784,1055,1477,1090,202,886,405,1622,1763,624,1761,1144,1122,1254,1203,79,1332,661,1038,1745,1239,717,1279,526,1827,1478,1042,793,386,1685,1153,825,640,887,1215,632,1230,829,1735,965,1421,998,1803,839,1745,839,1770,545,964]},{word:"yo",duration:.23,codes:[1107,1252,459,1227,966,175,1108,1407,1500,1265,1492,661,1223,95,1487,918,359]},{word:"xiemo",duration:.76,codes:[1304,1297,411,967,1196,730,1065,1106,1119,775,825,814,1378,916,548,41,921,1414,1352,338,1277,275,717,1414,612,1123,1092,674,1251,285,486,659,241,1321,151,765,0,1529,1832,1045,1256,1320,1100,353,1314,1817,1392,111,1213,1510,830,1218,327,1131,1126,1682,1113]},{word:"o",duration:.16,codes:[580,353,1265,1298,1671,1022,721,394,982,1690,1803,1324]},{word:"shi",duration:.16,codes:[679,1060,1378,1619,1808,1217,1586,1459,1826,496,1038,1246]},{word:"te",duration:.11,codes:[241,1455,274,1487,63,518,1068,22]},{word:"ki",duration:.17,codes:[924,1717,1070,1736,265,523,1572,766,1786,1478,1497,1460,813]},{word:"masu",duration:.43,codes:[747,1311,1430,1079,1331,1219,698,1131,1029,1772,1100,353,1264,1410,1745,1113,1150,941,1505,1266,1314,416,1634,1298,1609,1669,1331,1578,1713,1766,1557,1739]},{word:"na",duration:.48,codes:[1763,258,1289,762,419,1112,1168,209,1148,1205,54,1328,1699,458,1276,995,905,1367,54,1227,724,235,603,534,31,933,551,68,747,1141,1736,1447,665,913,671,1174]},{word:"no",duration:.17,codes:[1333,1226,1476,1425,1493,114,66,1393,1766,813,111,1347,1466]},{word:"de",duration:.24,codes:[1330,327,729,1382,1e3,984,1403,174,469,1750,35,1746,882,1159,900,6,9,531]},{word:"quanran",duration:1.03,codes:[1027,870,1159,1032,780,1282,376,511,1017,870,1116,1097,844,1196,376,1344,1058,529,1471,1280,1651,1148,1774,1319,1285,1744,20,1504,1729,497,982,546,178,977,1133,440,1320,1017,1112,1082,1303,1022,489,908,1057,724,1317,1826,792,1389,1784,1052,1758,1236,1464,1608,1569,1487,1416,1191,1671,1116,400,934,200,1206,1051,689,764,910,1305,927,998,447,1332,970,1429]},{word:"jizhong",duration:.97,codes:[266,560,1736,149,1204,1646,1172,1298,1806,1127,1457,1106,661,1107,1281,649,1149,1275,387,1792,1439,1561,1496,546,1524,1638,546,1496,1364,328,938,654,1179,1111,1682,1329,202,839,353,454,822,937,40,1364,454,1136,754,362,1428,1701,702,405,1525,445,1154,1608,1654,865,415,888,1600,1102,1277,202,756,894,1622,440,844,737,655,1061,1166]},{word:"ga",duration:.23,codes:[974,655,822,931,80,1433,859,316,1466,1671,547,303,972,973,497,1258,847]},{word:"deki",duration:.49,codes:[1200,1256,524,825,83,705,1122,1216,347,179,260,1187,999,461,1109,1462,761,729,1801,1092,1470,700,718,1381,440,1448,905,1746,119,1065,1176,1145,1587,1819,1087,957,1091]},{word:"mase",duration:.43,codes:[628,1257,284,1351,904,460,1468,728,1108,1076,741,651,339,693,1361,370,905,971,679,1613,1500,1606,1634,1687,1750,1202,1265,1203,1139,318,1129,816]},{word:"n",duration:.13,codes:[1169,1397,245,1126,1154,642,999,961,1742,1542]}],p_="ja";var h_={text:u_,words:c_,language:p_};const m_="全力を尽くしたのなら、結果はどうであれ胸を張っていきましょう。そうすればきっと次に繋がるはずです。",f_=[{word:"quanli",duration:.4,codes:[1007,673,1788,101,1354,1539,1337,1742,137,225,1521,359,189,699,1464,508,1298,1458,1546,1335,78,1251,526,1350,469,1010,295,1174,188,1426]},{word:"o",duration:.27,codes:[254,717,1733,59,151,1305,954,976,1382,1828,1118,367,908,923,138,1218,548,113,1030,674]},{word:"jinkushi",duration:.44,codes:[587,364,1433,1748,1635,544,976,1644,1451,906,22,512,882,1212,1432,1246,1142,1721,1754,927,95,676,2,1210,1189,1647,927,122,319,11,62,1535,1760]},{word:"ta",duration:.08,codes:[686,1805,1237,944,215,1434]},{word:"no",duration:.12,codes:[1203,1127,416,1574,1605,1187,1038,927,270]},{word:"nara",duration:.24,codes:[509,1409,343,98,1632,107,1361,1820,43,1286,1389,1187,1671,380,560,1553,147,1821]},{word:"jieguo",duration:.57,codes:[402,1785,581,200,1769,1278,1612,1293,1343,627,1448,799,1071,1752,406,1380,1305,1016,175,1345,934,508,1439,108,63,518,1019,906,1215,555,976,1114,1185,1809,673,1385,1669,1748,1001,1395,210,1130,215]},{word:"ha",duration:.15,codes:[1199,271,1140,1059,475,717,364,492,1367,215,718]},{word:"dou",duration:.28,codes:[1448,236,660,1511,1717,1783,160,1557,759,1124,248,1287,756,1150,981,215,988,1198,1119,1358,678]},{word:"de",duration:.16,codes:[1415,1245,1173,1043,1604,1602,969,1195,1735,157,1016,388]},{word:"are",duration:.28,codes:[1433,4,466,1695,1313,57,1482,1156,1760,581,205,1747,560,1284,293,1223,1755,277,1066,794,309]},{word:"xiong",duration:.33,codes:[1647,1678,795,1163,1448,712,1803,1694,1023,1652,1465,1262,1280,251,1549,203,954,113,454,36,633,362,1672,1335,1607]},{word:"o",duration:.16,codes:[1247,1172,1342,759,1059,95,1002,1149,695,637,1487,1042]},{word:"zhangtsu",duration:.27,codes:[1136,1323,679,1556,1623,1031,1415,1195,1110,1280,1423,1059,104,1300,1446,696,805,555,1205,1474]},{word:"te",duration:.05,codes:[1641,931,1330,183]},{word:"iki",duration:.2,codes:[552,1557,422,1346,510,983,1608,1390,606,1028,1724,335,546,422,568]},{word:"mashou",duration:.32,codes:[319,134,1674,229,1412,537,1468,1437,1297,1366,198,333,527,276,1395,113,1325,1258,1423,1258,1280,1075,1156,1066]},{word:"sou",duration:1.11,codes:[1202,271,41,450,1305,1157,1652,1824,17,1279,1478,891,1754,1288,1648,1669,1023,1458,1419,939,1707,1157,1648,1707,1163,1458,274,1288,976,1480,824,1322,1231,957,1390,1231,1652,1007,1262,1632,1080,1749,1707,591,1760,1233,1262,1707,659,1652,1652,17,1632,899,933,1489,986,1705,1525,710,1707,591,799,1632,555,1023,1255,1293,1772,1451,1664,1600,399,485,408,1309,106,1120,260,918,88,548,609]},{word:"sure",duration:.28,codes:[626,1147,826,519,1606,1302,1681,1617,1641,1691,1127,860,1264,1223,1574,1367,1105,1135,1183,1286,1031]},{word:"ba",duration:.12,codes:[324,1462,240,1381,1271,1177,282,764,977]},{word:"kitto",duration:.41,codes:[1181,270,870,1584,505,591,691,1495,1568,308,714,1785,1552,234,615,85,858,1353,1562,1699,287,1305,891,513,1639,1728,1353,1400,260,1292,83]},{word:"ci",duration:.4,codes:[1305,221,1707,550,1338,756,1530,1145,1705,659,459,1023,981,1749,1233,636,1363,298,1487,344,152,1341,1615,1721,1582,1221,1740,239,1428,243]},{word:"ni",duration:.15,codes:[1043,1624,1286,612,1493,523,1807,47,1601,47,918]},{word:"jigaru",duration:.52,codes:[293,1767,1578,939,1273,1028,1693,1688,10,863,18,725,1369,91,1580,1712,60,1756,324,992,1764,452,521,843,1635,906,1575,1669,115,42,461,9,471,730,1302,466,1188,1437,637]},{word:"hazu",duration:.21,codes:[1723,1160,1047,793,697,1391,1746,254,1433,1679,1608,634,328,93,964,65]},{word:"desu",duration:.24,codes:[1695,1561,408,967,479,658,1229,1205,474,890,176,1718,440,701,719,782,1724,1313]}],__="ja";var g_={text:m_,words:f_,language:__};const w_="この辺りでは非常に冬、雪が多いために",y_=[{word:"kono",duration:1.84,codes:[866,1242,169,820,16,1071,636,1499,782,1368,701,664,1638,1667,256,1284,231,1411,62,535,1342,24,715,1818,979,1004,945,714,1413,1727,98,730,787,1200,1356,376,475,616,1396,202,1755,1419,1241,1145,714,1490,1683,69,700,735,243,1749,626,67,713,83,1751,927,1499,471,1811,1227,1331,58,1264,1638,1433,696,1246,1331,1034,1079,1738,1370,700,1270,1549,0,767,895,1057,333,1760,1565,1151,406,1016,751,1205,1519,1123,1379,1714,1079,1329,1185,1303,1370,1504,1088,1735,1391,1175,1003,19,1343,169,1465,16,735,1215,1505,1077,1024,951,1824,1422,1509,1053,1805,1266,1262,799,1333,1484,1798,1558,1189,123,1204,120,153,484,1664,286,1150,754,931]},{word:"bianri",duration:.35,codes:[282,777,970,208,179,1032,208,966,121,1007,691,620,1743,1200,467,366,708,39,138,738,431,1034,809,398,966,888]},{word:"de",duration:.09,codes:[845,925,1792,1091,809,750,806]},{word:"ha",duration:.16,codes:[1665,961,1404,959,1761,840,1755,635,639,525,1738,147]},{word:"feichang",duration:.96,codes:[475,1259,147,657,1282,370,876,1432,1822,442,1064,1465,1254,1040,1504,1153,1459,1421,1153,1832,1064,1355,513,1309,1255,673,1360,343,984,1215,1007,1716,1320,1307,328,1402,1332,1037,1308,1349,1742,1438,1091,1775,1091,1214,1663,1642,1282,1503,895,1245,1800,454,1635,34,833,368,844,843,295,102,912,376,47,730,130,63,110,811,1019,2]},{word:"ni",duration:.16,codes:[1218,1240,1388,1387,638,1403,735,1350,202,1443,1554,409]},{word:"dong",duration:1.16,codes:[1175,1427,182,1332,1718,640,548,1319,862,316,1412,924,1223,1091,1079,1735,1215,717,1230,694,624,1273,275,1118,1228,1414,1476,997,1642,1247,58,1286,1565,1402,1436,1816,1477,1024,32,1429,928,1158,1752,584,1172,820,351,1293,625,601,1430,641,516,1383,490,924,1570,651,1639,572,967,1510,603,1418,1293,986,438,696,710,1338,258,1003,1144,712,1276,1803,1421,1129,1668,1720,1697,1013,1651,1697,679,296,1732]},{word:"xue",duration:1.19,codes:[952,1633,6,469,535,510,1618,787,853,1827,409,1485,752,41,1750,555,1118,1242,630,1614,659,1262,1601,696,1360,899,585,1763,487,274,686,287,1176,824,712,1176,1080,957,1338,680,1284,505,566,928,568,1067,786,490,1818,1462,1127,1146,1330,1496,1818,1666,788,1425,1671,1375,1181,1496,1639,1118,333,692,1573,1035,1725,1270,1372,1789,605,191,1680,1434,1483,1554,1787,78,1244,1821,440,947,1777,279,1098,1735,1337]},{word:"ga",duration:.16,codes:[277,465,67,1590,281,1568,1700,82,860,1066,43,660]},{word:"duoi",duration:.4,codes:[324,1072,1129,864,1365,1779,1347,1705,934,1357,1633,613,1555,1015,456,1605,1793,203,488,439,1674,1279,775,214,1639,493,1388,308,1418,319]},{word:"tame",duration:.32,codes:[1528,1666,1238,1746,1832,1536,442,899,1419,1261,1426,1378,1429,1318,1358,1098,1464,1792,1614,921,1677,1404,1245,1519]},{word:"ni",duration:.17,codes:[58,759,1639,1025,1672,633,1315,325,1471,1717,665,1401,1524]}],b_="ja";var M_={text:w_,words:y_,language:b_};const v_=" 아무래도 첫 데이트라 다들 잘 보이고 싶은 것 같은데요. 아직 꽂힌 사람 없다더니. 이렇게 열심히인 걸 보면 속마음은 좀 다른가 봐요.",x_=[{word:"amuraedo",duration:.52,codes:[1707,1788,1072,1484,1325,25,475,456,474,441,1331,1639,1439,214,572,996,1063,1223,208,1492,1070,1117,104,1271,1378,170,1154,245,695,1469,1798,1321,1322,28,1718,467,912,1340,774]},{word:"ceos",duration:.36,codes:[272,890,443,728,682,1732,1271,1596,1658,57,133,1581,864,1246,1817,1451,1822,178,407,1524,1423,797,1318,1397,1438,1725,1730]},{word:"deiteura",duration:.55,codes:[516,1707,1783,513,1687,1822,1324,931,412,714,1101,1105,849,461,1147,1705,510,1421,1655,459,693,1037,957,1572,1829,308,1535,1434,1313,705,1517,898,335,1595,446,531,498,658,29,248,613]},{word:"dadeul",duration:.52,codes:[946,570,560,1324,629,697,1136,1463,827,1647,1455,1404,1514,1421,1418,1721,1770,719,1459,1040,595,1542,868,1107,998,172,1077,317,1819,1319,939,608,1161,1347,282,1133,79,1212,770]},{word:"jal",duration:.24,codes:[749,1616,1624,335,1261,719,1177,1483,347,1438,901,1187,1030,340,1331,635,679,340]},{word:"boigo",duration:.36,codes:[1189,514,802,1352,86,691,1233,913,754,678,1563,182,506,770,69,990,592,775,921,648,712,1525,1829,832,1037,1089,732]},{word:"sipeun",duration:.28,codes:[787,1710,1463,14,384,767,512,1421,1510,1808,1380,1568,1667,1721,947,1393,1792,664,414,756,805]},{word:"geos",duration:.12,codes:[1371,1583,1700,1196,690,813,1650,702,1479]},{word:"gateundeyo",duration:.55,codes:[1525,1623,1332,1330,800,723,354,1731,1628,735,1205,1672,1771,1261,1364,1583,1546,1640,1048,28,1590,530,1828,134,1706,865,1150,1015,1698,361,1563,1726,1272,26,1278,1150,408,1771,764,1542,825]},{word:"ajig",duration:.96,codes:[1107,58,1424,1487,1300,1078,1775,109,1671,1780,1727,1099,1251,1118,1669,1595,1699,1176,729,743,970,1037,878,655,878,1738,1486,347,1801,1397,1329,1736,1059,1495,1433,1130,1118,1289,1037,1231,1478,1811,1298,1502,847,147,248,571,595,705,809,1677,702,1683,1711,22,1364,6,546,1363,1331,1427,1670,1804,1004,527,1671,1267,1585,1792,1832,1724]},{word:"ggojhin",duration:.45,codes:[1704,1623,1474,1595,1478,516,1289,1509,883,1415,682,716,217,1396,555,1717,799,1079,438,923,1007,1832,1166,10,844,62,178,368,1372,1211,1600,1341,184,1558]},{word:"saram",duration:.32,codes:[1071,1498,1657,1775,906,1718,1215,1005,13,497,953,570,522,810,1775,579,1133,498,1060,901,970,1243,1175,932]},{word:"eobsdadeoni",duration:.75,codes:[644,1742,1683,1330,1486,1222,1816,1689,1507,1717,1669,1621,344,1646,1573,1751,1346,1385,799,1010,823,1366,1042,1136,318,1229,326,550,1015,1300,1763,91,1752,1802,1682,1088,818,716,1156,503,1804,1330,1013,924,1294,363,1771,615,1594,1502,1646,1766,949,1312,1655,1783]},{word:"ireohge",duration:1.35,codes:[1584,1545,1768,1811,1267,1640,1782,1488,1388,1762,1828,1520,1396,1593,1605,1284,1339,1657,1769,1540,1605,1709,450,1712,734,1461,1616,1635,1536,1592,1321,325,1771,406,1657,1163,585,1016,17,1390,1693,758,1284,1474,862,1176,1346,426,1293,1338,1713,1346,1284,1176,939,1430,758,1176,1543,1440,862,785,1248,1721,1348,1408,1672,735,1763,1672,624,1525,555,923,1528,1721,519,1368,529,407,1177,50,1708,137,553,1268,186,626,1770,1794,1301,1735,976,1391,1139,1160,1677,479,200,51,1093]},{word:"yeolsimhiin",duration:.44,codes:[49,1103,137,1298,61,181,117,133,181,1819,856,50,844,507,356,1382,166,356,1366,1358,639,1435,1445,1365,1304,202,1270,1056,99,844,1427,1575,57]},{word:"geol",duration:.13,codes:[1299,1516,1399,721,346,600,374,549,1500,583]},{word:"bomyeon",duration:.37,codes:[1765,1626,1724,1737,1656,1149,635,617,1502,935,385,1580,1556,912,780,282,775,1015,695,143,110,532,1138,330,1372,782,1487,703]},{word:"sogmaeumeun",duration:.64,codes:[1333,1783,1315,1754,1673,1667,176,1535,554,1139,1654,1627,1525,959,516,965,957,910,1010,1213,1272,447,1221,1260,1213,1324,565,1121,521,1174,42,768,1149,1230,95,1666,1831,1550,1452,709,1006,329,1640,1485,734,1530,333,1604]},{word:"jom",duration:.13,codes:[50,927,1147,1110,647,1625,1740,481,1811,1784]},{word:"dareunga",duration:.44,codes:[1644,1163,1408,1116,971,872,958,1483,996,400,1281,973,1127,1610,1532,1234,1206,796,1491,317,1501,481,1594,1528,1610,1583,1073,1281,951,1281,1335,1423,1444]},{word:"bwayo",duration:.28,codes:[702,1405,1266,1669,1770,1089,887,1443,1314,1468,966,1087,1059,1436,966,1332,1335,1353,1423,1019,1073]}],T_="ko";var E_={text:v_,words:x_,language:T_};const P_=" 제가 지난 1년간은 거의 다른 향수 안 쓰고 이것만 썼어요. 남편하고 작년에 도쿄 여행 갔다가 시향을 해보고 반한 제품인데",C_=[{word:"jega",duration:.2,codes:[1571,1145,1430,1169,721,529,1307,117,1770,1095,1342,1182,613,657,73]},{word:"jinan",duration:.64,codes:[777,637,1177,1173,604,1202,875,1211,250,661,42,693,1704,1713,1451,1376,1287,767,802,546,1487,1127,502,1317,1554,1065,470,823,65,553,951,857,522,260,433,467,991,860,1105,880,384,880,997,461,1194,648,1079,1541]},{word:"one",duration:.43,codes:[1403,1025,945,779,111,1730,1298,66,1636,470,1452,978,480,1833,674,1740,1450,826,673,1108,259,1157,1067,1775,234,732,117,717,848,1165,1630,882]},{word:"nyeonganeun",duration:.49,codes:[1420,1382,661,1043,367,700,1064,1132,106,1078,1165,1106,1046,1192,1813,1211,1753,987,894,1230,81,248,433,373,1291,290,665,754,923,1638,1062,1452,628,203,47,1742,1698]},{word:"geoyi",duration:.36,codes:[771,150,1802,484,1318,1210,751,1759,1791,1775,1509,1827,922,389,770,953,863,977,133,1518,769,80,201,781,112,34,125]},{word:"dareun",duration:.43,codes:[4,583,189,1207,1540,166,604,721,1594,1623,674,1820,1226,1089,985,1823,1278,1160,996,1454,186,1260,128,322,155,955,793,208,1052,344,1115,281]},{word:"hyangsu",duration:.28,codes:[798,964,1372,581,699,976,579,972,1369,978,1255,1344,629,1401,1831,1641,440,1711,1786,1331,777]},{word:"an",duration:.15,codes:[1210,427,1331,1226,1686,1278,998,970,838,1767,1384]},{word:"sseugo",duration:.36,codes:[1339,1339,1510,1552,1583,1527,1748,1637,1546,1751,1290,34,1664,1794,977,473,1361,804,633,1346,1360,1490,819,17,321,1534,811]},{word:"igeosman",duration:.88,codes:[606,700,511,317,1560,1060,1625,1406,747,729,1425,1433,1619,1239,1294,1545,744,1321,1595,555,1765,1480,751,1740,630,805,1248,601,1321,1768,1007,1655,710,1023,1525,630,1242,1100,840,1460,1400,198,1237,71,1588,1706,590,1720,159,1588,613,288,1457,803,1312,1801,1650,617,970,412,172,294,576,1431,1816,1565]},{word:"sseosseoyo",duration:.4,codes:[1757,1667,1535,1709,1213,864,1066,61,1678,1810,1724,1701,1615,1714,1737,1673,1788,1786,1783,1731,907,411,803,1730,726,9,970,1168,994,905]},{word:"nampyeonhago",duration:.76,codes:[1162,671,516,86,861,957,758,1114,1750,1157,1321,1144,555,1704,1461,591,1623,824,1233,1385,275,584,1045,622,254,329,294,95,430,37,794,912,1806,1746,1231,872,622,707,25,1305,25,1209,802,864,662,1100,1203,535,115,373,1409,1061,1601,1008,130,1308,282]},{word:"jagnyeone",duration:.36,codes:[809,1548,18,1337,1622,1041,1119,913,1005,1267,1723,1799,709,1824,1032,1336,1755,818,1460,1036,1333,1146,1207,328,299,429,1759]},{word:"dokyo",duration:.32,codes:[1707,144,1134,1051,1170,1333,437,1492,698,935,1798,1299,1248,1628,223,1268,1043,1172,769,1774,1114,422,531,1478]},{word:"yeohaeng",duration:.27,codes:[65,316,192,403,1588,991,1200,7,537,390,1103,45,723,1833,407,752,1310,732,1581,1495]},{word:"gassdaga",duration:.44,codes:[1084,1130,955,497,1252,902,58,1096,1405,1346,58,1144,89,578,1137,1437,339,291,123,755,907,790,1330,776,852,1123,1207,1314,958,466,588,1736,1101]},{word:"sihyangeul",duration:.68,codes:[1245,847,809,203,997,721,1344,1040,1040,1135,354,1156,1132,1397,347,797,770,1809,1313,1726,231,1238,1175,1018,1059,368,1061,1565,749,1127,1431,586,577,498,1199,309,1172,147,772,816,336,1450,477,1158,878,498,621,932,344,1082,115]},{word:"haebogo",duration:.21,codes:[353,181,1032,1775,1694,1114,1731,1222,494,1540,1725,1062,1584,1245,991,109]},{word:"banhan",duration:.32,codes:[1740,469,1621,1420,1297,1178,1831,1178,1459,1620,9,1197,1208,1814,1294,1660,1232,904,366,699,1798,282,771,1791]},{word:"jepuminde",duration:.6,codes:[1645,1655,1518,1743,723,592,1173,835,1343,693,459,1739,378,1701,1226,1359,1511,1032,1804,1259,698,1249,1697,1530,1678,1140,1590,421,1489,909,761,1749,1417,1388,1213,663,8,1065,1187,137,723,628,1638,958,1086]}],k_="ko";var $_={text:P_,words:C_,language:k_};const S_=" 명단에 있는 학생들은 실제로 지능이 높지 않았고 무작위로 뽑힌 학생들이었기 때문입니다. 사실을 몰랐던 교사들은",A_=[{word:"myeongdane",duration:.48,codes:[151,1274,1665,1231,205,713,1368,1078,1155,1015,1301,297,1007,297,1765,927,593,1364,653,1664,1613,1563,910,944,847,39,152,248,321,1027,318,1093,146,1745,254,1103]},{word:"issneun",duration:.35,codes:[69,1001,1744,479,1781,536,631,1451,1596,1636,503,41,1214,1417,1286,1824,1069,1366,1690,430,1113,611,658,761,775,1025]},{word:"hagsaengdeuleun",duration:.73,codes:[13,299,607,1633,1447,1756,872,1743,1037,1589,1538,1230,713,1691,980,344,1375,1061,485,1013,1147,979,809,822,1308,783,28,1435,1089,1024,1526,440,98,1093,786,1689,28,787,1175,205,1708,349,763,1326,1120,595,211,1415,579,600,917,178,663,940,776]},{word:"siljero",duration:.92,codes:[678,59,1345,60,1756,776,744,501,762,606,766,227,1011,1157,1080,1669,487,762,1479,227,1305,1248,538,1327,673,696,544,241,1302,1348,1667,919,1707,962,1139,1797,596,1677,767,434,1525,1178,644,1488,305,191,1761,1241,735,785,423,538,1681,943,1250,1061,1088,532,1638,282,575,1342,1002,935,1344,1280,303,108,1286]},{word:"jineungi",duration:.55,codes:[120,143,1700,770,1584,1667,423,1510,1652,231,581,1583,596,1053,1459,769,1225,1825,595,877,750,779,1802,1726,1336,178,614,1651,549,783,1450,882,607,1808,1687,1015,940,1470,543,853,195]},{word:"nopji",duration:.4,codes:[1731,856,1654,559,1538,1796,1069,1825,876,1463,32,443,1408,1218,1764,287,538,1760,1359,566,1631,1313,1035,543,788,24,1317,1620,263,1312]},{word:"anhassgo",duration:.41,codes:[222,282,958,816,800,221,361,573,1509,864,578,374,958,1541,467,1110,1063,1013,1410,1010,151,676,256,559,1293,1831,1454,1401,319,225,217]},{word:"mujagwiro",duration:1.41,codes:[326,1789,1347,1554,1255,861,1246,334,624,1595,445,1080,1273,458,1319,567,241,975,538,496,417,94,325,538,151,765,285,1362,673,401,975,445,1242,275,391,862,445,975,633,551,325,487,766,933,673,1652,824,567,1623,555,799,1428,603,899,799,566,1151,287,420,401,1352,686,567,458,343,1672,1524,1272,1683,1346,836,1830,1346,376,1078,1805,1674,817,938,1,471,536,1280,1171,1344,254,367,102,116,1161,745,1781,363,1782,999,1330,232,318,536,1366,1493,583,1394,83,946,890]},{word:"bbobhin",duration:.45,codes:[1674,1684,401,316,986,379,1474,1401,1453,217,1014,557,1217,1218,1249,727,199,171,795,31,325,1236,1556,854,1726,1827,128,1637,455,769,831,882,177,1221]},{word:"hagsaengdeulieossgi",duration:1.03,codes:[355,1416,1701,709,1636,1639,1239,1448,1309,1752,1135,1794,1238,1160,1786,1031,1796,676,878,1737,849,10,1349,817,911,1226,684,206,970,682,308,994,1081,962,1833,506,1022,1302,1467,968,1710,903,364,268,1004,677,1802,232,443,949,796,1217,575,1403,248,1811,657,1686,992,1753,1121,285,1176,1246,1793,561,31,325,119,265,796,1680,750,55,645,983,527]},{word:"ddaemunibnida",duration:.64,codes:[203,581,681,1798,766,223,1262,337,337,1528,1416,657,549,1399,741,581,1056,364,617,1696,1379,961,425,1434,1410,617,1748,989,326,1370,1212,593,1225,898,1590,1422,514,154,711,1488,1644,1433,1136,339,1001,1245,1103,1668]},{word:"sasileul",duration:1.91,codes:[1203,814,1421,1203,355,1397,1193,91,1481,484,585,899,391,345,257,241,20,187,20,692,224,16,187,851,360,224,544,187,23,360,209,16,187,23,509,94,311,94,194,417,187,311,285,23,417,94,311,360,72,417,187,311,285,194,417,187,311,285,72,417,187,311,360,23,544,187,23,285,224,417,187,311,285,224,417,94,851,445,194,16,204,851,287,209,694,285,16,765,209,1151,285,311,257,224,281,445,3,1244,288,820,1293,896,231,895,527,714,1088,782,1238,719,1330,756,164,291,425,346,841,611,254,841,429,276,1088,1587,340,1519,398,1139,248,1598,375,1693,593,1241,346,443,482,384,154,768,783,37,546]},{word:"molrassdeon",duration:.65,codes:[1663,272,1482,1513,720,1069,368,870,757,214,856,556,1498,539,1221,253,898,617,631,1457,472,57,206,424,462,768,382,1506,1419,866,601,680,566,401,1510,1691,364,994,217,790,583,182,579,770,1394,1766,564,1374,1820]},{word:"gyosadeuleun",duration:.67,codes:[444,1439,1375,482,1828,1592,1411,605,1828,1423,653,1807,1690,557,1625,1286,116,1607,1253,1607,654,990,884,1247,1506,1073,248,302,656,88,1372,639,591,1538,1354,374,1147,383,716,1781,609,456,927,664,1285,1345,1301,1674,1114,1780]}],I_="ko";var O_={text:S_,words:A_,language:I_};const F_=" 며칠 후, 화가난 부자에게 그림을 보여주었다. 기다리던 그림을 받은 부자는 너무나 기뻐하며 그림을 보았다.",D_=[{word:"myeocil",duration:.32,codes:[561,27,1809,1516,268,479,181,657,407,711,642,18,1449,1609,18,790,135,206,780,1389,628,543,1616,506]},{word:"hu",duration:.08,codes:[1351,595,211,1625,532,29]},{word:"hwaganan",duration:1.07,codes:[1311,1388,682,1435,1323,1373,1063,1594,1746,1684,1765,1716,548,301,1121,735,1348,710,601,1719,457,465,636,1555,691,986,765,1536,227,824,1244,169,459,704,548,1214,136,1181,707,396,929,1730,1648,1276,1023,676,627,1550,1774,1500,1688,1468,961,705,271,339,587,565,112,320,1180,1650,1608,1267,547,452,386,407,1823,63,282,472,245,380,876,1590,1345,1048,184,1263]},{word:"bujaege",duration:.57,codes:[1575,787,1770,1084,1267,1826,1092,193,765,1715,985,430,1382,1493,1272,184,268,182,455,1712,541,399,45,678,864,430,660,276,1073,466,263,1136,759,178,1581,1617,1711,930,407,768,557,190,45]},{word:"geurimeul",duration:.48,codes:[600,79,45,599,326,1238,895,936,1703,624,516,736,1492,948,790,1389,637,1596,245,882,515,198,143,395,479,262,1663,742,1026,1591,218,600,289,49,621,112]},{word:"boyeojueossda",duration:.59,codes:[124,1812,1285,1681,1649,1804,1492,952,48,47,683,143,616,886,546,303,1618,1734,1217,358,882,1439,621,1674,1113,1081,864,1770,234,1160,1622,766,1654,1422,1711,275,287,1781,547,1498,76,1143,1200,1330]},{word:"gidarideon",duration:1.96,codes:[1117,1629,1829,1197,1224,1276,1506,1721,1038,223,1108,670,727,1142,762,1246,1273,458,694,696,275,686,287,417,465,275,704,696,606,325,538,401,766,54,1242,487,487,862,391,257,795,275,1151,287,401,325,275,1242,712,360,1016,54,1151,257,445,1570,559,401,1016,534,686,585,606,325,54,704,387,360,325,487,606,1016,534,704,567,765,862,445,975,274,534,686,824,538,1244,54,1390,585,487,1623,567,585,1016,566,325,766,287,1390,54,274,1244,538,1242,986,680,862,566,1293,995,1288,784,1375,694,1474,1278,581,1027,592,934,107,780,1728,1692,1588,135,116,152,153,945,137,1544,152,189,1420,736,1669,1554,1407,756,135,614,536,46,1497,748,319,807]},{word:"geurimeul",duration:.39,codes:[1350,1351,1620,820,1783,1481,604,1278,979,1645,157,529,429,213,1518,1733,263,181,280,500,911,1778,1335,211,433,315,357,983,536]},{word:"badeun",duration:.25,codes:[1567,1756,1382,791,341,682,107,536,1334,1522,1633,521,200,2,1599,1493,1004,1612,1368]},{word:"bujaneun",duration:.52,codes:[1542,1594,197,949,1444,1293,1273,1721,1247,782,1395,1611,1252,1537,1341,268,1753,1018,836,654,10,1287,282,456,1519,300,853,1439,1251,844,291,1287,430,374,1336,1830,1751,917,1750]},{word:"neomuna",duration:.92,codes:[521,1023,1257,239,1819,1464,1481,1454,1406,1479,250,313,758,1486,1436,572,259,669,832,301,869,163,1028,717,523,1168,470,1305,1305,470,1168,717,967,1164,396,1367,1343,681,1282,584,1123,1466,1465,1440,766,1408,1782,920,125,200,609,934,1004,1077,123,945,1520,1503,127,98,303,1340,1732,52,95,429,100,1281,100]},{word:"gibbeohamyeo",duration:.52,codes:[903,29,344,1683,1011,1500,328,340,473,104,557,104,1549,1564,1114,1142,936,1578,1810,775,940,664,268,13,112,289,65,488,29,1416,815,1290,1485,455,51,488,79,687,1161]},{word:"geurimeul",duration:.44,codes:[794,569,214,297,716,1273,1428,603,1799,1075,1814,650,1492,1497,110,143,324,350,1620,384,1217,903,863,1729,515,803,1492,1690,725,153,575,1646,1696]},{word:"boassda",duration:.32,codes:[758,1642,1468,1437,53,1369,95,1397,753,560,1355,1708,1639,1262,603,1289,68,975,1300,1073,179,1126,1252,1206]}],L_="ko";var z_={text:F_,words:D_,language:L_};const B_="食道癌等等。二十二种重大疾病的话不仅可以报销,还可以享受到额外最高十万元的大病补助。第二个就是报销比例之前一七年那版的时候。",R_=[{word:"shidao",duration:.63,codes:[962,1375,1459,11,1735,1139,1061,1671,796,1375,1500,889,1752,1370,527,1642,890,1222,1308,1678,1051,1022,1762,1100,143,1323,158,1281,1106,1781,1727,1269,101,855,1201,446,1066,826,115,1271,497,1309,221,818,1149,1200,524]},{word:"ai",duration:.21,codes:[1183,721,1399,956,1356,880,1222,393,1095,370,942,1247,552,873,1457,1403]},{word:"deng",duration:.27,codes:[955,753,1471,1499,1740,776,1080,1512,1642,996,871,1063,1345,1731,1501,1409,1506,904,1301,1807]},{word:"deng",duration:.48,codes:[261,1707,633,1142,1614,301,1262,933,986,1338,121,939,1792,566,899,1474,799,1157,659,762,377,1609,1423,1407,550,130,756,1044,794,1017,1698,382,1196,840,1108,1358]},{word:"twenty",duration:.44,codes:[1071,1385,1348,509,1771,171,334,563,984,1245,573,934,390,1038,461,477,1064,1247,477,1037,519,1772,943,788,1735,962,1637,701,176,977,1038,1235,613]},{word:"two",duration:.08,codes:[1106,1328,565,1111,879,441]},{word:"zhongzhong",duration:.48,codes:[841,826,422,1159,1099,1437,883,1696,1529,1586,1240,1202,1443,1494,894,1433,998,1490,1489,86,1087,1152,1779,59,1246,784,906,1119,1402,1757,876,130,1762,1353,982,905]},{word:"da",duration:.09,codes:[1800,728,663,1791,1492,797,963]},{word:"jibing",duration:.43,codes:[1183,1060,1110,1198,1078,992,1822,1619,1428,1571,784,634,1783,1229,771,1544,801,32,1596,1630,414,1550,805,892,826,1078,1345,1137,965,567,1312,987]},{word:"de",duration:.08,codes:[1545,1706,909,1245,818,1494]},{word:"huabu",duration:.59,codes:[1483,591,1683,1273,795,1601,925,1103,883,1001,819,1501,1143,1258,998,1200,1640,1504,929,345,1385,939,939,1153,1003,1556,1303,1003,1404,957,1118,1809,1262,1114,1273,680,1273,1262,765,1655,1071,825,856,737]},{word:"jinke",duration:.29,codes:[856,1456,1825,1563,1350,917,489,1464,1217,1124,250,1281,80,1792,1659,1299,1160,1400,1322,679,801,594]},{word:"yi",duration:.15,codes:[1287,759,690,322,1563,1797,1460,427,671,428,1136]},{word:"baoxiao",duration:.45,codes:[437,1323,659,17,1555,420,659,1666,260,819,1505,847,718,655,466,982,1525,1518,1737,554,415,1565,884,906,1356,42,466,978,797,879,446,826,1180,446]},{word:"haike",duration:.6,codes:[1165,1333,1686,633,964,1478,957,1282,1385,1714,19,1465,1434,1738,1648,1117,1705,1448,1611,680,1279,1246,606,1380,633,1130,1153,1823,1196,1324,549,997,819,1280,782,1256,1612,414,1500,1436,1752,1500,1022,302,225]},{word:"yi",duration:.11,codes:[982,1376,1364,1501,197,909,834,789]},{word:"xiangshou",duration:.44,codes:[447,882,1111,495,1518,1549,1376,731,736,1758,9,1198,711,1264,1630,955,1317,1167,1710,1339,1821,10,176,788,1720,973,690,40,1521,910,732,864,963]},{word:"dao",duration:.2,codes:[1826,1239,450,1439,589,1131,764,871,1277,660,594,907,1129,580,1487]},{word:"ewai",duration:.37,codes:[1169,1158,1782,1118,1358,1063,1087,1792,1344,908,621,86,705,832,753,675,594,1755,58,1281,1047,757,518,819,1171,512,1177,110]},{word:"zuigao",duration:.36,codes:[720,353,1685,1685,928,34,906,1210,1501,1140,1111,428,1638,969,770,60,1619,1697,1475,1127,818,1368,291,1044,1272,1162,1306]},{word:"ten",duration:.27,codes:[1326,1339,1649,736,1088,308,1774,962,1146,1738,1061,495,640,713,1774,321,130,1697,1670,1252]},{word:"wan",duration:.16,codes:[779,936,907,1137,412,1119,1106,142,1268,699,772,1166]},{word:"yuan",duration:.19,codes:[825,644,754,1600,1431,594,864,1065,806,1118,903,908,1373,1773]},{word:"de",duration:.09,codes:[728,845,973,1063,1087,382,1275]},{word:"dabing",duration:.4,codes:[1124,1747,343,712,686,939,1097,642,934,580,130,1197,1088,874,492,531,1790,1555,1246,933,1505,913,489,893,1546,1830,894,40,1811,1488]},{word:"buzhu",duration:.31,codes:[663,1676,64,505,377,1294,1076,828,1417,729,1060,1555,776,933,1290,654,1078,1065,1317,29,942,149,1596]},{word:"di",duration:.49,codes:[992,1463,1802,1144,1803,710,287,1428,1157,1716,1130,923,1714,1230,516,1059,1799,1199,1412,513,1223,1327,513,1668,377,735,758,1080,939,710,509,1657,1726,1202,1665,441,836]},{word:"two",duration:.12,codes:[1168,260,1208,1220,248,1183,1201,1169,1197]},{word:"gejiu",duration:.39,codes:[76,880,531,656,390,1046,1228,1280,988,1545,734,813,864,1501,774,116,472,916,328,1379,1425,1597,15,1077,1100,1218,1202,1296,1736]},{word:"shi",duration:.13,codes:[1312,1267,1750,11,554,1057,1532,1127,621,130]},{word:"baoxiao",duration:.39,codes:[1808,1581,5,1614,436,696,1086,294,754,996,632,594,892,897,984,175,1624,1580,4,1624,1207,1385,446,492,735,524,879,1078,1060]},{word:"bili",duration:.32,codes:[712,1740,1266,1614,1123,1308,940,1052,834,1375,1668,1825,1360,1304,1285,1234,1581,1700,894,1518,836,735,877,1287]},{word:"zhi",duration:.4,codes:[982,945,1652,1251,1669,504,1003,1404,624,1404,1306,751,1410,1465,1079,1496,751,1803,1474,651,1525,986,680,1527,1580,756,1333,521,405,860]},{word:"qian",duration:.24,codes:[1078,1137,577,1636,1547,1552,368,93,674,57,477,753,1232,1064,117,798,395,1295]},{word:"one",duration:.12,codes:[717,1713,705,898,325,628,717,47,1436]},{word:"seven",duration:.31,codes:[955,639,1086,1106,973,1617,1783,1664,1580,1565,0,1513,788,233,298,1477,1193,1361,1166,1457,1115,188,1499]},{word:"nian",duration:.2,codes:[1599,580,1663,1486,1366,466,908,759,1106,609,879,886,825,188,1776]},{word:"na",duration:.09,codes:[1759,1365,120,982,1403,1139,759]},{word:"ban",duration:.2,codes:[675,1311,1018,1109,272,1692,959,149,573,1187,1263,1089,1541,1424,1766]},{word:"de",duration:.12,codes:[1697,1414,1084,1757,832,1001,1801,942,0]},{word:"shihou",duration:.39,codes:[1014,1779,749,1734,1082,750,1738,746,1600,713,1820,1253,982,1353,1260,1257,1462,1049,1794,1103,1775,992,1224,1017,1022,942,1081,1484,994]}],N_="zh";var j_={text:B_,words:R_,language:N_};const U_="近日,阿里全资收购饿了么的消息掀起了不小浪花。据称三个月内,阿里将按照九十五亿的价格收购饿了么全部股份。",W_=[{word:"jinri",duration:.32,codes:[1536,1246,939,1703,1704,930,253,18,372,794,616,689,656,1440,51,1024,406,946,889,1572,1268,999,982,1104]},{word:"ali",duration:.72,codes:[1611,727,1390,442,1142,795,1352,1130,1279,1007,1059,1348,1495,1495,1419,1170,1667,1432,1040,1751,1395,1434,1751,1098,1777,1817,1177,1118,1397,869,1510,1638,538,861,1174,997,321,173,83,271,159,520,106,520,236,609,1686,863,1589,1726,263,700,1472,528]},{word:"quan",duration:.31,codes:[1281,645,1762,157,459,1534,231,633,1667,62,1351,232,769,239,927,1499,535,443,330,1471,746,787,1540]},{word:"zishou",duration:.4,codes:[1518,1497,994,1709,1570,1660,543,1376,1300,1217,1382,98,688,376,780,1823,1800,366,1340,358,499,713,609,871,576,725,934,148,455,1286]},{word:"goue",duration:.29,codes:[1675,1508,1672,1548,1790,1001,443,352,716,1660,210,1540,1308,1131,1740,1749,288,1721,1812,755,853,152]},{word:"le",duration:.16,codes:[1060,143,665,779,191,57,184,1019,1784,1041,374,1720]},{word:"mede",duration:.23,codes:[303,1829,1236,92,744,1081,868,1204,1032,1056,599,859,1242,1399,1144,1113,384]},{word:"xiaoxi",duration:.4,codes:[1804,821,1800,62,356,1451,10,1325,1731,535,475,1053,210,1804,306,779,1823,93,1472,788,949,26,780,0,24,556,1519,844,902,932]},{word:"xianqi",duration:.4,codes:[253,1741,1401,1139,1668,1833,919,1422,340,308,1270,556,1823,65,1365,305,825,701,1136,1233,1439,1388,652,1283,1364,24,1379,1175,1434,1249]},{word:"le",duration:.12,codes:[346,1810,1393,1148,1048,218,797,1803,1047]},{word:"bu",duration:.12,codes:[1718,986,220,1322,1812,1651,1252,503,1708]},{word:"xiaolang",duration:.4,codes:[1720,36,1605,276,863,350,335,1718,997,1072,1111,969,1105,1801,1743,1484,716,1705,716,860,1304,446,1317,107,1201,1323,1661,1294,1152,1465]},{word:"hua",duration:.19,codes:[1801,1810,1375,1532,1710,1637,1599,1726,1109,1804,210,491,1174,115]},{word:"ju",duration:.73,codes:[411,1117,565,225,1309,1212,240,1322,710,487,1033,740,744,1121,17,1108,1754,261,1037,899,5,1028,624,1305,1130,805,1134,1496,1749,1153,1788,1797,1329,1478,1074,1355,1738,833,1255,591,1338,534,1408,820,986,1262,1302,805,308,1,556,357,302,570,1476]},{word:"cheng",duration:.27,codes:[1431,135,312,888,1007,1535,135,592,318,1261,1304,1370,422,1008,1450,467,917,1748,1462,1236]},{word:"three",duration:.56,codes:[1747,265,861,957,606,923,964,27,1668,1130,476,1211,976,572,1367,1255,891,1130,799,1211,1011,1266,1658,1568,1441,400,18,368,943,848,9,1192,140,371,155,192,738,1591,1022,1456,713,1710]},{word:"geyue",duration:.2,codes:[1251,282,138,671,315,631,804,1777,357,134,1814,100,804,162,1234]},{word:"nei",duration:.24,codes:[157,599,946,890,1626,807,1832,138,900,270,1420,635,687,383,1200,1400,178,102]},{word:"ali",duration:.41,codes:[1808,715,1301,1073,888,391,1793,1142,567,1385,1437,339,699,557,393,73,1792,25,871,1457,81,671,1296,57,1157,1452,597,1030,1451,318,702]},{word:"jiang",duration:.37,codes:[47,980,301,1409,14,1787,1009,1742,157,1528,1246,1724,335,335,7,1308,969,1143,1194,711,791,200,158,312,1649,1173,1315,1466]},{word:"an",duration:.17,codes:[900,824,1815,1456,1235,339,520,408,1156,846,901,835,634]},{word:"zhao",duration:.2,codes:[1449,1439,1299,1679,461,1079,142,755,1129,1207,1068,725,1180,1369,1677]},{word:"ninety",duration:.28,codes:[1821,975,767,493,592,262,1422,382,116,1713,123,1651,229,197,1004,1671,437,1335,1447,1625,299]},{word:"five",duration:.27,codes:[206,595,366,164,1088,371,1401,856,143,1409,917,355,906,1062,1625,1732,1545,1607,832,1472]},{word:"yide",duration:.25,codes:[753,1450,758,47,760,1794,1350,1615,7,1762,57,232,1819,1695,1710,1737,53,989,152]},{word:"jiage",duration:.36,codes:[1379,1409,1527,1518,10,69,944,1115,966,1143,1424,1197,339,607,1125,303,944,1622,1756,1543,1614,1054,1647,1663,969,971,952]},{word:"shou",duration:.31,codes:[47,1671,1590,467,1668,961,1279,1406,979,218,1382,366,782,769,1206,1726,142,703,1633,359,1756,408,1595]},{word:"goue",duration:.32,codes:[1413,1538,1511,825,58,321,775,942,1243,286,1122,1464,1745,939,287,1037,401,1831,1499,1533,892,611,217,577]},{word:"le",duration:.17,codes:[1089,1141,1462,461,341,1524,95,1755,1581,234,1174,1032,903]},{word:"me",duration:.12,codes:[1542,1593,1764,729,1463,847,1218,1312,1183]},{word:"quanbu",duration:.39,codes:[1726,1125,1045,1708,731,686,178,340,1325,434,788,1680,1429,498,269,65,516,1345,1058,1503,1535,1006,1756,1737,1340,1335,932,348,1124]},{word:"gu",duration:.19,codes:[1445,1622,1377,950,27,1536,1794,1816,1251,1755,1291,1610,1815,1049]},{word:"fen",duration:.28,codes:[888,923,1433,1771,1740,1436,231,719,999,1642,1637,1156,1204,1275,882,1235,1471,1355,1675,387,438]}],V_="zh";var G_={text:U_,words:W_,language:V_},ga={en:{male_1:Hf,male_2:Yf,male_3:t_,male_4:o_,female_1:Rf,female_2:Wf},ja:{male_1:M_,female_1:d_,female_2:h_,female_3:g_},ko:{male_1:O_,male_2:z_,female_1:E_,female_2:$_},zh:{male_1:G_,female_1:j_}};const Jh=10,m1=100,np=1e3,op=1e6,ip=1e9,ap=1e12,lp=1e15,K_=9007199254740992,up=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],H_=["zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];function q_(Me){return Me>Number.MAX_SAFE_INTEGER||Meup[parseInt(U,10)]).join(" ");return j+" point "+ee}return j}function bn(Me){let v,s;return Me<20?(v=0,s=up[Me]):Me",this.eos="<|im_end|>",this.special_tokens={audio_code:"<|{}|>",text_start:"<|text_start|>",text_end:"<|text_end|>",audio_start:"<|audio_start|>",audio_end:"<|audio_end|>",time:"<|t_{:.2f}|>",code_start:"<|code_start|>",code_end:"<|code_end|>",text_sep:"<|text_sep|>"},this.text_prompt=`{bos} {text_start}{words}{text_end} {audio_start} `,this.map_audio_tokens=this.get_audio_token_map(),this.languages=s}get_audio_token_map(){const v=new Map;for(let s=0;s<4100;++s){const _=this.tokenizer.encode(this.special_tokens.audio_code.replace("{}",s),{add_special_tokens:!1})[0];v.set(BigInt(_),s)}return v}process_text(v,s){if(!this.languages.includes(s))throw new Error(`Language ${s} not supported, supported languages are ${this.languages}`);if(s!=="en")throw new Error("Non-English languages are not supported yet.");return v=v.toLowerCase().replace(/\d+(\.\d+)?/g,_=>X_(Number(_))).replace(/[-_/,\.\\]/g," ").replace(/[^a-z\s]/g,"").replace(/\s+/g," ").trim(),v.split(" ")}create_audio_prompt(v){return v.map(s=>{const _=s.word,A=this.special_tokens.time.replace("{:.2f}",s.duration.toFixed(2)),j=s.codes.map(ee=>this.special_tokens.audio_code.replace("{}",ee)).join("");return`${_}${A}${this.special_tokens.code_start}${j}${this.special_tokens.code_end}`}).join(` `)}get_completion_prompt(v,s,_=null){let A=this.process_text(v,s);_!==null&&(_.language!==s&&console.warn(`Speaker language ${_.language} does not match text language ${s}`),A=this.process_text(_.text,_.language).concat(A)),A=A.map(ee=>ee.trim()).join(this.special_tokens.text_sep);let j=this.text_prompt.replace("{bos}",this.bos).replace("{text_start}",this.special_tokens.text_start).replace("{words}",A).replace("{text_end}",this.special_tokens.text_end).replace("{audio_start}",this.special_tokens.audio_start);return _!==null&&(j+=this.create_audio_prompt(_.words)),j}extract_audio_from_tokens(v){const s=[];for(const _ of v){const A=this.map_audio_tokens.get(_);A&&s.push(A)}return s}}class Y_{constructor(v){this.wavtokenizer=v,this.sr=24e3}async decode(v){v=new Df("int64",v,[1,v.length]);const{waveform:s}=await this.wavtokenizer({codes:v});return s}}class J_{constructor(v){this.model=v}async generate(...v){return(await this.model.generate(...v)).tolist()[0]}}class Z_{constructor({model_path:v="onnx-community/OuteTTS-0.2-500M",language:s="en",tokenizer_path:_=null,languages:A=[],verbose:j=!1,device:ee=null,dtype:U=null,additional_model_config:b={},wavtokenizer_model_path:T=null,max_seq_length:M=4096}={}){this.model_path=v,this.language=s,this.tokenizer_path=_,this.languages=A,this.verbose=j,this.device=ee,this.dtype=U,this.additional_model_config=b,this.wavtokenizer_model_path=T,this.max_seq_length=M}}class e0{constructor({audio:v,sr:s}){this.audio=v,this.sr=s}to_wav(){if(this.audio.dims.length!==2||this.audio.dims[0]!==1)throw new Error(`Unsupported audio shape, expected [1, num_samples], got ${this.audio.dims}`);const v=this.audio.data,s=this.sr;let _=44;const A=new ArrayBuffer(_+v.length*4),j=new DataView(A),ee=(U,b,T)=>{for(let M=0;Ms+Object.keys(_).length,0);console.log(` === ALL AVAILABLE SPEAKERS ===`),console.log(`Total: ${v} speakers across ${Object.keys(ga).length} languages`),console.log("-".repeat(50));for(const[s,_]of Object.entries(ga)){console.log(` ${s.toUpperCase()} (${Object.keys(_).length} speakers):`);for(const A of Object.keys(_))console.log(` - ${A}`)}console.log(` To use a speaker: load_default_speaker(name) `)}load_default_speaker(v){const s=this.language.toLowerCase().trim();if(!(ga[s]&&ga[s][v]))throw new Error(`Speaker ${v} not found for language ${s}`);return ga[s][v]}prepare_prompt(v,s=null){const _=this.prompt_processor.get_completion_prompt(v,this.language,s);return this.prompt_processor.tokenizer(_,{add_special_tokens:!1})}async generate({text:v,speaker:s=null,temperature:_=.1,repetition_penalty:A=1.1,max_length:j=4096,additional_gen_config:ee={}}){const U=this.prepare_prompt(v,s);this.config.verbose&&(console.log(`Input tokens: ${U.input_ids.dims}`),console.log("Generating audio..."));const T=(await this.model.generate({max_length:j,temperature:_,repetition_penalty:A,do_sample:!0,...ee,...U})).slice(U.input_ids.dims[1]),M=await this.get_audio(T);return this.config.verbose&&console.log("Audio generation completed"),new e0({audio:M,sr:this.audio_codec.sr})}};const dp=Object.freeze({.2:{tokenizer:"onnx-community/OuteTTS-0.2-500M",sizes:["500M"],links:["https://huggingface.co/onnx-community/OuteTTS-0.2-500M"],languages:["en","ja","ko","zh"],hf_interface:t0,max_seq_length:4096}});function r0(Me){if(!(Me in dp))throw new Error(`Unsupported model version '${Me}'. Supported versions are: ${Object.keys(dp)}`);return dp[Me]}function s0(Me,v){if(!Me)throw new Error("max_seq_length must be specified.");if(Me>v)throw new Error(`Requested max_seq_length (${Me}) exceeds the maximum supported length (${v}).`)}async function n0({model_version:Me,cfg:v}){const s=r0(Me);v.tokenizer_path=v.tokenizer_path||s.tokenizer;const _=s.languages;if(!_.includes(v.language))throw new Error(`Language '${v.language}' is not supported by model version '${Me}'. Supported languages are: ${_}`);v.languages=_;const A=s.hf_interface;return s0(v.max_seq_length,s.max_seq_length),await A.load(v)}let om=!1;try{const Me=await navigator.gpu.requestAdapter();if(!Me)throw new Error("WebGPU is not supported (no adapter found)");om=Me.features.has("shader-f16"),self.postMessage({status:"feature-success"})}catch(Me){throw self.postMessage({status:"feature-error",data:Me.toString()}),Me}const o0=new Z_({model_path:"onnx-community/OuteTTS-0.2-500M",language:"en",dtype:om?"q4f16":"q4",device:"webgpu"}),Zh=await n0({model_version:"0.2",cfg:o0});self.postMessage({status:"ready"});self.addEventListener("message",async Me=>{const{text:v,speaker_id:s}=Me.data,_=s==="random"?null:Zh.load_default_speaker(s),j=(await Zh.generate({text:v,temperature:.1,repetition_penalty:1.1,max_length:4096,speaker:_})).to_wav("output.wav"),ee=new Blob([j],{type:"audio/wav"});self.postMessage({status:"complete",audio:URL.createObjectURL(ee),text:v})});